-3

Why the object of wrapper classes like Boolean etc. direct takes value without initialization but property of object is not allowed?
Code:

class TestByte{ 
   public static void main(String[] a) { 
      Byte b=125; System.out.println(b);
   }
}
Bo.
  • 2,547
  • 3
  • 24
  • 36
  • 2
    I don't see anything which is not allowed in your example. Can you give an example of what you mean? – Peter Lawrey Jun 14 '12 at 07:14
  • Your question is not obvious at all! and you don't have to write the whole question in the title and write only code in the body! – adranale Jun 14 '12 at 07:14
  • http://stackoverflow.com/questions/501653/java-whats-the-difference-between-autoboxing-and-casting has something you might be concerned with. – Vijay Shanker Dubey Jun 14 '12 at 07:15

2 Answers2

0

do you mean why can you use methods without throwing a NullPointerException from a wrapper class object just by using Byte b = 25 instead of explicitly initializing the Byte object as Byte b = new Byte(25)??

Well, if you DID meant that, its because ever since java 1.5 assigning values to Wrapper references can be done without explicitly instantiating the object. This is called Auto-Boxing, Which implicitly creates the wrapper objects instance and assigns it with the value.

Such that: Byte b = 25 its the same as Byte b = new Byte(25). There are a few differences with the boxing version that influence the result comparing Wrapper values by reference if you assign a value in the range of a byte.. but well that is a whole different thing xD..

Ed Morales
  • 1,027
  • 5
  • 9
0

Well Abhishek, the purpose of contructors to initialize objects is to do any preparation work to get that object live. Since wrapper classes and String hold only data, the only preparation to inialize them is to provide them necessary values. So, we actually don't need to call new for them.

Ahmad
  • 2,110
  • 5
  • 26
  • 36