Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assignment Operator and wrappers

 
Sid Robin
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How come in the above code Boolean and "(b1 = false)" are being accepted ? Please explain . I was expecting a equals operator in place of '='
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes its possible. All you need to remember the result of an expression within if, while, do while, for constructs must be a boolean.
Hence if you have
boolean b1 = false;
if((b1=true)) {System.out.print("Test");}
Here b1 will be assigned false and the output will be Test.
Also with Java 1.5
Boolean b1 = false;
if((b1=true)) {System.out.print("Test");}
will also work, Here b1 will be autoboxed to false during initialization and in the if statment true will be assigned to b1 via autoboxing and then its unboxed to boolean true and the result is "Test".
Hope this clears.
Thanks
Deepak
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Siddu,

This is valid because of Java 1.5's autoboxing feature. Essentially, the compiler will automatically convert wrapper objects (Integer, Double, Boolean, etc) to their corresponding primitives (int, double, boolean) in most places where they're used. The same holds for converting primitives to wrapper objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic