Bytes
rocket

Your Success, Our Mission!

6000+ Careers Transformed.

Variables and Data Types

Last Updated: 22nd March, 2026

3.1 Variables and Data Types

3.1.1 Explanation

Variables are containers that hold data during program execution. In Java, variables are statically typed, meaning their data type must be declared before use, ensuring type safety. Java provides eight primitive types for efficiency — byte, short, int, long, float, double, char, and boolean.

All other types (arrays, strings, classes) are reference types, which store memory addresses rather than actual data values.
Variables can have different scopes — local (inside methods), instance (specific to objects), or static (shared across all instances).

Understanding how Java handles memory allocation between stack (for primitives) and heap (for objects) is key to writing optimized programs. In modern Java (since Java 17+), features like var keyword offer local variable type inference, simplifying code while retaining strong typing.

3.1.2 Code

public class DataTypeDemo {

public static void main(String[] args) {

int age = 21;

double salary = 65000.50;

char grade = 'A';

boolean active = true;

String name = "John";

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Salary: " + salary);

System.out.println("Grade: " + grade);

System.out.println("Active: " + active);

}

}

3.1.3 Example

Output:

Name: John

Age: 21

Salary: 65000.5

Grade: A

Active: true

Explanation: Each variable is declared with a specific data type and printed. Java automatically handles memory and type conversions when combining data in expressions.

3.1.4 Use Cases

  • Defining attributes of an object (e.g., employee name, age).
  • Managing numeric, logical, or textual data.
  • Implementing computations and algorithmic operations.

3.1.5 Relevant Table

Type

Size

Range

Example

byte

8 bits

-128 to 127

byte b = 10;

int

32 bits

~ -2B to 2B

int x = 100;

double

64 bits

15 decimals

double d = 3.14159;

boolean

1 bit

true/false

boolean flag = true;

char

16 bits

Unicode

char c = 'J';

3.2 Operators and Expressions

3.2.1 Explanation

Operators in Java are special symbols used to perform operations on variables and values. They form the foundation of all logical, mathematical, and decision-making expressions within programs. An expression is a combination of operators and operands that produces a result.

Java supports several categories of operators:

  1. Arithmetic Operators — perform mathematical operations (+, -, *, /, %).
  2. Relational Operators — compare values (>, <, >=, <=, ==, !=).
  3. Logical Operators — evaluate multiple boolean expressions (&&, ||, !).
  4. Bitwise Operators — manipulate bits directly (&, |, ^, ~, <<, >>, >>>).
  5. Assignment Operators — assign values (=, +=, -=, *=, /=, %=).
  6. Conditional (Ternary) Operator — short-form of if-else (condition ? value1 : value2).
  7. Unary Operators — operate on a single operand (++, --, +, -, !).

Operator precedence and associativity determine the order in which operations are evaluated in complex expressions. Parentheses can always be used to enforce custom evaluation order, improving code readability and correctness.
Understanding how these operators behave—especially short-circuiting logical operators and pre/post increment—is critical to preventing subtle bugs and improving performance.

3.2.2 Code

public class OperatorsExample {

public static void main(String[] args) {

int a = 10, b = 3;

int sum = a + b;          // Arithmetic addition

double div = (double)a / b;  // Type casting for floating result

int remainder = a % b;    // Modulus operation

boolean equal = (a == b); // Relational

boolean condition = (a > b) && (b > 0); // Logical AND

a += 5; // Assignment shortcut (a = a + 5)

int result = (a > b) ? a : b; // Ternary operator

System.out.println("Sum: " + sum);

System.out.println("Division: " + div);

System.out.println("Remainder: " + remainder);

System.out.println("Equal: " + equal);

System.out.println("Condition: " + condition);

System.out.println("Ternary Result: " + result);

}

}

3.2.3 Example

Input:
Output:

Sum: 13

Division: 3.3333333333333335

Remainder: 1

Equal: false

Condition: true

Ternary Result: 15

Explanation:
Arithmetic operators perform standard calculations. The typecast (double) ensures decimal division.
Logical operators like && perform short-circuit evaluation, stopping once the result is determined.
The ternary operator quickly selects one of two values based on a condition, improving code compactness.

