JAVA - Zero to Hero / Java Fundamentals

Variables and Data Types

❔ What is a Variable?

  • A variable is a container that holds data used in a program.

  • In Java, all variables must be declared with a data type.

int age = 20;

🎛️Variable Declaration Syntax

dataType variableName = value;

Example:

int score = 100;
double temperature = 36.6;

You can also declare multiple variables of the same type:

int x = 10, y = 20, z = 30;

🏷️ Types of Variables

Type

Scope/Use

Local

Inside methods/blocks

Instance

Part of an object (non-static)

Static

Belongs to the class (shared)

🔣 Primitive Data Types

Java has 8 built-in (primitive) data types:

Type

Size

Example

Description

byte

1 byte

byte a = 100;

Small integer (-128 to 127)

short

2 bytes

short s = 5000;

Larger than byte

int

4 bytes

int x = 123456;

Standard whole number

long

8 bytes

long l = 123456L;

Very large numbers

float

4 bytes

float f = 4.5f;

Decimal with less precision

double

8 bytes

double d = 9.99;

Decimal with more precision

char

2 bytes

char c = 'A';

Single character

boolean

1 bit

boolean b = true;

true/false


🆕 Type Conversion

Implicit (Widening Conversion)

Automatically done by Java when converting a smaller type to a larger one:

int a = 10;
double b = a; // OK: int → double

❌ Explicit (Narrowing Conversion)

Manually done using casting. Risk of data loss.

double x = 5.8;
int y = (int) x;  // y = 5

Example:

public class TypeConversionMini {
    public static void main(String[] args) {
        int a = 5;
        double b = a;               // Implicit
        int c = (int) 6.8;          // Explicit
        int d = Integer.parseInt("10"); // String to int
        String e = String.valueOf(20);  // int to String

        System.out.println(b + " " + c + " " + d + " " + e);
    }
}
5.0 6 10 20