Java Control Flow and Arrays: Complete Beginner Guide

In Java, control flow statements control the execution order of a program, while arrays are used to store multiple values of the same type in a single variable. These two topics are very important for Java beginners, coding interviews, and SCJP preparation.

Java Control Flow Statements

Control flow statements decide how a Java program executes instructions. By default, Java statements execute from top to bottom, but control flow statements allow us to make decisions, repeat code, and jump from one part of the program to another.

Types of Control Flow Statements

  • Selection statements: if, if-else, switch
  • Iteration statements: for, while, do-while
  • Jump statements: break, continue, return

if Statement in Java

The if statement is used when we want to execute a block of code only if a condition is true.

Syntax

if (condition) {
    // statements
}

Example

int marks = 75;

if (marks >= 35) {
    System.out.println("Pass");
}

In this example, the message Pass will be printed only when the condition is true.

if-else Statement in Java

The if-else statement is used when we want to execute one block if the condition is true and another block if the condition is false.

Syntax

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

Example

int number = 10;

if (number % 2 == 0) {
    System.out.println("Even number");
} else {
    System.out.println("Odd number");
}

else-if Ladder in Java

The else-if ladder is used when we need to test multiple conditions.

Example

int marks = 85;

if (marks >= 90) {
    System.out.println("Grade A+");
} else if (marks >= 75) {
    System.out.println("Grade A");
} else if (marks >= 60) {
    System.out.println("Grade B");
} else {
    System.out.println("Needs Improvement");
}

switch Statement in Java

The switch statement is used when we want to compare one value with multiple possible cases. It is commonly used as an alternative to long else-if ladders.

Syntax

switch (expression) {
    case value1:
        // statements
        break;

    case value2:
        // statements
        break;

    default:
        // default statements
}

Example

int day = 2;

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("Invalid day");
}

The break statement is important because it stops execution from falling into the next case.

Loops in Java

Loops are used to execute a block of code repeatedly. Java supports three main loop statements:

  • while loop
  • do-while loop
  • for loop

while Loop in Java

The while loop executes a block of code as long as the condition is true.

Example

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}

do-while Loop in Java

The do-while loop executes the block at least once, even if the condition is false.

Example

int i = 1;

do {
    System.out.println(i);
    i++;
} while (i <= 5);

for Loop in Java

The for loop is used when we know how many times we want to repeat a block of code.

Example

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

Enhanced for Loop in Java

The enhanced for loop is mainly used to read elements from arrays and collections.

Example

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

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

break and continue Statements

break Statement

The break statement is used to stop loop or switch execution immediately.

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}

continue Statement

The continue statement skips the current iteration and moves to the next iteration.

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    System.out.println(i);
}

Java Arrays

An array in Java is an object used to store multiple values of the same data type. Arrays are useful when we want to store a group of related values under a single variable name.

Arrays in Java involve three major steps:

  1. Array declaration
  2. Array creation
  3. Array initialization

Array Declaration in Java

Array declaration creates a reference variable that can point to an array object.

Valid Declarations

int[] a;
int a[];
int []a;

The recommended form is int[] a; because the type is clearly separated from the variable name.

Invalid Declaration

int[5] a; // invalid in Java

In Java, array size cannot be specified at the time of declaration.

Array Creation in Java

Arrays are created using the new keyword because arrays are objects in Java.

Example

int[] a = new int[3];

This creates an integer array of size 3.

Allowed Types for Array Size

Array size can be specified using integral types such as:

  • byte
  • short
  • int
  • char

Example

byte b = 10;
int[] a = new int[b];

char ch = 'A';
int[] x = new int[ch];

Array Initialization in Java

Array initialization means assigning values to array elements.

Example

int[] a = new int[3];

a[0] = 10;
a[1] = 20;
a[2] = 30;

Declaration, Creation and Initialization in One Line

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

Multidimensional Arrays in Java

Java supports multidimensional arrays. A two-dimensional array can be imagined as an array of arrays.

Example

int[][] a = new int[2][3];

a[0][0] = 10;
a[0][1] = 20;
a[1][0] = 30;

Jagged Array Example

int[][] a = new int[3][];

a[0] = new int[2];
a[1] = new int[3];
a[2] = new int[1];

In a jagged array, each row can have a different size.

Anonymous Array in Java

An anonymous array is an array without a name. It is commonly used when we need to pass an array directly to a method.

Example

class Test {
    public static void sum(int[] x) {
        int total = 0;

        for (int i : x) {
            total = total + i;
        }

        System.out.println(total);
    }

    public static void main(String[] args) {
        sum(new int[] {10, 20, 30, 40});
    }
}

Array Element Assignment

In primitive type arrays, values that can be promoted to the declared array type are allowed.

Example

int[] a = new int[5];

a[0] = 10;
a[1] = 'A';  // valid because char can be promoted to int

But incompatible values are not allowed.

int[] a = new int[5];

a[0] = 10.5; // compile-time error

Array Variable Assignment

When assigning one array reference to another, the array type must be compatible. The size does not need to be the same, but the type must match.

Example

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

a = b; // valid

Invalid Example

int[] a = {10, 20, 30};
char[] ch = {'a', 'b'};

a = ch; // compile-time error

length vs length() in Java

In Java, length and length() are different.

Feature length length()
Type Variable / property Method
Used for Arrays String objects
Example a.length str.length()

Example

int[] a = new int[10];
System.out.println(a.length); // 10

String str = "Java";
System.out.println(str.length()); // 4

Summary

Java control flow statements help us control program execution using decision-making, looping, and jumping statements. Arrays help us store multiple values of the same type. Understanding control flow and arrays is essential for Java programming, SCJP preparation, and technical interviews.

Frequently Asked Questions

What is control flow in Java?

Control flow in Java defines the order in which program statements execute. It includes decision-making, looping, and jump statements.

What is an array in Java?

An array is an object that stores multiple values of the same data type.

What is the difference between length and length()?

length is used with arrays, while length() is used with strings.

Can array size change after creation?

No, once an array is created in Java, its size is fixed.