Java data types, operators and expressions
Java data types (primitive and reference), literals, type conversion and promotion, operators (arithmetic, relational, logical, bitwise, shift, assignment, ternary, instanceof), precedence, and expressions with evaluation order, short-circuiting, overflow, and IEEE‑754 behavior.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers write every Java program using data types, operators and expressions to compute results, control logic, and manipulate bits. Correct knowledge of sizes, conversion rules, precedence, and evaluation order avoids subtle bugs (overflow, truncation, short-circuit surprises) in real systems like device drivers, finance engines, and back-end services.
Key ideas
Primitive types: Built-in, non-object types with fixed sizes. Java primitives are: byte, short, int, long, char, float, double, boolean.
Reference types: Types whose values are references (pointers) to objects. Examples: classes (e.g., String), arrays, interfaces, enums, records. The special value null denotes no object.
Exact sizes and nature of Java primitives (as defined by the Java Language Specification):
- byte: 8-bit signed two’s complement; range −128 to 127.
- short: 16-bit signed two’s complement; range −32768 to 32767.
- int: 32-bit signed two’s complement.
- long: 64-bit signed two’s complement; suffix L or l for literals.
- char: 16-bit unsigned UTF-16 code unit; range '\u0000' (0) to '\uFFFF' (65535). Note: a Java char is not necessarily a full Unicode code point for characters beyond BMP (requires surrogate pairs).
- float: 32-bit IEEE 754 binary32; suffix F or f for literals.
- double: 64-bit IEEE 754 binary64; default for floating literals; suffix D or d optional.
- boolean: logical true/false; size not specified by the language; not numerically convertible.
Literals: Fixed values written directly in code.
- Integer literals: decimal (e.g., 42), hexadecimal (0x2A), binary (0b101010), octal (e.g., 052; a leading 0 denotes octal). Use underscores for readability (e.g., 1_000_000). Append L for long (e.g., 42L).
- Floating literals: decimal (3.14, 1e-3) or hexadecimal floating (0x1.8p1). Append F for float (e.g., 3.14F).
- Char literals: 'A', '\n', '\u03C0' (Greek small letter pi code unit).
- String literals: "Hello"; Strings are immutable reference types.
- Boolean literals: true, false.
- Null literal: null.
Variables and default values:
- Local variables must be explicitly initialized before use; no default.
- Fields (instance and static) of classes have default values: numeric 0/0.0, char '\u0000', boolean false, reference types null.
Operators (core categories and exact behavior):
- Arithmetic: +, −, *, /, % on numeric types. Division of integers truncates toward zero. The remainder operator % has the same sign as the dividend (left operand). Integer division by zero throws ArithmeticException; floating-point division by zero yields ±Infinity or NaN.
- Unary: +, −, ++, --, ~ (bitwise NOT), ! (logical NOT). Prefix ++x applies increment before value is used; postfix x++ uses value then increments.
- Relational and equality: <, <=, >, >= (numeric and char); ==, != (primitives and reference identity). For floating-point, comparisons follow IEEE-754: any comparison with NaN is false except != which is true.
- Logical: &&, ||, ! on boolean. && and || are short-circuiting (right operand evaluated only if needed).
- Bitwise and bitwise-logical: &, |, ^ on integer types; also on boolean with non-short-circuit semantics.
- Shift: << (left shift), >> (signed right shift with sign extension), >>> (unsigned right shift with zero-fill). Shift distance is masked: for int, distance is (rhs & 0x1F); for long, (rhs & 0x3F). Operands smaller than int are promoted to int before shifting.
- Assignment: = and compound assignments like +=, −=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=. Compound assignments include an implicit cast after numeric promotion.
- Ternary conditional: condition ? exprIfTrue : exprIfFalse; only one of the second/third operands is evaluated.
- Type check: instanceof tests at runtime whether a reference is an instance of a given type; returns boolean.
- String concatenation: + concatenates when at least one operand is a String; evaluation is left-to-right; non-String is converted via String.valueOf (which uses toString for objects and prints "null" for null references).
Precedence and associativity (highest to lowest overview):
- Postfix: expr++, expr--
- Unary: ++expr, --expr, +, −, ~, !, type cast
- Multiplicative: *, /, %
- Additive: +, −
- Shift: <<, >>, >>>
- Relational: <, <=, >, >=, instanceof
- Equality: ==, !=
- Bitwise AND: &
- Bitwise XOR: ^
- Bitwise OR: |
- Logical AND: &&
- Logical OR: ||
- Ternary: ? :
- Assignment: =, +=, −=, ... Associativity: most binary operators are left-associative; assignment and ternary associate right-to-left.
Expression evaluation order: Java evaluates operands from left to right with well-defined order. For a + b * c, precedence decides grouping, but within each subexpression, operand evaluation is left-to-right. Short-circuit operators (&&, ||, ?:) may skip right operand evaluation.
Numeric promotion and conversion rules:
- Widening primitive conversion (no loss): byte→short→int→long→float→double; char→int→long→float→double.
- Narrowing primitive conversion (possible loss; requires cast): e.g., int→short, double→float, long→int, etc.
- Unary numeric promotion: for unary +, −, ~, byte/short/char are promoted to int; long stays long; float/double unchanged.
- Binary numeric promotion: for +, −, *, /, %, and for integral &, |, ^ (not boolean). Shifts do not use binary numeric promotion: the left operand is promoted to int or long, and the right operand’s distance is masked. Rule: if either operand is double→double; else if either is float→float; else if either is long→long; else both to int.
- Compound assignment e.g., s += i: computes (type) (s + i) with an implicit cast to the left-hand type; may silently truncate.
Overflow and underflow:
- Integer arithmetic overflows wrap around modulo 2^n (n = bit width), two’s complement; no exception is thrown.
- Floating-point operations follow IEEE-754 and can yield +Infinity, −Infinity, NaN, and signed zero (−0.0).
Casting:
- Explicit cast syntax: (targetType) expression. Narrowing casts can truncate or change sign. Casting a floating-point value to an integral type truncates toward zero; if the value is NaN the result is 0; if the (truncated) value is outside the target type’s range, the result is clamped to that type’s nearest bound (e.g., (int)3e9 -> 2147483647, (int)-3e9 -> -2147483648). For char, the result is clamped to the range 0..65535.
- Safe cast with instanceof: if (obj instanceof String s) { ... } pattern matching (from newer Java) binds s with correct type.
Characters and Unicode:
- char is a 16-bit code unit. Some Unicode code points (U+10000 and above) require surrogate pairs. String.length() counts code units, not code points. Use codePointCount for code points.
Bitwise operations as sets/flags:
- Use bit masks to pack multiple boolean flags into one int/long. & tests, | sets, ^ toggles, ~ flips all bits.
Diagram to draw (if asked: “Operator precedence and evaluation diagram”):
- Draw a vertical list of precedence levels (14 lines as above), highest at top, each line labeled with operators. On the right, draw arrows labeled “L→R” for left-associative levels and “R→L” for assignment and ternary. At bottom, add a note: “Operands are evaluated left-to-right; short-circuit applies for &&, ||, ?:”.
Formulas
type name = literal;— Declare and initialize a variable; type is a primitive or reference; literal is a fixed value.long x = 10L; float y = 3.5F; double z = 1e-3;— Integer and floating literals with suffixes.char c = '\u03C0'; String s = "Hello"; boolean b = true;— Character, string, boolean literals.x = y; x += y; x <<= 2;— Simple and compound assignments; compound implies cast after promotion.a + b, a - b, a * b, a / b, a % b— Arithmetic operators.a & b, a | b, a ^ b, ~a— Bitwise operators for integers; logical for booleans (non-short-circuit for &, |).a << n, a >> n, a >>> n— Shift operators; int masked by 0x1F, long by 0x3F.a < b, a <= b, a > b, a >= b, a == b, a != b— Relational and equality.a && b, a || b, !a— Short-circuit logical operators on booleans.T result = condition ? expr1 : expr2;— Ternary conditional operator.(TargetType) expr— Explicit cast.obj instanceof Type— Runtime type test; true if obj is an instance of Type (and not null).String t = s1 + s2 + x;— String concatenation; left-to-right evaluation and conversion via String.valueOf.
Worked examples
Example 1: Numeric promotion, casting, overflow, and division behavior Program:
import java.util.*;
public class NumericDemo {
public static void main(String[] args) {
byte b = 100; // 8-bit
byte b2 = 30; // 8-bit
int sum = b + b2; // binary numeric promotion to int
System.out.println("sum (int) = " + sum);
byte overflow = (byte)(b * b2); // 100*30 = 3000 -> truncate to byte
System.out.println("overflow (byte) = " + overflow);
int a = -7;
int d1 = a / 3; // truncates toward zero: -2
int r1 = a % 3; // remainder has sign of dividend: -1
System.out.println("-7 / 3 = " + d1 + ", -7 % 3 = " + r1);
double posInf = 1.0 / 0.0; // +Infinity
double negInf = -1.0 / 0.0; // -Infinity
double nan = 0.0 / 0.0; // NaN
System.out.println("+Inf? " + Double.isInfinite(posInf) + ", -Inf? " + Double.isInfinite(negInf) + ", NaN? " + Double.isNaN(nan));
char c = '\u0041'; // 'A'
int ci = c + 1; // char promotes to int
System.out.println("'A' + 1 = " + ci + " (code unit)");
// Compound assignment implicit cast
short s = 30000; // near short max 32767
s += 5000; // implicit cast after int promotion -> overflow in short
System.out.println("s after s += 5000: " + s);
}
}
Exact output:
sum (int) = 130
overflow (byte) = -72
-7 / 3 = -2, -7 % 3 = -1
+Inf? true, -Inf? true, NaN? true
'A' + 1 = 66 (code unit)
s after s += 5000: -30536
Notes:
- 100*30 = 3000; 3000 modulo 256 = 184; as byte signed: 184 − 256 = −72.
- For short overflow: 30000 + 5000 = 35000; modulo 65536 is 35000; interpreting as signed 16-bit: 35000 − 65536 = −30536.
Example 2: Bitwise masks and shift behavior Program:
import java.util.*;
public class BitwiseFlags {
// Define bit flags
static final int READ = 1 << 0; // 0001
static final int WRITE = 1 << 1; // 0010
static final int EXEC = 1 << 2; // 0100
public static void main(String[] args) {
int perms = 0;
perms |= READ; // set READ
perms |= EXEC; // set EXEC
System.out.println("perms = " + toBits(perms));
boolean canWrite = (perms & WRITE) != 0; // test WRITE
System.out.println("WRITE? " + canWrite);
// Shift examples
int x = -8; // 0xFFFFFFF8
System.out.println("x = " + toBits(x));
System.out.println("x >> 2 = " + toBits(x >> 2)); // sign-propagating
System.out.println("x >>> 2 = " + toBits(x >>> 2)); // zero-fill
// Shift distance masking
int y = 1;
int dist = 33; // for int, mask to 33 & 0x1F = 1
System.out.println("1 << 33 = " + (y << dist)); // same as 1 << 1 -> 2
}
static String toBits(int v) {
String s = String.format("%32s", Integer.toBinaryString(v)).replace(' ', '0');
return s.substring(0, 4) + " " + s.substring(4, 8) + " " + s.substring(8, 12) + " " + s.substring(12, 16) + " " +
s.substring(16, 20) + " " + s.substring(20, 24) + " " + s.substring(24, 28) + " " + s.substring(28, 32);
}
}
Exact output:
perms = 0000 0000 0000 0000 0000 0000 0000 0101
WRITE? false
x = 1111 1111 1111 1111 1111 1111 1111 1000
x >> 2 = 1111 1111 1111 1111 1111 1111 1111 1110
x >>> 2 = 0011 1111 1111 1111 1111 1111 1111 1110
1 << 33 = 2
Notes:
- For a negative int, >> keeps leading ones; >>> inserts zeros.
- Shift distance for int is masked by 0x1F (i.e., modulo 32).
Example 3: Precedence, short-circuit, and String concatenation order Program:
import java.util.*;
public class PrecedenceShortCircuit {
static int side(String label) {
System.out.print(label);
return 1;
}
public static void main(String[] args) {
// Precedence: * before +, left-to-right evaluation
int a = 2 + 3 * 4; // 14
System.out.println("a=" + a);
// Short-circuit prevents division by zero
int x = 0;
boolean safe = (x != 0) && ((10 / x) > 1);
System.out.println("safe=" + safe);
// String concatenation left-to-right
String s = "X" + 1 + 2; // "X12"
String t = 1 + 2 + "X"; // (1+2)=3 then "3X"
System.out.println("s=" + s + ", t=" + t);
// Demonstrate left-to-right evaluation order
int val = side("L") + side("R");
System.out.println();
System.out.println("val=" + val);
}
}
Exact output:
a=14
safe=false
s=X12, t=3X
LR
val=2
Notes:
- 2 + 3 * 4 groups as 2 + (3 * 4) = 14; operands evaluated left-to-right.
- (x != 0) is false, so (10 / x) is not evaluated due to && short-circuit.
- String concatenation is left-to-right: "X" + 1 → "X1"; then + 2 → "X12"; but 1 + 2 + "X" computes 3 first.
Common mistakes
- Forgetting that byte, short, and char promote to int in expressions; writing byte b = b1 + b2; without a cast.
- Misusing == with Strings and other objects. == tests reference identity, not content. Use equals for content comparison.
- Expecting integer overflow to throw an exception. Java silently wraps modulo 2^n.
- Confusing >> and >>>; using >>> for negative numbers expecting sign-propagation.
- Relying on unspecified sizes for boolean, or trying to cast boolean to int directly (not allowed).
- Writing chained comparisons like 0 < x < 10 (invalid). Must write 0 < x && x < 10.
- Thinking && and || evaluate both operands always. They short-circuit and may skip side effects.
- Misunderstanding String concatenation: 1 + 2 + "X" yields "3X", not "12X".
- Using octal by mistake with a leading 0 in integer literals; be explicit with 0x, 0b, or decimal.
For your exam
- Short notes: difference between == and equals; char as UTF-16 code unit; IEEE-754 special values (NaN, ±Infinity, −0.0); overflow behavior; shift operators and masking of shift distance.
- Programs: demonstrate promotion and casting; bit masks; short-circuit safety; String concatenation order. Include import, class, main, correct literals/suffixes, and exact outputs.
- Diagrams: operator precedence ladder with associativity arrows; data type hierarchy of widening conversions. Label each level clearly.
- Numericals/theory: compute the result of an expression step-by-step with promotion rules and precedence; predict binary results of bitwise operations and shifts; determine output of small code snippets. Show grouping, promotion, and intermediate values.
- Full marks tips: define every technical term before use; state assumptions (e.g., int is 32-bit two’s complement); show the exact promotion path; for bitwise answers, show binary with grouping; explain short-circuit reasoning.
Quick check
- What are the results of -9 / 4 and -9 % 4 in Java?
- Which operator has higher precedence: << or + ? State associativity of =.
- For int n = -16, what is n >>> 2 in binary (32 bits, grouped as 4-4-...)?
Answers: 1) -2 and -1. 2) << has higher precedence than +; = is right-associative. 3) 0011 1111 1111 1111 1111 1111 1111 1100.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?