Data Types in Java | What are the different Data Types in Java?



In Java, a data type is a classification of the type of data that a variable can hold. 

Java has two types of data: primitive and non-primitive.


Primitive data types include:


int: This data type is used to store integers (whole numbers) with a minimum value of -2^31 and a maximum value of 2^31-1.


int age = 30;
int year = 2020;
 


float: This data type is used to store decimal numbers with a single precision (32-bit).


float temperature = 23.5f;
float pi = 3.14f;
 


double: This data type is used to store decimal numbers with double precision (64-bit).


double weight = 65.23;
double salary = 100000.00;
 


char: This data type is used to store a single character (a letter, a number, or a symbol) enclosed in single quotes.


char grade = 'A';
char gender = 'M';
 


boolean: This data type can only hold the values true or false.


boolean isStudent = true;
boolean isMorning = false;
 


byte: This data type is used to store 8-bit integers.


byte age = 30;
byte b = 100;
 


short: This data type is used to store 16-bit integers.


short s = 32000;
short distance = 25;
 


long: This data type is used to store 64-bit integers.


long l = 100000;
long salary = 2000000;
 




Non-primitive data types include:


String: This is a class in Java used to store and manipulate strings of characters.


String name = "John Doe";
String address = "New York, USA";
 


Arrays: This data type is used to store a collection of variables of the same data type.


int[] numbers = new int[5];
String[] names = {"John", "Jane", "Mike"};
 


Classes: Classes are templates for creating objects, which are instances of a class.


MyClass obj = new MyClass();
Student student = new Student();
 


Interfaces: Interfaces define a set of methods that a class must implement, but do not provide implementations for those methods.


List<String> list = new ArrayList<>();
Queue<Integer> queue = new LinkedList<>();
 


Enumerations: Enumerations are used to define a set of named values.


enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
Days day = Days.MONDAY;
 


It is important to use the appropriate data type for a variable to ensure that the variable can hold the expected value and to prevent errors. 

Post a Comment

Post a Comment (0)

Previous Post Next Post