Java Expressions, Type Casting, and Code Tracing, CS312 – Study Notes
offline

Overview

Date: CS312 Credit by Exam, Sample 2 | Source: University of Texas at Austin, Introduction to Computer Programming

Tags: Java expressions, type casting, integer division, string concatenation, boolean logic, operator precedence, Math.round, code tracing, array output, object references

Difficulty: Intermediate. Prerequisites: basic Java syntax, primitive types, and familiarity with if/else and loops.

This material covers how Java evaluates mixed-type expressions, how strings interact with the + operator, and how to trace code output by hand. These are the bread-and-butter skills tested on every CS312 exam. If you can evaluate an expression correctly on paper, you can debug one in code. If you can trace a loop by hand, you can predict what any short programme will print. This is the foundation everything else in the course builds on.


TL;DR

Java expressions follow strict rules about type promotion, integer division, and string concatenation order. Getting the right answer on paper means knowing when Java silently converts an int to a double, when the + operator concatenates instead of adding, and how boolean operators short-circuit. Code tracing questions test whether you can mentally execute loops, track array contents, and follow object references step by step.


Key Terms

Type promotion (widening conversion)

When Java automatically converts a narrower numeric type to a wider one during an operation. For example, an int becomes a double when it appears in an expression with a double operand.

In simple terms, Java "upgrades" the smaller type so both sides match before doing the maths.

Integer division (truncation)

When both operands of the / operator are integers, Java discards the decimal portion entirely. 7 / 2 gives 3, not 3.5.

Think of it as: Java chops off the remainder with no rounding whatsoever.

String concatenation

The + operator, when at least one operand is a String, joins values together as text rather than performing arithmetic. Java evaluates left to right, so 2 + 3 + "hi" gives "5hi", but "hi" + 2 + 3 gives "hi23".

In simple terms, once Java hits a String in a left-to-right chain of + operations, everything after it becomes glued-on text.

Boolean short-circuit evaluation

With && (and) and || (or), Java stops evaluating as soon as the result is determined. If the left side of && is false, the right side never runs. If the left side of || is true, the right side never runs.

Think of it as: Java is lazy and skips work it does not need to do.

Math.round()

Returns the closest long to the argument. Ties (exactly halfway values) round toward positive infinity. So Math.round(-4.5) returns -4, not -5, which catches many students off guard.

In simple terms, for negative halfway cases, it rounds toward zero rather than away from it.

Operator precedence

The order in which Java evaluates operators. Multiplication and division happen before addition and subtraction. Parentheses override everything. The == and != comparisons happen after arithmetic but before && and ||.

Think of it as: PEMDAS from secondary school maths, extended with comparison and logic layers.

Code tracing

The process of manually stepping through code line by line, tracking variable values, to predict the output. The single most useful exam skill in CS312.

In simple terms, you become the computer, executing each line in order and writing down what changes.


Core Content

Expression Evaluation Rules

  • Java evaluates expressions left to right, respecting operator precedence

  • When int and double appear in the same operation, the int is promoted to double and the result is double

    • Example: 3 + 2.5 gives 5.5 (the 3 becomes 3.0 first)

  • Integer division truncates toward zero: 7 / 2 = 3, -7 / 2 = -3

    • To force decimal division, make at least one operand a double: 7 / 2.0 = 3.5

  • The % (modulus) operator gives the remainder: 7 % 2 = 1

  • Casting with (int) or (double) converts explicitly: (int) 3.9 gives 3 (truncation, not rounding)

String Concatenation Behaviour

  • The + operator concatenates when at least one operand is a String

  • Evaluation proceeds left to right, so the position of the String matters enormously

    • 1 + 2 + "abc" evaluates as (1 + 2) + "abc" = "3abc"

    • "abc" + 1 + 2 evaluates as ("abc" + 1) + 2 = "abc12"

  • Boolean values become the text "true" or "false" when concatenated with a String

    • false + "H" + 10 + 1.5 becomes "falseH101.5" (all string concatenation after the boolean is joined to a String)

  • Concatenation does not add spaces. If you want spaces, you must include them explicitly

Boolean Expressions and Comparisons

  • The == operator compares primitive values directly

  • For objects (including Strings), == checks reference equality (same object in memory), not content. Use .equals() for content comparison

  • Short-circuit evaluation: false && (anything) skips the right side; true || (anything) skips the right side

  • The ! operator negates: !true is false, !false is true

Math Class Methods

  • Math.round(double) returns a long, rounding to the nearest integer

    • Ties (halfway values like 2.5) round toward positive infinity

    • Math.round(2.5) = 3 (rounds up)

    • Math.round(-4.5) = -4 (rounds toward positive infinity, which is up toward zero, not away from it)

    • This is the single most surprising result on the exam. Students expect -4.5 to round to -5.

  • Math.abs() returns the absolute value

  • Math.pow(base, exponent) returns base raised to the exponent as a double

  • Math.random() returns a double in the range [0.0, 1.0)

