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

8 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 - Operators and Control Flow

Java Programming Language

Chapter 3: Operators and Control Flow

Controlling Program Execution


Course: 4343203 - Java Programming

What We'll Cover

  • Arithmetic Operators
  • Assignment & Relational Operators
  • Logical & Bitwise Operators
  • Conditional Operator & Precedence
  • Selection Statements (if, switch)
  • Looping Statements (while, for)
  • Jump Statements (break, continue, return)

Control Flow Structures

Java Control Flow Structures

Arithmetic Operators

Arithmetic operators perform mathematical operations

OperatorNameDescriptionExample
+AdditionAdds two valuesx + y
-SubtractionSubtracts one value from anotherx - y
*MultiplicationMultiplies two valuesx * y
/DivisionDivides one value by anotherx / y
%ModulusReturns division remainderx % y
++IncrementIncreases value by 1++x, x++
--DecrementDecreases value by 1--x, x--

Arithmetic Examples

Basic Operations:


int a = 10, b = 3;
int sum = a + b;        // 13
int difference = a - b; // 7
int product = a * b;    // 30
int quotient = a / b;   // 3 (integer division)
int remainder = a % b;  // 1
                            

Increment/Decrement:


int x = 5;
int y = ++x; // Pre-increment: x=6, y=6
int z = x++; // Post-increment: x=7, z=6

int p = 10;
int q = --p; // Pre-decrement: p=9, q=9
int r = p--; // Post-decrement: p=8, r=9
                            

Assignment Operators

Assignment operators assign values to variables

OperatorExampleSame AsDescription
=x = 5x = 5Simple assignment
+=x += 3x = x + 3Add and assign
-=x -= 3x = x - 3Subtract and assign
*=x *= 3x = x * 3Multiply and assign
/=x /= 3x = x / 3Divide and assign
%=x %= 3x = x % 3Modulus and assign

Assignment Examples

Compound Assignment:


int score = 100;
score += 50;  // score = 150
score -= 20;  // score = 130
score *= 2;   // score = 260
score /= 4;   // score = 65
score %= 10;  // score = 5
                            

Multiple Assignment:


int a, b, c;
a = b = c = 10; // All variables get 10

// Chain assignment
int x = 5;
int y = (x += 3); // x = 8, y = 8
                            

Relational (Comparison) Operators

Relational operators compare values and return boolean results

OperatorNameDescriptionExample
==Equal toReturns true if values are equalx == y
!=Not equalReturns true if values are differentx != y
>Greater thanReturns true if left > rightx > y
<Less thanReturns true if left < rightx < y
>=Greater than or equalReturns true if left >= rightx >= y
<=Less than or equalReturns true if left <= rightx <= y

Relational Examples


public class RelationalExample {
    public static void main(String[] args) {
        int a = 10, b = 5, c = 10;
        
        System.out.println(a == b);  // false
        System.out.println(a != b);  // true
        System.out.println(a > b);   // true
        System.out.println(a < b);   // false
        System.out.println(a >= c);  // true
        System.out.println(b <= a);  // true
        
        // Common usage in conditions
        if (a > b) {
            System.out.println("a is greater than b");
        }
    }
}
                    

Logical Operators

Logical operators work with boolean values

OperatorNameDescriptionExample
&&Logical ANDTrue if both operands are truex && y
||Logical ORTrue if at least one operand is truex || y
!Logical NOTReverses the logical state!x

Logical Examples & Truth Tables

Examples:


boolean a = true, b = false;
boolean result1 = a && b;  // false
boolean result2 = a || b;  // true
boolean result3 = !a;      // false

// Practical usage
int age = 20;
boolean hasLicense = true;
boolean canDrive = (age >= 18) && hasLicense;

// Short-circuit evaluation
if (age > 0 && (100/age) > 5) {
    System.out.println("Valid");
}
                            

Truth Tables:

ABA&&BA||B!A
TTTTF
TFFTF
FTFTT
FFFFT

Short-circuit: && stops at first false, || stops at first true

Bitwise Operators

Bitwise operators perform operations on individual bits

OperatorNameDescription
&ANDBitwise AND
|ORBitwise OR
^XORBitwise XOR
~ComplementBitwise NOT
<<Left ShiftShift bits left
>>Right ShiftShift bits right

Example:


int a = 5;  // Binary: 101
int b = 3;  // Binary: 011

int and = a & b;    // 001 = 1
int or = a | b;     // 111 = 7
int xor = a ^ b;    // 110 = 6
int not = ~a;       // ...11111010
int left = a << 1;  // 1010 = 10
int right = a >> 1; // 10 = 2
                        

Conditional (Ternary) Operator

Ternary operator provides a compact if-else alternative

Syntax:

variable = (condition) ? expressionTrue : expressionFalse;

Instead of:


