Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 4/
  5. Java Programming (4343203)/

6 mins· ·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Java Programming - Data Types and Variables

Java Programming Language

Chapter 2: Data Types and Variables

Understanding Java's Type System


Course: 4343203 - Java Programming

What We'll Cover

  • Primitive Data Types
  • Non-Primitive Data Types
  • Type Conversion and Casting
  • Identifiers and Naming Rules
  • Variables and Constants
  • Arrays (1D and 2D)

Java Data Types Overview

Java Data Types Hierarchy

Primitive Data Types

8 primitive data types - predefined by Java, store actual values

Characteristics:

  • Store actual values
  • Cannot be null
  • Start with lowercase
  • Stored in stack memory

Categories:

  • Numeric (6 types)
  • Character (1 type)
  • Boolean (1 type)

Integer Types

TypeSizeRangeExample
byte8 bits-128 to 127byte b = 100;
short16 bits-32,768 to 32,767short s = 1000;
int32 bits-2³¹ to 2³¹-1int i = 100000;
long64 bits-2⁶³ to 2⁶³-1long l = 100000L;

Note: int is most commonly used. Use L suffix for long values.

Floating-Point Types

TypeSizePrecisionExample
float32 bits6-7 decimal digitsfloat f = 3.14f;
double64 bits15 decimal digitsdouble d = 3.14159;

Float Example:


float price = 19.99f;
float rate = 5.75f;
                            

Double Example:


double pi = 3.14159265359;
double result = 123.456789;
                            

Character and Boolean Types

char (Character)

  • Size: 16 bits
  • Range: 0 to 65,535 (Unicode)
  • Usage: Single character

char letter = 'A';
char digit = '5';
char symbol = '@';
char unicode = '\u0041'; // 'A'
                                

boolean

  • Size: 1 bit
  • Values: true or false
  • Usage: Logical conditions

boolean isActive = true;
boolean isComplete = false;
boolean result = (5 > 3);
                                

Non-Primitive Data Types

Reference types - created by programmer, store references to objects

Characteristics:

  • Store object references
  • Can be null
  • Start with uppercase
  • Stored in heap memory
  • Have methods available

Types:

  • String
  • Arrays
  • Classes
  • Interfaces
  • Enums

Key Differences: Primitive vs Non-Primitive

AspectPrimitiveNon-Primitive
DefinitionPredefined by JavaCreated by programmer
StorageActual valuesObject references
Null ValueCannot be nullCan be null
MethodsNo methodsCan call methods
MemoryStackHeap
CaseLowercaseUppercase

Type Conversion and Casting

Implicit Conversion (Widening)

Automatic conversion from smaller to larger data types

byte → short → char → int → long → float → double

public class ImplicitConversion {
    public static void main(String[] args) {
        int myInt = 9;
        double myDouble = myInt; // Automatic casting: int to double
        
        System.out.println(myInt);      // Outputs 9
        System.out.println(myDouble);   // Outputs 9.0
    }
}
                    

Explicit Conversion (Narrowing)

Manual conversion from larger to smaller data types

double → float → long → int → char → short → byte

public class ExplicitConversion {
    public static void main(String[] args) {
        double myDouble = 9.78d;
        int myInt = (int) myDouble; // Manual casting: double to int
        
        System.out.println(myDouble);   // Outputs 9.78
        System.out.println(myInt);      // Outputs 9 (truncated)
    }
}
                    

Identifiers

Identifiers are names given to classes, methods, variables, etc.

Naming Rules (Must Follow)

  • Must begin with a letter (a-z, A-Z), underscore (_), or dollar sign ($)
  • Can contain letters, digits, underscores, and dollar signs
  • Cannot start with a digit
  • Cannot contain whitespace
  • Case-sensitive ("myVar" ≠ "myvar")
  • Cannot be Java keywords

✅ Valid:

  • myVariable
  • _count
  • $amount
  • num1

❌ Invalid:

  • 2num
  • my var
  • class
  • my-var

Naming Conventions (Best Practices)

