Overview
An expression combines values, variables, operators, and method calls to produce a single value. Output displays information to the user, typically with System.out.print() or System.out.println().
1) Expressions
Expressions range from a literal like 10 to complex formulas like (a + b) * c / 2. Java follows operator precedence and type conversion rules.
Arithmetic Expressions
Use +, -, *, /, and % (remainder).
int sum = 5 + 3 * 2; // 11
int remainder = 10 % 3; // 1
String Expressions
Use + for concatenation (joining text).
String name = "Mr. " + "Cusack"; // "Mr. Cusack"
Boolean Expressions
Produce true or false using relational and logical operators.
boolean result = (5 > 3) && (2 < 4); // true
// Relational: > < >= <= == !=
// Logical: &&, ||, !
2) Operator Precedence
Determines evaluation order. Use parentheses for clarity.
| Priority | Operators |
|---|---|
| Highest | () (parentheses) |
*, /, % | |
+, - | |
Relational: <, >, <=, >= | |
Equality: ==, != | |
Logical AND: && | |
| Lowest | Logical OR: || |
int a = 5 + 3 * 2; // 11
int b = (5 + 3) * 2; // 16
3) Type Conversion (Casting)
Java promotes types automatically when mixing int and double. Use casting to control results.
double avg1 = (3 + 4 + 5) / 3; // 12 / 3 = 4 (integer division → 4.0)
double avg2 = (3 + 4 + 5) / 3.0; // 12 / 3.0 = 4.0 (double)
double avg3 = (double)(3 + 4 + 5) / 3; // 12.0 / 3 = 4.0
Note: If all operands of / are int, Java performs integer division and truncates decimals.
4) Output Statements
Use System.out.print() (no newline) and System.out.println() (adds newline).
System.out.print("Hello");
System.out.println(" World!");
// Output: Hello World!
5) Escape Sequences
| Sequence | Description |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\\ | Backslash |
System.out.println("Hello\nWorld!");
/* Output:
Hello
World!
*/
6) Combining Expressions and Output
int age = 17;
System.out.println("You are " + age + " years old.");
// You are 17 years old.
7) Common Pitfalls
- Integer division truncates:
5 / 2is2, not2.5. - Concatenation order matters:
System.out.println("Sum: " + 2 + 3); // Sum: 23 System.out.println("Sum: " + (2 + 3)); // Sum: 5 - Use parentheses to control evaluation order and readability.
✅ Summary
| Concept | Description | Example |
|---|---|---|
| Expression | Values + variables + operators → one value | x + y * 2 |
| Output | Display with print/println | System.out.println("Hi"); |
| Arithmetic | Math operators | a + b, x % y |
| Boolean | True/false logic | (x > 5) && (y < 10) |
| Precedence | Evaluation order | 3 + 4 * 2 = 11 |
| Type Casting | Change data type | (double) sum / count |
| Escape Sequences | Formatting in strings | \n, \t, \" |
Tip: Add small, runnable snippets in your IDE so students can see actual outputs.