File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assignment Operator and wrappers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assignment Operator and wrappers" Watch "Assignment Operator and wrappers" New topic

Assignment Operator and wrappers

Sid Robin
Ranch Hand

Joined: Nov 24, 2007
Posts: 53

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

Joined: Aug 05, 2006
Posts: 637
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.

Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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.

SCJP 5.0
I agree. Here's the link:
subject: Assignment Operator and wrappers
jQuery in Action, 3rd edition