Home
1Java Syntax, Data Types & Control Flow
1

Lab Manual I · CSE 202

Java Syntax, Data Types & Control Flow

Set up the JDK and an IDE, then write a first Java program that uses variables, primitive types, type casting, if/switch decisions and the three loops.

← → move between slides · F full screen · M slide list

Before we start

Why this lab

Every Java program you write this semester — bank systems, threads, GUIs — is built from the same few pieces. Which ones?

Variables hold data, types say what kind of data, decisions choose a path and loops repeat work. This lab puts all of them in one program, Lab1Demo.

Lab 1 of 10

Lab at a glance

After this lab you can

  • Set up and verify a JDK (11+) with NetBeans, Eclipse or IntelliJ IDEA
  • Explain how source code becomes bytecode that the JVM runs
  • Declare variables of the eight primitive types and String
  • Apply widening and narrowing casts
  • Use if / else if / else and switch
  • Repeat work with for, while and do-while; control loops with break and continue

Before you start

  • Create folders and save files
  • Basic idea of variables, expressions, input and output
  • JDK 11+ and an IDE installed

Plan for the session

  1. Theory recap
  2. Walk through the program, section by section, and run it
  3. In-lab tasks, shown to the instructor
  4. Report exercises at home

Setting up · 1 of 4

Which Java do you need?

  • A JDK (Java Development Kit): it contains the compiler javac and the runtime java. A JRE alone cannot compile.
  • Use the current LTS release, JDK 25, from the official Java site oracle.com/java. The manual needs JDK 11 or later.
  • Install the JDK first, then the IDE: this course uses Apache NetBeans.
  • On the next slides, pick your operating system: each slide has direct download links, the steps and a YouTube video link.

Setting up · 2 of 4

Install the JDK

Setting up · 3 of 4

Install Apache NetBeans

Setting up · 4 of 4

Your first project in NetBeans

Theory 1 of 6

From .java to a running program

  • You write Lab1Demo.java; javac compiles it to bytecode in Lab1Demo.class.
  • The JVM loads the bytecode and starts at main: “write once, run anywhere”.
  • A public class must live in a file with the same name.

Theory 2 of 6

Structure of a Java program

public class Lab1Demo {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
  • Every statement lives inside a class; execution begins in main.
  • System.out.println() prints a line to the console.
  • Check your setup: compile and run this before starting the tasks.

Theory 3 of 6

Variables and the eight primitive types

TypeHoldsExample
byte / shortsmall integersbyte b = 100;
intcommon integersint age = 21;
longlarge integers (suffix L)long pop = 9876543210L;
floatsingle-precision (suffix f)float gpa = 3.75f;
doubledouble-precision decimalsdouble h = 5.91;
charone characterchar grade = 'A';
booleantrue / falseboolean ok = true;
  • Java is statically typed: every variable has a declared type. String is a reference type for text.

Theory 4 of 6

Type casting

  • Widening (small → large) is automatic and safe.
  • Narrowing needs a cast and may lose data: the fraction is cut off, not rounded.

Type casting

double d = 25;            // widening: automatic -> 25.0
int price = (int) 99.99;  // narrowing: explicit -> 99

Theory 5 of 6

Decisions: if-else and switch

  • Use if / else if / else for ranges and conditions.
  • Use switch to compare one value against fixed cases; forget break and execution falls through.

Decisions: if-else and switch

switch (score / 10) {
    case 10: case 9: grade = 'A'; break;
    case 8:          grade = 'B'; break;
    default:         grade = 'F';
}

Theory 6 of 6

Loops, break and continue

Theory 6 of 6

Loops, break and continue (cont.)

  • for: number of iterations known in advance (summation).
  • while: repeat while a condition holds (reverse digits).
  • do-while: body runs at least once (Collatz sequence).
  • break leaves the loop; continue skips to the next iteration.

Implementation design

Execution flow

