Variable Default Values
Java class variables have default values. Let us experiment with that.
Learning Objectives
- Understanding the default values of java class variables.
Source Code
|
Run Output
Code Understanding
class VarDefaultValues
{
static byte b; static short s; static int i; static long l;
static char c; static double d; static float f; static boolean bool;
All the 8 types of primitive data types have been defined as class/static variables without any initialisation
public static void main(String[] args)
{
System.out.println(“Default value of byte “+b);
System.out.println(“Default value of short “+s);
System.out.println(“Default value of int “+i);
System.out.println(“Default value of long “+l);
Default values of integer types byte,short,int and long is 0.
System.out.println(“Default value of char “+c);
Of character type it is ‘u0000’ which is basically the null character of ascii code. This would be unprintable.
System.out.println(“Default value of double “+d);
System.out.println(“Default value of float “+f);
For decimal types float and double it is 0.0.
System.out.println(“Default value of boolean “+bool);
And for boolean type it is false.
}
}
Notes
- The default value of local variables is not automatically set and they have to be initialised or assigned to be used in any expression of the program.
- The documentation of primitive types with default value explanation can be referred at
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Suggested Filename(s): VarKinds.java
sunmitra| Created: 20-Mar-2018 | Updated: 20-Mar-2018|