Classes

PascalCase


public class MyClass
public class StudentRecord
                                

Variables & Methods

camelCase


int myVariable
void calculateTotal()
                                

Constants

UPPER_CASE


final int MAX_SIZE
final double PI_VALUE
                                

Variables

Variables are containers for storing data values

Variable Declaration and Initialization

Declaration:


int myVariable;        // Declared
double price;          // Declared
String name;           // Declared
                            

Multiple Declaration:


int x, y, z;           // Multiple variables
int a = 5, b = 6, c = 50;
                            

Initialization:


int myVariable = 10;   // Initialized
double price = 19.99;  // Initialized
String name = "John";  // Initialized
                            

Same Value Assignment:


int x, y, z;
x = y = z = 50;        // All get 50
                            

Variable Scope

Local Variables

  • Declared inside methods
  • Accessible only within method
  • Must be initialized

Instance Variables

  • Declared in class
  • Accessible to all methods
  • Default values assigned

Class Variables

  • Declared with static
  • Shared among all objects
  • Memory allocated once

public class VariableScope {
    static int classVar = 100;    // Class variable
    int instanceVar = 50;         // Instance variable
    
    public void method() {
        int localVar = 20;        // Local variable
        // localVar only accessible here
    }
}
                    

Constants (final keyword)

Constants are variables whose values cannot be changed

Declaration:


final int MAX_SIZE = 100;
final double PI = 3.14159;
final String COMPANY = "TechCorp";
                        

Characteristics:

  • Must be initialized when declared
  • Value cannot be changed
  • Usually named in UPPER_CASE

Example:


public class Constants {
    final int myNum = 15;
    
    public static void main(String[] args) {
        Constants obj = new Constants();
        // obj.myNum = 20; // ERROR!
        System.out.println(obj.myNum);
    }
}
                        

Arrays

Arrays store multiple values of the same type in a single variable

One-Dimensional Arrays

Declaration & Initialization:


// Method 1: Declare then initialize
int[] numbers = new int[5];

// Method 2: Declare and initialize
int[] numbers = {1, 2, 3, 4, 5};

// Method 3: Using new keyword
int[] numbers = new int[]{1, 2, 3, 4, 5};
                            

Accessing Elements:


int[] numbers = {10, 20, 30, 40, 50};

// Access elements (0-indexed)
int first = numbers[0];    // 10
int third = numbers[2];    // 30

// Modify elements
numbers[1] = 25;           // Changes 20 to 25

// Array length
int size = numbers.length; // 5
                            

Important: Array indices start at 0. Length is fixed after creation.

Two-Dimensional Arrays

Declaration & Initialization:


// Method 1: Declare then initialize
int[][] matrix = new int[3][3];

// Method 2: Initialize with values
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
                            

Accessing Elements:


int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};

// Access element at row 1, column 2
int element = matrix[1][2]; // 6

// Modify element
matrix[0][1] = 10;

// Array dimensions
int rows = matrix.length;        // 3
int cols = matrix[0].length;     // 3
                            

Array Memory Layout & Structure

Array Memory Layout and Structure

Array Iteration

1D Array - Traditional Loop:


int[] numbers = {1, 2, 3, 4, 5};

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
                            

1D Array - Enhanced Loop:


for (int number : numbers) {
    System.out.println(number);
}
                            

2D Array Iteration:


int[][] matrix = {{1,2,3}, {4,5,6}};

// Nested loops
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

// Enhanced for loops
for (int[] row : matrix) {
    for (int element : row) {
        System.out.print(element + " ");
    }
    System.out.println();
}
                            

Chapter Summary

Key Concepts:

  • 8 primitive data types
  • Reference types (non-primitive)
  • Type conversion (implicit/explicit)
  • Naming rules and conventions

Practical Skills:

  • Variable declaration and initialization
  • Understanding variable scope
  • Working with constants
  • Creating and using arrays

Next: Operators and Control Flow

Thank You!

Questions?


Ready to work with Java operators and control structures!