DEV Community

Bala Murugan
Bala Murugan

Posted on

Data types in java

what is variable :

A variable is a container used to store data in memory during program execution.

It helps programmers store, update, and manipulate values in a program.

Each variable has:

  • a datatype
  • a variable name
  • a value

Example in Java:

int age = 21;

Here:

  • int → datatype
  • age → variable name
  • 21 → value

Variables are important because they allow dynamic data handling and calculations in programming.

Types of Datatypes:

Primitive Datatypes
Non-Primitive Datatypes

  1. Primitive Datatypes:

    Primitive datatypes are predefined datatypes provided by Java.

There are 8 primitive datatypes:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean
Example:

int age = 21;
double salary = 45000.50;
char grade = 'A';
boolean isPassed = true;

Enter fullscreen mode Exit fullscreen mode

2.Non-Primitive Datatypes:

Non-primitive datatypes are user-defined or reference datatypes.

Examples:

  • String
  • Arrays
  • Classes
  • Objects

Example:

String name = "Bala";

Why do we use Datatypes?

Datatypes are used to define the type of data a variable can store.

They help the programming language understand:

  • what type of value is stored
  • how much memory should be allocated
  • what operations can be performed on the data

For example:

  • int is used for integer values
  • double is used for decimal values
  • char is used for single characters
  • boolean is used for true or false values

Example:

int age = 21;
double salary = 45000.50;

Using datatypes improves memory management, program efficiency, and data accuracy.

Example Program:

public class Main {

Enter fullscreen mode Exit fullscreen mode

public static void main(String[] args) {

byte age = 21;

short year = 2026;

int marks = 450;

long population = 8000000L;

float height = 5.8f;

double salary = 45000.75;

char grade = 'A';

boolean isPassed = true;

System.out.println("Age: " + age);
System.out.println("Year: " + year);
System.out.println("Marks: " + marks);
System.out.println("Population: " + population);
System.out.println("Height: " + height);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + isPassed);
Enter fullscreen mode Exit fullscreen mode

}


}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)