Skip to content

VOL 01 / CH 02 / LESSON 04

2.4 Lab: Variables, Types, and Conversion ​

Prerequisites: Pages 1-3 of this chapter

Estimated time: 40 minutes

Exercise environment: JDK 17+ and Bash; all files written to a temporary directory

You are ready to continue when: You have completed four required experiments and record predictions and actual results

bash
chapter2_lab_root=$(mktemp -d)
readonly chapter2_lab_root
mkdir -p "$chapter2_lab_root/chapter02-lab/out"
cd "$chapter2_lab_root/chapter02-lab"

Required Exercise 1: Declarations, Scope and final ​

Save as Profile.java:

java
public class Profile {
    public static void main(String[] args) {
        String name = "Lin";
        int age = 20;
        double heightMeters = 1.72;
        char initial = 'L';
        boolean learningJava = true;
        final int birthYear = 2006;

        System.out.println(name);
        System.out.println(age);
        System.out.println(heightMeters);
        System.out.println(initial);
        System.out.println(learningJava);
        System.out.println(birthYear);
    }
}
bash
javac -d out Profile.java
java -cp out Profile

Then try each of the following separately:

  • Assign a new integer value to age before printing;
  • Assign a string to age and observe the compilation error;
  • Assign a value to birthYear and observe the final constraint.

Introduce one failure at a time, record the first diagnostic, then restore the source. Also move the declaration of age into a separate { ... } block while keeping its print statement outside; observe the out-of-scope compilation error.

Required Exercise 2: Ranges, Overflow, and Checked Arithmetic ​

Save as IntegerBoundaries.java:

java
public class IntegerBoundaries {
    public static void main(String[] args) {
        int max = Integer.MAX_VALUE;
        System.out.println(max);
        System.out.println(max + 1);

        try {
            System.out.println(Math.addExact(max, 1));
        } catch (ArithmeticException error) {
            System.out.println("overflow detected");
        }
    }
}

Compile and run:

bash
javac -d out IntegerBoundaries.java
java -cp out IntegerBoundaries

Expected output:

text
2147483647
-2147483648
overflow detected

In your lab notebook, explain the difference in failure strategies between the standard + and Math.addExact.

Required Exercise 3: Floating Point Precision and Decimal Rules ​

Save as DecimalDemo.java:

java
import java.math.BigDecimal;

public class DecimalDemo {
    public static void main(String[] args) {
        double binary = 0.1 + 0.2;
        BigDecimal decimal = new BigDecimal("0.1")
                .add(new BigDecimal("0.2"));

        System.out.println(binary);
        System.out.println(binary == 0.3);
        System.out.println(decimal);
    }
}

Compile and run:

bash
javac -d out DecimalDemo.java
java -cp out DecimalDemo

Expected output:

text
0.30000000000000004
false
0.3

Do not conclude that double cannot be used. Write two applicable scenarios: numerical calculations that allow for measurement error, and business calculations that must adhere to exact decimal rules.

Required Exercise 4: Promotion, Narrowing, and Text Parsing ​

Save as ConversionLab.java:

java
public class ConversionLab {
    public static void main(String[] args) {
        byte left = 10;
        byte right = 20;
        int sum = left + right;

        int source = 1000;
        byte narrowed = (byte) source;

        long precise = 9_007_199_254_740_993L;
        double widened = precise;

        int parsed = Integer.parseInt("42");

        System.out.println(sum);
        System.out.println(narrowed);
        System.out.println((long) widened);
        System.out.println(parsed);
    }
}

Predict the output of the next four lines, then run:

bash
javac -d out ConversionLab.java
java -cp out ConversionLab

Expected output:

text
30
-24
9007199254740992
42

These four lines respectively verify binary numeric promotion, integer narrowing, precision loss after widening, and text parsing.

Optional Exercise 1: Limits of var ​

java
public class VarDemo {
    public static void main(String[] args) {
        var city = "Beijing";
        var count = 42;
        var ratio = 0.5F;

        System.out.println(city.getClass().getSimpleName());
        System.out.println(count + 1);
        System.out.println(ratio + 0.25F);
    }
}

After verification, try var missing;, var unknown = null;, and city = 42; in sequence. The reasons for the three failures are not the same: missing initializer, no inferable type, and incompatible inferred type.

Optional Exercise 2: One Symbol May Need More Than One char ​

java
public class UnicodeDemo {
    public static void main(String[] args) {
        String symbol = "😀";
        System.out.println(symbol.length());
        System.out.println(symbol.codePointCount(0, symbol.length()));
        System.out.printf("U+%X%n", symbol.codePointAt(0));
    }
}

Expected: UTF-16 length is 2, number of code points is 1, and the code point is U+1F600.

Temperature Converter ​

java
double fahrenheit = 100.0;
double celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
System.out.println(celsius);

Use floating-point literals to explicitly express floating-point operations. If the requirement specifies displaying two decimal places, additional rules for rounding and formatting must be specified; the long decimal output of the original double is not part of the final user interface specification.

Troubleshooting Quick Reference ​

Key DiagnosisCheck First
variable might not have been initializedWas the local variable assigned a value before it is read
possible lossy conversionIs it a narrowing conversion; has the range been validated
integer number too largedecimal literals require L or have exceeded long
bad operand typesAre the types on either side of the operator supported
NumberFormatExceptionInput text, radix, and whitespace handling conform to conventions
cannot infer type for local variablevar has an initializer that can be inferred and is not null

The original diagnosis may vary with JDK changes; prioritize checking compile-time versus runtime first, then examine the first key reason.

Safe Cleanup ​

bash
pwd
test ! -e out || rm -r -- out

Delete this experiment's out only after pwd confirms the current directory is the correct one for this experiment. Do not expand the path or delete other sections' products.

Acceptance and Cleanup ​

Confirm that you have actually observed the differences between regular overflow and the exact method, the numeric promotion in byte + byte, the loss of precision after widening, and a scenario where a symbol occupies two char. Then clean up the entire experiment directory:

bash
cd
ls -ld -- "$chapter2_lab_root"
rm -r -- "$chapter2_lab_root"

The next chapter will combine values into computations and judgments.

→ Next Step: Expressions and Operators

Built with VitePress | Software Systems Atlas