?
Determine output:
Determine output:
public class Test{
int a = 10;
public void method(int a){
a += 1;
System.out.println(++a);
}
public static void main(String args[]){
Test t = new Test();
t.method(3);
}
}
public class Test{
int a = 10;
public void method(int a){
a += 1;
System.out.println(++a);
}
public static void main(String args[]){
Test t = new Test();
t.method(3);
}
}
Answer & Solution
Correct Answer:
Option
B
Here's an explanation of the code:
1. The class
2. The
3. Inside the
4. The value of the local variable
5. The value of the local variable
6. The value of the local variable
7. In the
8. The
9. This triggers the execution of the
Therefore, the output of the code is 5. Thus, option B is the correct answer.
1. The class
Test is defined with an instance variable a initialized to 10.2. The
method method is defined within the Test class, which takes an integer parameter a.3. Inside the
method method, the local variable a shadows the instance variable a because they have the same name.4. The value of the local variable
a is incremented by 1 using the += operator, making it 4.5. The value of the local variable
a is then incremented again using the pre-increment operator ++, making it 5.6. The value of the local variable
a (which is 5) is printed using System.out.println().7. In the
main method, an instance of the Test class is created.8. The
method method is invoked on the t object with the argument 3.9. This triggers the execution of the
method method, which prints 5 as explained above.Therefore, the output of the code is 5. Thus, option B is the correct answer.
Join the Discussion
Login to post a comment or share your explanation.
Loginint a = 10;
public void method(int a){
a += 1;
System.out.println(++a);
}
public static void main(String args[]){
Test t = new Test();
t.method(3);
}
}
Hey, here main is calling method with object reference t by passing the value 3, so method will calculate the value of a, because a+=1; can be written as a=(int)(a+1), so here method receiving 3 in a and will calculate the value and will assign to a is nothing but a=(int)(3+1), i.e nothing but 4, and its increasing the value of a by using pre increment operator, so it will increase first from 4 to 5 then it will print 5.
public class Test
{
int a = 10;
{
a += 1;
System.out.println(++a);
}
public static void main(String args[])
{
Test t = new Test();
}
}
if your code as same above then it will print 12.
Thank you.
2) static block
3) static method ( public static void main()) in this example.
Control goes to 3rd one..
t.method(3)
Hence a value become 3.
Control not goes to int a = 10.
first the original input a is 3 then a+=1 operation is performed on a which is calculated as a=a+1 so now a =3+1 =4 and then at the print statement ++a is to be printed so in ++a operation first value of a is incremented by 1 and then it is printed so answer is 5