Sunday, 15 July 2012

Java Data Types Default Values – No Garbage


Java does not support garbage values. An unassigned local variable gives compilation error and an instance (global) variable takes a default value. Following program illustrates the default values given by JVM for unassigned instance variables.

String is not a data type. If not assigned, String takes null as the default.


public class DataTypeDefaults
{
   byte byteValue;  
   short shortValue;  
   int intValue;  
   long longValue;  
   float floatValue;  
   double doubleValue;  
   char charValue;
   boolean booleanValue;  
   String stringValue;

   public static void main(String args[])
   {
      DataTypeDefaults dtd = new DataTypeDefaults ();
      System.out.println("byte default value: " + dtd.byteValue);
      System.out.println("short default value: " + dtd.shortValue);
      System.out.println("int default value: " + dtd.intValue);
      System.out.println("long default value: " + dtd.longValue);
      System.out.println("float default value: " + dtd.floatValue);
      System.out.println("double default value: " + dtd.doubleValue);
      System.out.println("char default value: " + dtd.charValue);
      System.out.println("boolean default value: " + dtd.booleanValue);
      System.out.println("String default value: " + dtd.stringValue);
   }
}




Observe the screenshot. The default values for whole numbers is 0, for floating-point numbers is 0.0 and for primitive data type boolean it is false. String takes null and char does not print any value. Actually, it prints a value equivalent to Unicode value of /u0000 which prints nothing.







No comments:

Post a Comment

There was an error in this gadget