Java Basics

Java Data Types

Understand Java's type system — primitive data types, reference types, type casting, and how to choose the right type for your data.

What are Data Types?

Data types specify what kind of data a variable can hold and how much memory it occupies. Java is a statically-typed language — every variable must have a declared type.

java
int age = 25;            // integer number
double salary = 75000.50; // decimal number
char grade = 'A';         // single character
boolean active = true;    // true or false
String name = "Arjun";    // text (reference type)

Java data types are divided into two categories:

  1. Primitive Types — Built-in, store actual values
  2. Reference Types — Store memory addresses (objects, arrays, strings)

Primitive Data Types

Java has 8 primitive data types:

TypeSizeRangeDefaultExample
byte1 byte-128 to 1270byte b = 100;
short2 bytes-32,768 to 32,7670short s = 30000;
int4 bytes-2¹⁻ to 2³¹-1 (~2.1 billion)0int i = 100000;
long8 bytes-2⁶³ to 2⁶³-10Llong l = 99999999L;
float4 bytes~7 decimal digits0.0ffloat f = 3.14f;
double8 bytes~15 decimal digits0.0ddouble d = 3.14159;
char2 bytes0 to 65,535 (Unicode)'\u0000'char c = 'A';
boolean1 bit*true or falsefalseboolean b = true;

Integer Types

java
public class IntegerTypes {
    public static void main(String[] args) {
        byte smallNum = 127;            // -128 to 127
        short mediumNum = 32000;        // -32,768 to 32,767
        int regularNum = 2_000_000;     // Underscores for readability
        long bigNum = 9_999_999_999L;   // Note the 'L' suffix

        System.out.println("byte: " + smallNum);
        System.out.println("short: " + mediumNum);
        System.out.println("int: " + regularNum);
        System.out.println("long: " + bigNum);
    }
}

Output:

byte: 127
short: 32000
int: 2000000
long: 9999999999

Tip: Use underscores (_) in numeric literals for readability: 1_000_000 instead of 1000000.

Floating-Point Types

java
public class FloatTypes {
    public static void main(String[] args) {
        float price = 99.99f;            // Must end with 'f'
        double pi = 3.141592653589793;   // More precise

        System.out.println("float: " + price);
        System.out.println("double: " + pi);

        // Scientific notation
        double distance = 1.496e8;       // 1.496 × 10⁸
        System.out.println("Distance to Sun: " + distance + " km");
    }
}

Output:

float: 99.99
double: 3.141592653589793
Distance to Sun: 1.496E8 km

When to use float vs double? Use double by default — it's more precise. Use float only when memory is a concern (e.g., large arrays in game development).

Character Type

The char type stores a single Unicode character (2 bytes):

java
public class CharType {
    public static void main(String[] args) {
        char letter = 'A';
        char digit = '7';
        char symbol = '@';
        char unicode = '\u0041';  // Unicode for 'A'
        char hindi = 'अ';         // Hindi character

        System.out.println(letter);   // A
        System.out.println(unicode);  // A
        System.out.println(hindi);    // अ

        // char is actually stored as a number (Unicode value)
        System.out.println((int) letter);  // 65
    }
}

Boolean Type

The boolean type holds only true or false:

java
public class BooleanType {
    public static void main(String[] args) {
        boolean isJavaFun = true;
        boolean isRaining = false;
        boolean isAdult = (18 >= 18);   // true

        System.out.println("Java is fun: " + isJavaFun);
        System.out.println("Is adult: " + isAdult);
    }
}

Reference Data Types

Reference types store the memory address (reference) of an object rather than the actual value.

String

String is the most commonly used reference type:

java
String greeting = "Hello, World!";
String name = new String("Arjun");  // Also valid, but not preferred

System.out.println(greeting.length());        // 13
System.out.println(greeting.toUpperCase());   // HELLO, WORLD!
System.out.println(greeting.charAt(0));       // H

Arrays

Arrays store multiple values of the same type:

java
int[] numbers = {10, 20, 30, 40, 50};
String[] names = {"Arjun", "Priya", "Rahul"};

System.out.println(numbers[0]);   // 10
System.out.println(names.length); // 3

Objects

Any instance of a class is a reference type:

java
Scanner scanner = new Scanner(System.in);

Primitive vs Reference Types

FeaturePrimitiveReference
StoresActual valueMemory address
MemoryStackHeap
Default0, 0.0, false, '\u0000'null
MethodsNoneHas methods
Examplesint, double, booleanString, Array, Object

Type Casting

Converting one data type to another.

Widening Casting (Automatic)

Smaller type → Larger type. Done automatically by Java:

byte → short → int → long → float → double
java
int myInt = 100;
long myLong = myInt;       // Automatic: int → long
double myDouble = myLong;  // Automatic: long → double

System.out.println(myInt);     // 100
System.out.println(myLong);    // 100
System.out.println(myDouble);  // 100.0

Narrowing Casting (Manual)

Larger type → Smaller type. Must be done explicitly:

java
double myDouble = 9.78;
int myInt = (int) myDouble;    // Manual: double → int

System.out.println(myDouble);  // 9.78
System.out.println(myInt);     // 9 (decimal part lost)

Warning: Narrowing casting can cause data loss (truncation, overflow).

java
int largeNum = 130;
byte smallNum = (byte) largeNum;
System.out.println(smallNum);  // -126 (overflow!)

Wrapper Classes

Every primitive type has a corresponding wrapper class (object version):

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
java
// Autoboxing: primitive → wrapper (automatic)
int num = 42;
Integer wrapped = num;

// Unboxing: wrapper → primitive (automatic)
int unwrapped = wrapped;

// Useful methods
int parsed = Integer.parseInt("123");          // String → int
String str = Integer.toString(123);            // int → String
int max = Integer.MAX_VALUE;                   // 2147483647

Choosing the Right Data Type

Use CaseRecommended Type
Age, count, loop counterint
Large numbers (timestamps, IDs)long
Money, precise decimalsdouble (or BigDecimal for finance)
Yes/No flagsboolean
Single characterchar
TextString
Memory-sensitive large arraysbyte or short

Practical Example

java
public class StudentProfile {
    public static void main(String[] args) {
        // Using different data types
        String name = "Arjun Kumar";
        int age = 22;
        double gpa = 8.75;
        char bloodGroup = 'O';
        boolean isGraduated = false;
        long aadhaarNumber = 1234_5678_9012L;
        byte semester = 6;

        System.out.println("=== Student Profile ===");
        System.out.printf("Name:       %s%n", name);
        System.out.printf("Age:        %d years%n", age);
        System.out.printf("GPA:        %.2f/10%n", gpa);
        System.out.printf("Blood Group: %c+%n", bloodGroup);
        System.out.printf("Graduated:  %b%n", isGraduated);
        System.out.printf("Aadhaar:    %d%n", aadhaarNumber);
        System.out.printf("Semester:   %d%n", semester);
    }
}

Output:

=== Student Profile ===
Name:       Arjun Kumar
Age:        22 years
GPA:        8.75/10
Blood Group: O+
Graduated:  false
Aadhaar:    123456789012
Semester:   6

Summary

  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean
  • Reference types include String, arrays, and objects — they store memory addresses
  • Widening casting (small → large) happens automatically; narrowing (large → small) requires explicit cast
  • Every primitive has a wrapper class (intInteger) for object-oriented use
  • Use int for most integers, double for decimals, String for text, boolean for flags
  • Java is statically typed — declare the type before using a variable