+ 3

Java classes

class TestClass{ int number; void testMethod(TestClass t) { t.number=25; System.out.println("Inside the Testclass, test method "+ t.number); } } public class Main { public static void testMethod(int number) { number = 25; System.out.println("Inside the testMethod "+ number ); } public static void main(String[] args) { //scenario 1 int number=45; testMethod(number); System.out.println("Inside the main method "+ number); //scenario 2 TestClass t=new TestClass();//object initialization t.number=45; t.testMethod(t); System.out.println("Inside the Main Method "+t.number); } } In the second scenario println part why does it get printed as 25 but not 45? What happens there?

21st Feb 2021, 1:37 PM
okurpants
okurpants - avatar
8 Respuestas
+ 3
You have created a class TestClass that has a method 'testMethod' which accepts an object of TestClass. You're always assigning the variable of the object that will be passed to the method, the value 25. Back in the 'Main' class you you created an instance of TestClass and then assigned its number variable the value 45. But on the next line, you passed the object itself as the argument to the function 'testMethod'. Now if you recall, your method defined in TestClass always assigns the value 25 to the object being passed. As a result, you get the value as 25. And also, this has got nothing to do with inner classes?
21st Feb 2021, 1:47 PM
Soumik
Soumik - avatar
+ 2
♨ Soumik 🎶 thanks alot sorry typo turned into inner-classes i guess
21st Feb 2021, 3:29 PM
okurpants
okurpants - avatar
+ 2
okurpants Welcome :)
21st Feb 2021, 3:29 PM
Soumik
Soumik - avatar
+ 2
♨ Soumik 🎶 also what's the difference between scenario 1 and scenario 2? i just want to confirm if my logic is correct
21st Feb 2021, 3:40 PM
okurpants
okurpants - avatar
+ 2
okurpants In the 1st scenario, you're using the method of the 'Main' class. It accepts an int as parameter. Remember that java is pass by value, that is, you can't change the value of a primitive data type directly through a method (you can do this only for reference types). So even though you change the value of the parameter in the function, the original value still remains the same, 45.
21st Feb 2021, 3:45 PM
Soumik
Soumik - avatar
+ 2
In the 2nd case, you pass a object or in other words, a reference to the object. As mentioned before, you CAN change values or attributes of reference data types like arrays, lists etc. So you can easily change the value of variable of the object
21st Feb 2021, 3:49 PM
Soumik
Soumik - avatar
+ 2
♨ Soumik 🎶 thank you so muchhhhh was a great help
21st Feb 2021, 3:51 PM
okurpants
okurpants - avatar
+ 2
okurpants No problem! 🤗
21st Feb 2021, 3:52 PM
Soumik
Soumik - avatar