Java is rich in its data type.
Data type tells the type of data, that you are going to store in memory.
It gives the information that which operations that may be performed on it.
The Java programming language supports eight primitive data types.
A primitive type is predefined by the language and is named by a reserved keyword.
Primitive values do not share state with other primitive values.
The eight primitive data types supported by the Java programming language are:
Data Type | Size | Default Value (for fields) |
---|---|---|
boolean | 1 bit | false |
char | 2 byte | '\u0000' |
byte | 1 byte | 0 |
short | 2 byte | 0 |
int | 4 byte | 0 |
long | 8 byte | 0L |
float | 4 byte | 0.0f |
double | 8 byte | 0.0d |
public class DefaultValuesTest{
//(instance/non-static variable) primitive data type
byte b;
short sh;
int a;
long l;
float f;
double d;
char ch;
boolean bool;
// (class/static variable) primitive data type
static int x;
// class type (reference variable)
String s;
void showValues(){
System.out.println("Default Value of bye, b is :"+b);
System.out.println("Default Value of short, sh is :"+sh);
System.out.println("Default Value of int, a is :"+a);
System.out.println("Default Value of long, l is :"+l);
System.out.println("Default Value of float, f is :"+f);
System.out.println("Default Value of double, d is :"+d);
System.out.println("Default Value of char, ch is :"+ch);
System.out.println("Default Value of boolean, bool is :"+bool);
System.out.println("Default Value of static int, x is :"+x);
System.out.println("Default Value of non-primitive String, s is :"+s);
}
public static void main(String [] args){
DefaultValuesTest ob = new DefaultValuesTest();
ob.showValues();
}
}
OUTPUT
Default Value of bye, b is :0 Default Value of short, sh is :0 Default Value of int, a is :0 Default Value of long, l is :0 Default Value of float, f is :0.0 Default Value of double, d is :0.0 Default Value of char, ch is : Default Value of boolean, bool is :false Default Value of static int, x is :0 Default Value of non-primitive String, s is :nullTips :
There are only two values for boolean data type either true or false, and cannot replace it with 1 or 0.
Default values are for fields, not for local variables.
The compiler never assigns a default value to an uninitialized local variable. make sure to assign it a value before you attempt to use it.
public class LocalDefaultValueTest{
public static void main(String [] args){
int x; // local varaible
System.out.println("Value of local variable x :"+x);
}
}
OUTPUT
LocalDefaultValueTest.java:5: error: variable x might not have been initialized System.out.println("Value of local variable x :"+x); ^ 1 error
Accessing an uninitialized local variable will result in a compile-time error.
Default value for reference variable is null.