DEV Community

Subash
Subash

Posted on

Data Types in Java

What is a Data Type?

A data type tells Java what kind of value a variable can store, such as numbers, decimal values, characters, or text.

Every variable in Java must have a data type before we can use it.

Example:

int age = 25;
String name = "John";
double salary = 25000.50;
Enter fullscreen mode Exit fullscreen mode

Types of Data Types in Java

Java data types are divided into two categories:

  1. Primitive Data Types
  2. Non-Primitive Data Types

1. Primitive Data Types

Primitive data types are the basic data types available in Java. They store simple values directly.

Java provides eight primitive data types.

Integer Types:

Data Type Size Description
byte 8 bits Small whole numbers
short 16 bits Short-range integers
int 32 bits Commonly used for integers
long 64 bits Large whole numbers

Floating-Point Types:

Data Type Size Description
float 32 bits Decimal values
double 64 bits More precise decimal values

Other Types:

Data Type Size Description
char 16 bits Stores a single character
boolean JVM-dependent Stores true or false

Example:

int age = 25;
long population = 8000000L;

float price = 99.5f;
double salary = 25000.75;

char grade = 'A';
boolean isPassed = true;
Enter fullscreen mode Exit fullscreen mode

Default Values of Primitive Data Types

When primitive variables are declared as class fields without assigning values, Java provides default values.

Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false

2. Non-Primitive Data Types

Non-primitive data types are used to store references to objects rather than directly storing simple values.

Some common examples are:

String

A String is used to store a sequence of characters (text).

String name = "Java";
Enter fullscreen mode Exit fullscreen mode

Array

An array is used to store multiple values of the same data type in a single variable.

int[] numbers = {10, 20, 30, 40};
Enter fullscreen mode Exit fullscreen mode

Class and Object

A class is a blueprint used to create objects. An object is an instance of a class.

Creating a Class:

class Student {
    String name;
    int age;
}
Enter fullscreen mode Exit fullscreen mode

Creating an Object:

Student s1 = new Student();

s1.name = "John";
s1.age = 22;
Enter fullscreen mode Exit fullscreen mode

Here, Student is the class, and s1 is the object created from that class.

Default Value of Non-Primitive Data Types

The default value of a non-primitive reference variable is null when declared as a class field without an assigned value.

Example:

class Student {
    String name;
    int age;
}
Enter fullscreen mode Exit fullscreen mode

Here, the default value of name is null, and the default value of age is 0.

Note: Java provides default values for class fields, but local variables must be initialized before they are used.

Top comments (0)