Code Tracing Techniques

  • Draw a table of variables and update values line by line

  • For arrays, write out the full contents at each step, noting index changes

  • For objects, track which reference points to which instance

  • Watch for aliasing: two variables pointing to the same array means changes through one are visible through the other

    • Example: if arr2 = arr1, then arr2[0] = 99 also changes arr1[0]

  • For ArrayList output, use square brackets with commas: [3, 2, 12, 7, 1]

  • When tracing methods, note whether parameters are primitives (copied) or references (shared)

Object and Inheritance Tracing

  • When a subclass object is created, the superclass constructor runs first

  • Method calls on an object use the actual type (runtime type), not the declared type

  • Private fields are not accessible outside the class, even from subclasses

    • Attempting to access a private field from outside produces a syntax (compile) error

  • The toString() method is called automatically when an object is printed or concatenated with a String

  • Static methods belong to the class, not instances. They cannot access instance variables directly


Common Misconceptions

  • Students often think (int) rounds a double. It does not. It truncates, discarding the decimal entirely. (int) 3.9 is 3, not 4.

  • Students often think Math.round(-4.5) gives -5. It gives -4. Ties round toward positive infinity, not away from zero.

  • Students often think 1 / 2 in Java gives 0.5. It gives 0. Both operands are ints, so Java performs integer division.

  • Students often think "abc" + 1 + 2 gives "abc3". It gives "abc12". Once concatenation starts, each subsequent + joins text. The 1 and 2 are never added together.

  • Students often confuse == and .equals() for Strings. Using == on two String objects checks whether they are the same object in memory, not whether they contain the same text. Use .equals() to compare String contents.

  • Students often think va++ is valid Java. It is not. The ++ operator works only on variables, not on arbitrary expressions. va++ on a String variable is a syntax error.


Why It Matters / Exam Flags

  • Expression evaluation is worth 1 point per sub-question, with deductions for missing or extra quotation marks and trailing .0 on double results. Capitalization of true and false does not matter.

  • Code tracing questions also carry 1 point each, with -1 for incorrect answers. Array output must use square brackets, but differences in spacing and commas are accepted.

  • Know the difference between syntax errors (code will not compile) and runtime errors (code compiles but crashes). The exam tests both.

  • Private field access from outside a class is a syntax error, not a runtime error. The compiler catches it.

  • Pay close attention to whether a method is static or instance-level. Static methods cannot use instance variables.

  • When tracing code involving arrays and object references, aliasing (two references to the same array) is a favourite exam trick.


Quick Self-Test

  1. True or false: 5 / 2 in Java evaluates to 2.5. (Answer: False. It evaluates to 2, because both operands are ints.)

  1. Fill in the blank: "hi" + 3 + 4 evaluates to ______. (Answer: "hi34")

  1. True or false: Math.round(-2.5) returns -3. (Answer: False. It returns -2, because ties round toward positive infinity.)

  1. Fill in the blank: If int x = 7; then (double) x / 2 evaluates to ______. (Answer: 3.5)

  1. True or false: Using == to compare two Strings checks whether they contain the same characters. (Answer: False. It checks reference equality. Use .equals() for content comparison.)


Practice Q&A

Q: What is the result of the expression: 3 + 4.0 * 2?

A: 11.0. Multiplication happens first (4.0 * 2 = 8.0), then addition with type promotion (3 + 8.0 = 11.0).

Q: What does the following print? System.out.println(false + "H" + 10 + 1.5);

A: falseH101.5. The boolean false is converted to the String "false", then each subsequent + concatenates: "false" + "H" = "falseH", then + 10 = "falseH10", then + 1.5 = "falseH101.5".

Q: What is the value of (int)(7.0 / 2)?

A: 3. The division 7.0 / 2 gives 3.5 (double division because one operand is double), then (int) truncates to 3.

Q: What does the following code output if arr = {3, 5, 7} and arr2 = arr; arr2[1] = 99; System.out.println(Arrays.toString(arr));?

A: [3, 99, 7]. Because arr2 and arr refer to the same array in memory (aliasing), the change through arr2 is visible through arr.

Q: Is the following valid Java? String s = "hello"; s++;

A: No. This is a syntax error. The ++ operator cannot be applied to Strings. It works only on numeric types.

Q: What does Math.round(-4.5) return?

A: -4. The Math.round() method rounds ties toward positive infinity. Since -4 is closer to positive infinity than -5, the result is -4.

Q: What is the output of: System.out.println(10 % 3 + " remainder");

A: 1 remainder. The modulus 10 % 3 = 1, then concatenation with " remainder" gives "1 remainder".


Connections to Other Topics

Expression evaluation connects directly to array indexing, because incorrect index arithmetic (off-by-one errors from integer division or misunderstanding operator precedence) is one of the most common bugs in array problems. It also connects to method writing, where return types must match the expression type, and to object-oriented programming, where understanding reference equality (==) versus content equality (.equals()) is critical for working with objects and inheritance.


Related Terms / Search Tags

Java type casting, widening conversion, narrowing conversion, implicit type promotion, explicit cast, integer division Java, truncation vs rounding, String concatenation order, operator precedence Java, boolean short-circuit, Math.round ties, Math.round negative, code tracing by hand, variable tracking table, array aliasing, reference vs value, == vs .equals Java, syntax error vs runtime error, compile-time error