int time = 20;
String greeting;
if (time < 18) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}
                        

Use:


int time = 20;
String greeting = (time < 18) ? 
    "Good day" : "Good evening";

// More examples
int max = (a > b) ? a : b;
String status = (score >= 60) ? 
    "Pass" : "Fail";
                        

Operator Precedence

Precedence determines evaluation order in expressions

LevelOperatorsAssociativity
1() [] .Left to Right
2++ -- ! ~Right to Left
3* / %Left to Right
4+ -Left to Right
5<< >> >>>Left to Right
6< <= > >=Left to Right
7== !=Left to Right
8&Left to Right
9^Left to Right
10|Left to Right
11&&Left to Right
12||Left to Right
13?:Right to Left
14= += -= *=Right to Left

Examples:


int result = 5 + 3 * 2;     // 11 (not 16)
int result2 = (5 + 3) * 2;  // 16

boolean check = 10 > 5 && 3 < 7;  // true
boolean check2 = !false || true && false; 
// true (! has higher precedence)

int x = 10;
int y = ++x * 2;  // 22 (++x evaluated first)
                        

Tip: Use parentheses () to make intentions clear

Operator Precedence Visualization

Java Operator Precedence Hierarchy

Selection Statements

Selection statements execute different code based on conditions

if Statement

Single condition

if-else Statement

Two-way selection

switch Statement

Multi-way selection

if Statement

Syntax:


if (condition) {
    // code to execute if true
}
                            

Example:


int age = 20;
if (age >= 18) {
    System.out.println("You can vote!");
}
                            

if-else:


if (condition) {
    // code if true
} else {
    // code if false
}
                            

if-else-if:


if (grade >= 90) {
    System.out.println("A");
} else if (grade >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}
                            

switch Statement

Syntax:


switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
}
                            

Example:


int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Other day");
}
                            

Important: Use break to prevent fall-through. default is optional.

Looping Statements

Loops execute code repeatedly based on conditions

while Loop

Entry-controlled

do-while Loop

Exit-controlled

for Loop

Counter-controlled

while and do-while Loops

while Loop:


// Syntax
while (condition) {
    // code to repeat
}

// Example
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
// Output: 1 2 3 4 5
                            

do-while Loop:


// Syntax
do {
    // code to repeat
} while (condition);

// Example
int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);
// Output: 1 2 3 4 5
                            

Difference: do-while executes at least once, while may not execute at all

for Loop

Traditional for Loop:


// Syntax
for (initialization; condition; update) {
    // code to repeat
}

// Example
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

// Nested loops
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print(i + "," + j + " ");
    }
    System.out.println();
}
                            

Enhanced for Loop (for-each):


// Syntax
for (dataType variable : collection) {
    // code using variable
}

// Array example
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

// String array example
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
    System.out.println("Hello " + name);
}
                            

Jump Statements

Jump statements transfer control to different parts of the program

break

Exit loop/switch

continue

Skip iteration

return

Exit method

break and continue Examples

break Statement:


// Exit loop when condition met
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;  // Exit loop
    }
    System.out.println(i);
}
// Output: 1 2 3 4

// In switch statement
switch (day) {
    case 1:
        System.out.println("Monday");
        break;  // Exit switch
    case 2:
        System.out.println("Tuesday");
        break;
}
                            

continue Statement:


// Skip current iteration
for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;  // Skip rest of iteration
    }
    System.out.println(i);
}
// Output: 1 2 4 5

// Skip even numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println(i); // Only odd numbers
}
                            

return Statement

Returning Values:


public static int add(int a, int b) {
    return a + b;  // Return sum
}

public static boolean isEven(int num) {
    return num % 2 == 0;  // Return boolean
}

public static String getGrade(int score) {
    if (score >= 90) return "A";
    if (score >= 80) return "B";
    return "C";
}
                            

Void Methods:


public static void printNumbers(int max) {
    for (int i = 1; i <= max; i++) {
        if (i > 100) {
            return;  // Exit method early
        }
        System.out.println(i);
    }
    // Implicit return here
}

public static void main(String[] args) {
    printNumbers(5);
    return;  // Optional in main
}
                            

Chapter Summary

Operators Learned:

  • Arithmetic: +, -, *, /, %, ++, --
  • Assignment: =, +=, -=, *=, /=, %=
  • Relational: ==, !=, >, <, >=, <=
  • Logical: &&, ||, !
  • Bitwise: &, |, ^, ~, <<, >>
  • Conditional: ?:

Control Structures:

  • Selection: if, if-else, switch
  • Iteration: while, do-while, for
  • Jump: break, continue, return
  • Operator precedence and associativity
  • Nested loops and conditions

Next: Object-Oriented Programming Fundamentals

Thank You!

Questions?


Ready to explore Object-Oriented Programming!