Skip to main content

Command Palette

Search for a command to run...

Variables and datatypes in java

Updated
2 min read

Variables are containers that store data in a program. Every variable has:

  1. Type → What kind of data it can store (number, text, etc.)

  2. Name → Identifier for the variable

  3. Value → The actual data stored

Syntax for Variable

dataType variableName = value;

  • dataType → int, double, char, String, etc.

  • variableName → name you give to the variable

  • value → data you assign

Example

public class Main {

public static void main(String[] args) {

int age = 20; // integer variable

String name = "Preethika"; // text variable

System.out.println("Name: " + name);

System.out.println("Age: " + age);

}

}

Data Types

A data type specifies what kind of data a variable can store. Java has two main types of data types.

1.Primitive Data Types

2.Non – Primitive Data Types

Primitive Data Types

Data TypeExampleDescription
int100Stores whole numbers
float3.14fStores decimal numbers (single precision)
double3.14159Stores decimal numbers (double precision)
char'A'Stores a single character
booleantrue / falseStores true or false values
byte10Stores small integers
short1000Stores small integers
long100000LStores large integers

Non-Primitive Data Types

These are more complex types, like:

  • String → Stores text

  • Arrays → Store multiple values of the same type

  • Classes → User-defined objects

Example

public class Main {

public static void main(String[] args) {

int age = 25;

double salary = 55000.50;

char grade = 'A';

boolean isPassed = true;

String name = "Preethika";

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Salary: " + salary);

System.out.println("Grade: " + grade);

System.out.println("Passed: " + isPassed);

}