Post

Data Types and Variables

In Java, a variable is a container that holds data during the execution of a program. A data type specifies the type of value a variable can hold.

Data Types and Variables

1. Primitive Data Types

Java has 8 primitive data types:

TypeSizeDescriptionExample
byte1 byteWhole number (small range)byte a = 100;
short2 bytesWhole numbershort b = 500;
int4 bytesWhole number (default)int x = 1000;
long8 bytesVery large whole numberlong l = 900000000L;
float4 bytesDecimal number (less precise)float f = 3.14f;
double8 bytesDecimal number (more precise)double d = 3.14159;
char2 bytesA single characterchar c = 'A';
boolean1 bittrue or falseboolean b = true;

2. Reference Data Types

These store references to objects:

  • Arrays
  • Strings
  • Classes
  • Interfaces
1
2
String name = "John";
int[] scores = {90, 85, 78};

3. Variable Declaration

You must declare a variable before using it:

1
2
3
// <dataType> <variableName> [assign = <value>];
int age;          // Declaration
age = 25;         // Initialization

You can also do both at once:

1
int age = 25;

4. Naming Rules <variableName>

  • Must start with a letter, _ or $.
  • Can contain letters and digits.
  • Case-sensitive (age ≠ Age).
  • Use camelCase for convention: studentScore.

Code Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class DataTypeDemo {
    public static void main(String[] args) {
        // Primitive types
        int age = 30;
        double salary = 45000.50;
        char grade = 'A';
        boolean isEmployed = true;

        // Reference types
        String name = "Alice";
        int[] scores = {80, 85, 90};

        // Output
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: $" + salary);
        System.out.println("Grade: " + grade);
        System.out.println("Is Employed: " + isEmployed);
        System.out.println("Scores: " + scores[0] + ", " + scores[1] + ", " + scores[2]);
    }
}

Output:

1
2
3
4
5
6
Name: Alice
Age: 30
Salary: $45000.5
Grade: A
Is Employed: true
Scores: 80, 85, 90
This post is licensed under CC BY 4.0 by the author.