Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Object assignment doubt.  RSS feed

 
Sandeep Sundaram
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main(String[] a){
Boolean str = Boolean.FALSE;
Boolean str1 = str;
str1 = Boolean.TRUE;
System.out.println(str);
}

In this code, i was expecting an output 'true', but got 'false'. Please educate me. Same result when i tried with String

public static void main(String[] a){
String str = "true";
String str1 = str;
str1 = "false";
System.out.println(str);
}
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
str and str1 are not objects, they are references to objects.
So

At this point str refers to a Boolean object whose value is false


str1 now also refers to the same Boolean object that str refers to


str1 now refers to a different Boolean object whose value is true, but str is still referring to the first Boolean object with value false


str still refers to the first Boolean object, so prints false
 
Sandeep Sundaram
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! Joanne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!