3.2.4 Use Cases

  • Performing mathematical computations in financial or scientific applications.
  • Comparing user inputs or program states to control logic.
  • Efficient conditional assignments and flag checks.
  • Implementing binary operations in encryption, compression, and system-level software.

3.2.5 Relevant Table

Operator Type

Examples

Description

Example Output

Arithmetic

+, -, *, /, %

Basic calculations

a+b = 13

Relational

>, <, ==, !=

Comparison results in boolean

a > b → true

Logical

&&, ||, !

Combines boolean expressions

(a>b)&&(b>0) → true

Assignment

=, +=, -=

Assign or update variable values

a+=5 → 15

Bitwise

&, |, ^, <<, >>

Works on bits

5<<1 → 10

Conditional

?:

Short form of if-else

(a>b)?a:b

Unary

++, --, !

Single operand manipulation

++a → 11

3.3 Control Flow Statements

3.3.1 Explanation

Control flow statements define the order of execution of program instructions. In Java, these statements enable decision-making, looping, and conditional branching. They ensure that programs can react to different inputs or states dynamically.

The major control flow categories are:

  1. Conditional Statements – make decisions based on boolean conditions (if, if-else, switch).
  2. Looping Statements – repeatedly execute blocks of code (for, while, do-while).
  3. Jump Statements – alter normal flow using break, continue, and return.

Modern Java versions (14 and above) extend the switch statement into a switch expression, which returns values directly, improving readability and reducing boilerplate code.
Proper use of these control structures ensures efficiency, modularity, and clarity in logic design. Deeply nested or redundant conditions can be refactored into smaller, well-defined methods or strategy patterns.

3.3.2 Code

public class ControlFlowExample {

public static void main(String[] args) {

int number = 7;

// Conditional

if (number > 0) {

System.out.println("Positive number");

} else if (number < 0) {

System.out.println("Negative number");

} else {

System.out.println("Zero");

}

// Switch expression (Java 14+)

String result = switch (number) {

case 1, 2, 3 -> "Small Number";

case 4, 5, 6, 7 -> "Medium Number";

default -> "Large Number";

};

System.out.println("Category: " + result);

// Loop Example

System.out.print("Counting: ");

for (int i = 1; i <= 5; i++) {

System.out.print(i + " ");

}

}

}

3.3.3 Example

Output:

Positive number

Category: Medium Number

Counting: 1 2 3 4 5

Explanation:
The program uses an if-else chain to categorize the number as positive or negative. The switch expression simplifies multi-condition evaluation.
Finally, a for loop demonstrates controlled iteration with a fixed boundary condition.

3.3.4 Use Cases

  • Handling user decisions and input validation.

  • Performing repetitive calculations (e.g., summation, iteration).

  • Structuring decision-based workflows (menus, navigation systems).

  • Controlling nested loops in algorithmic problems.

     

3.3.5 Relevant Table

Control Type

Statement

Description

Example

Conditional

if, if-else, switch

Executes code based on conditions

if(a>b)

Looping

for, while, do-while

Repeats until condition fails

for(i=0;i<5;i++)

Jump

break, continue, return

Alters default flow

break; exits loop

Modern Switch

switch (→)

Returns expression values

case 3 -> "Low";

Module 2: Core Java Language ElementsVariables and Data Types

Top Tutorials

Logo
Computer Science

CNN in Deep Learning 2026

A beginner-friendly guide to CNNs: understand deep learning essentials, create Python-based models, and explore advanced applications.

4 Modules12 Lessons151 Learners
Start Learning
Logo
Computer Science

Breaking The Limits: Scaling Databases with MySQL Partitioning

Learn MySQL partitioning with examples. Improve query performance, scalability, and data management using RANGE, LIST, HASH, KEY, and composite techniques.

7 Modules11 Lessons71 Learners
Start Learning
Logo

ML in Action: Hands-On Guide to Deploying and Serving Models

Learn model deployment and serving—from concepts to real-world architectures, tools, APIs, containers, and cloud workflows for production-ready ML.

4 Modules10 Lessons78 Learners
Start Learning
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2026 AlmaBetter