Getting Started
Nearly every useful computer program needs to perform calculations and show the results to a user. To accomplish these fundamental tasks, we must learn how Java handles mathematical computations and how it can print information to the screen. This chapter introduces expressions, the core building block for all calculations, and the commands used to produce console output.
What You Should Be Able to Do
Evaluate arithmetic expressions that use integers and floating-point numbers.
Apply operator precedence rules to determine the order of evaluation in a complex expression.
Use casting to deliberately convert a value from one primitive data type to another.
Write code to display variable values, string literals, and expression results to the console.
Combine strings with other data types for formatted output using the concatenation operator.
Key Concepts & Java Implementation
The Core Idea
In Java, an expression is a combination of values, variables, and operators that the computer evaluates to produce a single, resulting value. The simplest expression is a literal value (like 5 or 3.14), but they are typically more complex, such as 5 + 3. The values or variables in an expression are called operands, and the symbols that perform actions on them (like + or *) are called operators.
The data type of the operands is critical. When an arithmetic expression involves only int values, the result will be an int. If it contains at least one double value, the entire expression is "promoted," and the result will be a double. This distinction is especially important for division, as dividing two integers in Java results in an integer, with any fractional part being truncated (discarded).
Once an expression is evaluated, we often need to display its result. Java provides built-in methods for printing output to a standard console, allowing us to see the outcome of our program's computations.
Syntax & Implementation
Java uses standard mathematical operators. Their behavior depends on the data types of the operands.
Arithmetic Operators Table
| Operator | Purpose | Java Example (int x = 10, y = 4;) | Result |
|---|---|---|---|
+ | Addition | x + y | 14 |
- | Subtraction | x - y | 6 |
* | Multiplication | x * y | 40 |
/ | Division | x / y | 2 |
% | Modulo (Remainder) | x % y | 2 |
Annotated Java Examples
Operator Precedence
Java evaluates expressions using a well-defined order of operations, similar to PEMDAS in mathematics. Multiplication (
*), division (/), and modulo (%) have higher precedence than addition (+) and subtraction (-).// Multiplication is performed before addition. int result = 5 + 3 * 2; // Evaluates 3 * 2 first, resulting in 6. Then 5 + 6. System.out.println(result); // Prints 11 // Parentheses can be used to override the default precedence. int anotherResult = (5 + 3) * 2; // Evaluates 5 + 3 first, resulting in 8. Then 8 * 2. System.out.println(anotherResult); // Prints 16Integer vs. Double Division
The result of the
/operator depends on its operands' types.// When both operands are integers, the result is an integer (truncated). int intDivision = 7 / 2; System.out.println(intDivision); // Prints 3, not 3.5 // If at least one operand is a double, the result is a double. double doubleDivision = 7.0 / 2; System.out.println(doubleDivision); // Prints 3.5Casting
Casting is an operation that explicitly converts a value of one data type into another. This is often used to force floating-point division when you have integer variables.
int numerator = 7; int denominator = 2; // Cast the numerator to a double BEFORE the division occurs. double preciseResult = (double) numerator / denominator; System.out.println(preciseResult); // Prints 3.5 // Casting can also convert a double to an int (truncating the decimal). double value = 9.8; int truncatedValue = (int) value; System.out.println(truncatedValue); // Prints 9Output and String Concatenation
To print output, we use
System.out.print()orSystem.out.println(). The+operator, when used with aString, performs concatenation, which joins the string with the other operand's string representation.String label = "Score: "; int score = 95; // System.out.println() prints the text and moves to a new line. System.out.println("Hello, World!"); // System.out.print() prints the text and leaves the cursor on the same line. System.out.print("Player 1"); System.out.print(" is winning."); // Use concatenation to combine strings and variables for formatted output. // The int 'score' is automatically converted to a String. System.out.println(label + score); // Prints "Score: 95" on a new line
Tracing & Analysis
Execution Trace
Let's trace the evaluation of a complex expression to see precedence rules in action.
Code:
int finalValue = 10 + 8 / 2 * 3 % 5;8 / 2is evaluated first (division has high precedence, evaluated left-to-right):10 + 4 * 3 % 54 * 3is evaluated next (multiplication):10 + 12 % 512 % 5is evaluated next (modulo has same precedence as*and/):10 + 210 + 2is evaluated last (addition has lower precedence):12The final value assigned to
finalValueis12.
Analysis
A common logical error occurs when programmers forget about integer division. Consider calculating an average:
int sum = 15; int count = 2; double average = sum / count;. The variableaveragewill hold7.0, not7.5. This is because the integer division15 / 2is performed first, resulting in7. That integer7is then assigned to thedoublevariable, becoming7.0. To get the correct result, you must cast one of the operands:double average = (double) sum / count;.
Java Syntax Quick-Reference
A summary of the key syntax introduced in this topic.
| Syntax | Purpose |
|---|---|
+, -, *, /, % | Standard arithmetic operators for addition, subtraction, multiplication, division, and modulo. |
(type) expression | Casts the result of the expression to the specified type (e.g., (double) 5). |
System.out.println(value) | Prints the value to the console, followed by a new line character. |
System.out.print(value) | Prints the value to the console without moving to a new line. |
String + value | Concatenates (joins) a String with another value, converting the value to its String form first. |
Core Code Examples & Terminology
Expression: A combination of literals, variables, and operators that evaluates to a single value.
Operator: A symbol (e.g.,
+,*) that performs an operation on one or more operands.Casting: The explicit conversion of a data type to another, such as
(int)or(double).Concatenation: The operation of joining character strings end-to-end using the
+operator.Core Snippet 1 (Operator Precedence)
int result = 10 - 2 * 3; // result is 4This demonstrates that multiplication (
*) is performed before subtraction (-).Core Snippet 2 (Integer Division)
int quotient = 15 / 4; // quotient is 3This shows that dividing two integers results in an integer, with the remainder discarded.
Core Snippet 3 (Casting for Precision)
double preciseQuotient = (double) 15 / 4; // preciseQuotient is 3.75This shows how to cast an integer to a
doubleto force floating-point division.Core Snippet 4 (Output with Concatenation)
int items = 25; System.out.println("Total items: " + items);This prints a descriptive label along with the value of a variable to the console.
Core Skill Check
Code Tracing: What is the final value of
xafter this Java code runs:int x = 20 % 6 + 10 / 4 * 2;?Answer: 6
Debugging: Identify the logical error in this Java code intended to find the average of
aandb:int a = 5; int b = 6; double avg = (a + b) / 2;.Answer: The division
(a + b) / 2is integer division, resulting in5. The result should be5.5. It should be written asdouble avg = (a + b) / 2.0;ordouble avg = (double)(a + b) / 2;.Application: Write a single line of Java code that prints the remainder when an integer variable
totalis divided by10.Answer:
System.out.println(total % 10);
Common Misconceptions & Errors
Integer Division by Default: Assuming
5 / 2will produce2.5. In Java, if both operands are integers, the result is always a truncated integer (2). You must use adoubleliteral (e.g.,5 / 2.0) or casting to get a floating-point result.Incorrect Casting Order: Writing
(double) (x / y)whenxandyare integers. The integer divisionx / yhappens first inside the parentheses, and only then is the truncated result cast to adouble. The correct way is to cast one of the operands before the division:(double) x / y.Confusing
printandprintln: UsingSystem.out.print()in a loop and wondering why all the output appears on a single line. Remember thatprintlnadds a newline character after its output, whileprintdoes not.Order of Concatenation and Addition: In an expression like
System.out.println("Sum: " + 5 + 10);, the result is"Sum: 510", not"Sum: 15". Because evaluation proceeds left-to-right, the"Sum: "string concatenates with5first, producing"Sum: 5". This new string then concatenates with10. To perform the addition first, use parentheses:System.out.println("Sum: " + (5 + 10));.
Summary
Expressions are the foundation of computation in Java, allowing us to perform calculations using operators like +, -, *, /, and %. The outcome of an expression is heavily influenced by the data types of its operands and the rules of operator precedence. Integer division truncates decimals, a frequent source of bugs that can be resolved using casting or double literals. Finally, the System.out.println() and System.out.print() methods, combined with string concatenation, provide the essential tools for displaying the results of our expressions and communicating information to the user.