1. Will the following code compile, and if not, which line or lines will cause a
ID: 3919329 • Letter: 1
Question
1. Will the following code compile, and if not, which line or lines will cause a compile error?
Line 1: public void myMethod() {
Line 2: int sum = 0;
Line 3: while (i<3) {
Line 4: sum += i;
Line 5: System.out.println("i = " + (i++));
Line 6: }
Line 7: System.out.println(sum);
Line 8: }
Line 4 and 7 have errors.
Line 6 has an error.
Lines 3, 4, and 5 have errors.
Line 1 has an error.
There are no compile errors - it will compile correctly.
2.
What will be the value of total after the following code is executed?
int total = 4;
int myVariable1 = 12;
int myVariable2 = 7;
if (myVariable1 > myVariable2) {
myVariable1 += myVariable2;
total+= myVariable1;
}
else {
myVariable2 += myVariable2;
total+= myVariable2;
}
3.
What will the value of myVar be after the following statements are executed?
int myVar = 0;
myVar = 13 / 4;
switch (myVar)
{
case 4:
myVar += 5;
break;
case 3:
myVar -= 5;
break;
default:
myVar *= 3;
}
Line 4 and 7 have errors.
2.Line 6 has an error.
3.Lines 3, 4, and 5 have errors.
4.Line 1 has an error.
5.There are no compile errors - it will compile correctly.
Explanation / Answer
Q1. Will the following code compile, and if not, which line or lines will cause a compile error?
Line 1: public void myMethod() {
Line 2: int sum = 0;
Line 3: while (i<3) { // Variable i is not declared previously
Line 4: sum += i;
Line 5: System.out.println("i = " + (i++));
Line 6: }
Line 7: System.out.println(sum);
Line 8: }
ANS: Variable i is not declared previously
3) Lines 3, 4, and 5 have errors.
Q2) What will be the value of total after the following code is executed?
int total = 4;
int myVariable1 = 12;
int myVariable2 = 7;
if (myVariable1 > myVariable2) {
myVariable1 += myVariable2; // myVariable1 = myVariable1 + myVariable2 = 12 + 7 = 19
total+= myVariable1; // total = total + myVariable1 = 4 + 19 = 23
}
else {
myVariable2 += myVariable2;
total+= myVariable2;
}
ANS : total = 23
Q3) What will the value of myVar be after the following statements are executed?
int myVar = 0;
myVar = 13 / 4; // myVar = 3
switch (myVar) //
{
case 4:
myVar += 5;
break;
case 3: // Comes in this case because myVar = 3
myVar -= 5; // myVar = myVar - 5 = 3 - 5 = -2
break;
default:
myVar *= 3;
}
ANS : myVar = -2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.