System.out.println(); solution thanksss 1 l public class Sample Class 3 private
ID: 3839594 • Letter: S
Question
System.out.println(); solution thanksss
1 l public class Sample Class 3 private int x; 5 public Sampleciass this .x 0; 9 public Sampleciass (int x) this .x x; 10 11 12 13 public int getx. return this 14 15 16 17 public void set (int x this .x x; 18 19 21 public static void alter (Sampleciass instance instance x 2; 1 Sample Class instance1 new Sample Class 2 Sample Class instance2 new Sample Class (5) 3 Sample Class instance3 new Sample Class (10) 4 Sample Class instance4 new Sample Class (3) 5 Sample Class instance5 new Sample Class (1) 6 instance 3.setx(instance getx. instance2.getx. 7 Sample Class. alterx Cinstance4 8 instance 5.set (27) 1. Give the value of instancel.getX 2. Give the value of instance2.getx0 3. Give the value of instance3.getX0 4. Give the value of instance4.getX 5. Give the value of instance5.getX0Explanation / Answer
Execution and output:
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
instance1.getX()=0
instance2.getX()=5
instance3.getX()=15
instance4.getX()=6
instance5.getX()=27
sh-4.3$
instance1.getX() = 0
Explanation:
The constructor SampleClass() is called because there is no argument passed while creating an object which initializes the value of x to 0. Thats why when getX() is called using instance1() the value returned is zero.
instance2.getx() = 5
Explanation:
The constructor SampleClass(5) is called when instance2 is created because the argument is passed which initializes the value to 5. Thats why when getX() is called using instance2() the value returned is 5
instance3.getX() = 15
Explanation:
instance3 object when initially created will have the value 10 but when instance3 called again(instance3.setX(instance3.getX() + instance2.getX());) it sets the value to 15 because instance3.getX() returns 10 and instance2.getX() is 5 as mentioned above.
instance4.getX() = 6
Explanation:
instance4 object is initially set to 3 when instance4 object is created but when the alter method is called(SampleClass.alterX(instance4)) the value of instance4 which is 3 is multiplied to 2. Thats why the result is '6'
instance5.getX() = 27
Explanation:
instnace5 object initially when created has the value set to 1 but when instance5.setX(27); is called the value is set to 27. Thats why the final value is 27
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.