Variables and datatypes in java
Variables are containers that store data in a program. Every variable has:
Type → What kind of data it can store (number, text, etc.)
Name → Identifier for the variable
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 Type | Example | Description |
| int | 100 | Stores whole numbers |
| float | 3.14f | Stores decimal numbers (single precision) |
| double | 3.14159 | Stores decimal numbers (double precision) |
| char | 'A' | Stores a single character |
| boolean | true / false | Stores true or false values |
| byte | 10 | Stores small integers |
| short | 1000 | Stores small integers |
| long | 100000L | Stores 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);
}