Java: tracing activity: explain how this code produced the following output (bas
ID: 3667227 • Letter: J
Question
Java: tracing activity: explain how this code produced the following output (basically just talk about what is happening during each part of the code):
when the code is run in Eclipse:
1 public class Main 2 public static void main(String[] args) ( int x = 3, y = 4; System.out.printIn(x % y + " " + x / y); 4 5 6 System.out.printIn(x % y + " " + x / y); System.out.println(x y); 9 10 public static void m1() 1 12 13 14 15 16 17 int x 12, y = 5; System.out.printIn(x % y + '. " + x / y); x += 20 y += x - 10; System.out.println(x y);Explanation / Answer
Here is the code along with explanation as comments.
public class Main
{
public static void main(String[] args)
{
int x = 3, y = 4; //1. Assigns 3 to x, and 4 to y.
System.out.println(x%y+" "+x/y); //2. When x divided by y, Prints the value of the reminder, followed by a space then the quotient. Therefore 3 0.
m1(); //3. Calls the method m1, and the control moves there.
//Note that, when switched back to main(), the value of x is 3, and the value of y is 4.
//All the variables are local variables. Therefore the variables x, y declared here in this function with values 3, and 4
//will live only in main(). The same happens there, which means x, y declared there in that function with values 12, and 5
//will live only in m1(). There is no relation between these 2 functions, and the variables with same names, even they are in the same class.
System.out.println(x%y+" "+x/y); //9. When x divided by y, Prints the value of the reminder, followed by a space then the quotient. Therefore 3 0.
System.out.println(x + y); //10. The sum of x and y is printed. Therefore 3 + 4 = 7, will be printed.
//Here the execution comes to an end.
//Therefore line 2 prints 3 0 first.
//Then line 5 prints 2 2.
//Then line 8 prints 59.
//Then line 9 prints 3 0 again.
//Then line 10 prints 7 finally.
//Hence the output is justified.
}
public static void m1()
{
int x = 12, y = 5. //4. Assigns 12 to x, and 5 to y.
System.out.println(x%y+" "+x/y); //5. When x divided by y, Prints the value of the reminder, followed by a space then the quotient. Therefore 2 2.
x += 20; //6. 20 is added to the value of x. Therefore x becomes 32.
y += x - 10; //7. x - 10, i.e., 32 - 10 = 22 will be added to y. Therefore y becomes 27.
System.out.println(x + y); //8. The sum of x and y is printed. Therefore 32 + 27 = 59, will be printed.
//Then the control moves back to main method, and continues.
}
}
If you still have any queries, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.