  1. Declare and print the eight primitive variables and a String
  2. Widen an int to double, narrow a double to int, convert char ↔ int
  3. Classify a number (positive/zero/negative) and a BMI with if-else
  4. Assign a letter grade with switch
  5. Sum 1..10 with for; print even numbers using continue and break
  6. Reverse digits with while
  7. Print the Collatz sequence of 27 with do-while

Single class, everything inside main: the focus is syntax, not objects.

Code walkthrough 1 of 10 · Lab1Demo.java

Variables of every primitive type

// 1. Primitive Data Types and String
byte byteVal = 100;
short shortVal = 30000;
int age = 21;
long bigNum = 9876543210L;
float gpa = 3.75f;
double height = 5.91;
char initial = 'A';
boolean isStudent = true;
String name = "Mozdaher Abdul Quader";
  • One variable per primitive type, plus a String.
  • Note the suffixes: L for long, f for float.

Code walkthrough 2 of 10 · Lab1Demo.java

Printing with labels

System.out.println("=== Primitive Data Types and String ===");
System.out.println("byte    : " + byteVal);
System.out.println("short   : " + shortVal);
System.out.println("int     : " + age);
System.out.println("long    : " + bigNum);
System.out.println("float   : " + gpa);
System.out.println("double  : " + height);
System.out.println("char    : " + initial + " (Unicode = " + (int) initial + ")");
System.out.println("boolean : " + isStudent);
System.out.println("String  : " + name);
  • + joins text and values into one String.
  • (int) initial shows the Unicode number of a char.

Code walkthrough 3 of 10 · Lab1Demo.java

Widening and narrowing casts

// 2. Type Casting
System.out.println("\n=== Type Casting ===");
double ageAsDouble = age;
System.out.println("int " + age + " widened to double: " + ageAsDouble);

double pi = 3.14159;
int piTruncated = (int) pi;
System.out.println("double " + pi + " narrowed to int: " + piTruncated);

Code walkthrough 3 of 10 · Lab1Demo.java

Widening and narrowing casts (cont.)

char letter = 'Z';
int code = letter;
char nextChar = (char) (code + 1);
System.out.println("char 'Z' as int: " + code + " | next char: " + nextChar);
  • int → double happens automatically (widening).
  • double → int needs (int) and drops the fraction.
  • A char is a number: 90 + 1 is the char after Z.

Code walkthrough 4 of 10 · Lab1Demo.java

if / else if / else

// 3. Conditional Statement
System.out.println("\n=== Conditional Statement ===");
int n = 42;
if (n > 0) {
    System.out.println(n + " is Positive");
} else if (n == 0) {
    System.out.println(n + " is Zero");
} else {
    System.out.println(n + " is Negative");
}
  • Only the first true branch runs.

Code walkthrough 5 of 10 · Lab1Demo.java

Ranges with an if-else chain

double weightKg = 70.0;
double heightM = 1.75;
double bmi = weightKg / (heightM * heightM);
System.out.printf("BMI = %.2f => ", bmi);
if (bmi < 18.5) {
    System.out.println("Underweight");
} else if (bmi < 25.0) {
    System.out.println("Normal weight");
} else if (bmi < 30.0) {
    System.out.println("Overweight");
} else {
    System.out.println("Obese");
}
  • Each test only needs the upper bound: earlier branches already ruled out smaller values.
  • printf("%.2f") prints two decimals.

Code walkthrough 6 of 10 · Lab1Demo.java

switch with fall-through

int score = 85;
char grade;
switch (score / 10) {
    case 10:
    case 9:
        grade = 'A';
        break;
    case 8:
        grade = 'B';
        break;
    case 7:
        grade = 'C';
        break;
    case 6:
        grade = 'D';
        break;
    default:
        grade = 'F';
}
  • score / 10 is integer division: 85 → 8.
  • case 10: has no break, so it falls through to case 9.
  • default catches everything else.

Code walkthrough 7 of 10 · Lab1Demo.java

for loop: summation

// 5. For Loop
System.out.println("\n=== For Loop: Summation 1 to n ===");
int upperBound = 10;
int sum = 0;
for (int i = 1; i <= upperBound; i++) {
    sum = sum + i;
}
System.out.println("Sum of 1 to " + upperBound + " = " + sum);
  • Initialise, test, update — all in the loop header.

Code walkthrough 8 of 10 · Lab1Demo.java

continue and break

System.out.print("Even numbers from 1 to 20, skipping multiples of 6: ");
for (int i = 1; i <= 20; i++) {
    if (i % 6 == 0) {
        continue;
    }
    if (i > 18) {
        break;
    }
    if (i % 2 == 0) {
        System.out.print(i + " ");
    }
}
System.out.println();
  • continue skips multiples of 6.
  • break stops the loop once i passes 18.

Code walkthrough 9 of 10 · Lab1Demo.java

while loop: reverse the digits

// 6. While Loop
System.out.println("\n=== While Loop: Reverse Digits ===");
int number = 12345;
int temp = number;
int reversed = 0;
while (temp != 0) {
    int digit = temp % 10;
    reversed = reversed * 10 + digit;
    temp = temp / 10;
}
System.out.println("Original number: " + number);
System.out.println("Reversed number: " + reversed);
  • % 10 takes the last digit; / 10 removes it.
  • The loop runs until no digits are left.

Code walkthrough 10 of 10 · Lab1Demo.java

do-while: the Collatz sequence

// 7. Do-While Loop
System.out.println("\n=== Do-While Loop: Collatz Sequence ===");
long collatz = 27;
int steps = 0;
System.out.print("Sequence: ");
do {
    System.out.print(collatz + " ");
    if (collatz % 2 == 0) {
        collatz = collatz / 2;
    } else {

Code walkthrough 10 of 10 · Lab1Demo.java

do-while: the Collatz sequence (cont.)

        collatz = 3 * collatz + 1;
    }
    steps++;
} while (collatz != 1);
System.out.println("1");
System.out.println("Steps to reach 1: " + steps);
  • The body runs before the test, so 27 is printed first.
  • Even → halve; odd → 3n + 1; stop at 1.

Step through the code · 1 of 3

Trace: widening and narrowing

Watch each variable appear in main’s stack frame and see exactly what a cast keeps.

Step through the code · 1 of 3

Trace: widening and narrowing (cont.)

Step through the code · 2 of 3

Trace: reversing the digits

Follow temp, digit and reversed through every pass of the while loop.

Step through the code · 2 of 3

Trace: reversing the digits (cont.)

Step through the code · 3 of 3

Trace: switch, case by case

Pick a score. See which case the switch jumps to, how 100 falls through into case 9, and what break does.

Step through the code · 3 of 3

Trace: switch, case by case (cont.)

For reference · 1 file

The complete program

public class Lab1Demo {
    public static void main(String[] args) {

        // 1. Primitive Data Types and String
        byte byteVal = 100;
        short shortVal = 30000;
        int age = 21;
        long bigNum = 9876543210L;
        float gpa = 3.75f;
        double height = 5.91;
        char initial = 'A';
        boolean isStudent = true;
        String name = "Mozdaher Abdul Quader";

        System.out.println("=== Primitive Data Types and String ===");
        System.out.println("byte    : " + byteVal);
        System.out.println("short   : " + shortVal);
        System.out.println("int     : " + age);
        System.out.println("long    : " + bigNum);
        System.out.println("float   : " + gpa);
        System.out.println("double  : " + height);
        System.out.println("char    : " + initial + " (Unicode = " + (int) initial + ")");
        System.out.println("boolean : " + isStudent);
        System.out.println("String  : " + name);

        // 2. Type Casting
        System.out.println("\n=== Type Casting ===");
        double ageAsDouble = age;
        System.out.println("int " + age + " widened to double: " + ageAsDouble);

        double pi = 3.14159;
        int piTruncated = (int) pi;
        System.out.println("double " + pi + " narrowed to int: " + piTruncated);

        char letter = 'Z';
        int code = letter;
        char nextChar = (char) (code + 1);
        System.out.println("char 'Z' as int: " + code + " | next char: " + nextChar);

        // 3. Conditional Statement
        System.out.println("\n=== Conditional Statement ===");
        int n = 42;
        if (n > 0) {
            System.out.println(n + " is Positive");
        } else if (n == 0) {
            System.out.println(n + " is Zero");
        } else {
            System.out.println(n + " is Negative");
        }

        double weightKg = 70.0;
        double heightM = 1.75;
        double bmi = weightKg / (heightM * heightM);
        System.out.printf("BMI = %.2f => ", bmi);
        if (bmi < 18.5) {
            System.out.println("Underweight");
        } else if (bmi < 25.0) {
            System.out.println("Normal weight");
        } else if (bmi < 30.0) {
            System.out.println("Overweight");
        } else {
            System.out.println("Obese");
        }

        // 4. Switch Statement
        System.out.println("\n=== Switch Statement: Grade Classifier ===");
        int score = 85;
        char grade;
        switch (score / 10) {
            case 10:
            case 9:
                grade = 'A';
                break;
            case 8:
                grade = 'B';
                break;
            case 7:
                grade = 'C';
                break;
            case 6:
                grade = 'D';
                break;
            default:
                grade = 'F';
        }
        System.out.println("Score: " + score + " => Grade: " + grade);

        // 5. For Loop
        System.out.println("\n=== For Loop: Summation 1 to n ===");
        int upperBound = 10;
        int sum = 0;
        for (int i = 1; i <= upperBound; i++) {
            sum = sum + i;
        }
        System.out.println("Sum of 1 to " + upperBound + " = " + sum);

        System.out.print("Even numbers from 1 to 20, skipping multiples of 6: ");
        for (int i = 1; i <= 20; i++) {
            if (i % 6 == 0) {
                continue;
            }
            if (i > 18) {
                break;
            }
            if (i % 2 == 0) {
                System.out.print(i + " ");
            }
        }
        System.out.println();

        // 6. While Loop
        System.out.println("\n=== While Loop: Reverse Digits ===");
        int number = 12345;
        int temp = number;
        int reversed = 0;
        while (temp != 0) {
            int digit = temp % 10;
            reversed = reversed * 10 + digit;
            temp = temp / 10;
        }
        System.out.println("Original number: " + number);
        System.out.println("Reversed number: " + reversed);

        // 7. Do-While Loop
        System.out.println("\n=== Do-While Loop: Collatz Sequence ===");
        long collatz = 27;
        int steps = 0;
        System.out.print("Sequence: ");
        do {
            System.out.print(collatz + " ");
            if (collatz % 2 == 0) {
                collatz = collatz / 2;
            } else {
                collatz = 3 * collatz + 1;
            }
            steps++;
        } while (collatz != 1);
        System.out.println("1");
        System.out.println("Steps to reach 1: " + steps);
    }
}

Copy or download each file, save it under the same name, then compile and run: javac *.java → java Lab1Demo

Implementation

Expected output

Why is the next char after Z a “[”? Characters are numbers: 'Z' is 90, and 91 is '['.

Interactive 1 of 5

Try widening and narrowing

Interactive 2 of 5

Evaluate operators step by step

Interactive 3 of 5

Follow an if-else ladder

Interactive 4 of 5

Watch switch and fall-through

Interactive 5 of 5

Compare the three loops

In-lab task 1 of 4

Task 1: Temperature converter

Read a temperature in Celsius and convert it to Fahrenheit, Kelvin and Rankine: F = C × 1.8 + 32, K = C + 273.15, R = F + 459.67.
Requirements
Show a hint
Read with Scanner sc = new Scanner(System.in); double c = sc.nextDouble(); and compute F first, because R depends on it.

In-lab task 2 of 4

Task 2: FizzBuzz extended

Print 1 to 50: FizzBuzz if divisible by 3 and 5, Fizz for 3, Buzz for 5, Boom for 7, otherwise the number.
Requirements
Show a hint
Order matters: once one branch of an if-else chain matches, the rest are skipped. Use i % 15 == 0 or i % 3 == 0 && i % 5 == 0 first.

In-lab task 3 of 4

Task 3: Number system classifier

Read an integer and classify it by the remainder when divided by 4: 0 → Divisible by 4, 1 or 3 → Odd, 2 → Even, not divisible by 4.
Requirements
Show a hint
case 1: case 3: can share one body. Careful with negative numbers: -3 % 4 is -3 in Java.

In-lab task 4 of 4

Task 4: Digit frequency counter

Read a positive integer and count how often each digit 0–9 appears.
Requirements
Show a hint
Inside the loop: freq[n % 10]++; n /= 10;. Use long if you want very large inputs.

In-lab tasks

Show your work during the lab

For each task, show the instructor:

  • the source code
  • a successful compilation
  • the running output
  • a short explanation of the logic you used

Lab report · exercise 1 of 2

Student grade management system

Manage the marks of five students in Mathematics, Physics and Chemistry.
Requirements

Lab report · exercise 2 of 2

Pattern & sequence explorer

A menu-driven program: 1. Pascal’s triangle, 2. Primes by the Sieve of Eratosthenes, 3. Perfect numbers up to 10000, 4. Exit.
Requirements

Lab report

Writing the lab report

  • Problem statement and your design (classes, fields, methods)
  • Complete source code, formatted and commented
  • Sample output or screenshots for normal and edge cases
  • A short discussion: what each OOP concept did in your program

Academic integrity

Copying from the internet, classmates, seniors or any other unauthorized source is strictly prohibited. Full marks may be deducted if plagiarism, copied work or academic dishonesty is detected. Complete the tasks, implementation, output analysis and report yourself.

Discussion and analysis

Viva questions (1 of 2)

Why is Java called statically typed, and how does that help?
Show the answer
Every variable must be declared with a type before use, so the compiler catches type errors (for example assigning 3.7 to an int without a cast) before the program runs.
What does (int) 99.99 give, and why must the cast be written?
Show the answer
99. Narrowing can lose data (the fraction is truncated), so Java makes you state it explicitly.

Discussion and analysis

Viva questions (2 of 2)

When would you choose do-while over while?
Show the answer
When the body must run at least once, such as showing a menu or the first value of the Collatz sequence.
What happens if you remove a break from a switch case?
Show the answer
Execution falls through into the next case and runs its statements too, until a break or the end of the switch.

Check yourself

Quiz

Summary

Summary

  • javac turns .java source into .class bytecode; the JVM runs it starting from main.
  • Eight primitive types plus String; Java checks types at compile time.
  • Widening is automatic; narrowing needs a cast and can lose data.
  • if-else for conditions and ranges, switch for fixed values (remember break).
  • for when the count is known, while for conditions, do-while to run at least once.