Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Assignment Operator and wrappers

 
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 '='
 
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
 
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.
 
Hoo hoo hoo! Looks like we got a live one! Here, wave this tiny ad at it:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic