DI-322 Web Technologies Lecture 10: Java, variables, types and control structures
DI-322 Web Technologies
0% Completed

Lecture 10: Java, variables, types and control structures

Outcomes and readiness

You can compile and run a small Java program, select suitable primitive/reference types, trace conditions and loops, and handle boundary input. Readiness: variables, assignment, Boolean conditions, and loops from Programming Fundamentals.

Program model

Java source is compiled to class files for a Java Virtual Machine. The selected course baseline is Java 17; this is an instructional choice because the outline gives no version. A program’s main method receives strings and begins the example below.

public class GradeBand {
    static String band(int score) {
        if (score < 0 || score > 100) return "invalid";
        if (score >= 80) return "A";
        if (score >= 70) return "B";
        if (score >= 60) return "C";
        return "F";
    }

    public static void main(String[] args) {
        int[] scores = {80, 79, 0, 101};
        for (int score : scores) {
            System.out.println(score + " -> " + band(score));
        }
    }
}

Expected trace: 80 -> A, 79 -> B, 0 -> F, 101 -> invalid.

Types and state

int, long, double, boolean, and char are primitive types; String, arrays, and user classes are reference types. Choose types for meaning and range, not merely habit. Integer division truncates toward zero: 7 / 2 is 3; 7.0 / 2 is 3.5. Local variables must be definitely assigned before use.

Faded example

Complete a loop that sums inclusive integers 1 through n.

int total = 0;
for (int i = 1; ______; i++) total += i;

Hint: include n. Solution: i <= n. For n < 1, specify whether the result is zero or input is rejected.

Common mistakes

  • = assigns; == compares primitive values.
  • Comparing strings with == tests reference identity, not text equality; use .equals when appropriate.
  • An off-by-one loop often mishandles 0, 1, or the final element.

Practical – DI322-LAB10

Implement a command-line marks analyzer: validate 0-100, print grade band, count passes, and calculate an average without accidental integer division. Test empty input, boundaries 0/49/50/100, invalid -1/101, and repeated values. Record actual compiler/runtime version and output; if unavailable, mark the trace as unexecuted.

Independent check

Q1 Source becomes what before JVM execution? Class/bytecode files. Q2 int x = 3; x++; final value? 4. Q3 7 / 2? 3. Q4 Loop condition for indices of a length-5 array? i < 5.

Homework – DI322-A10-H1

Write a menu-driven unit converter with at least four conversions, input validation, and repeated operation until exit. Rubric: correct control flow 3, types/calculations 2, boundary handling 2, methods/readability 2, test evidence 1.

Revision

Trace state after every statement. Test lower boundary, normal value, upper boundary, and invalid values before trusting a program.