☕ Java
Assignment Operators
Assignment operators store values into variables. Java has one basic assignment operator and eleven compound assignment operators that combine an operation with assignment. They're concise, but have specific type behavior — especially the implicit cast in compound assignments — that every Java developer needs to understand.
The Basic Assignment Operator
= stores the value of the right-hand side into the variable on the left-hand side. It evaluates right-to-left, which allows chained assignment.
Java
// Basic assignment:
int x = 10;
double pi = 3.14159;
String name = "Alice";
boolean flag = true;
// Assignment is an expression — it returns the assigned value:
int a, b, c;
a = b = c = 100; // right-to-left: c=100, b=100, a=100
System.out.println(a + " " + b + " " + c); // 100 100 100
// Assignment in a condition (intentional, though uncommon):
int value;
while ((value = readNextValue()) != -1) {
process(value);
}
// Common mistake — = instead of == in conditions:
if (x = 10) { } // COMPILE ERROR in Java — unlike C, Java requires boolean
if (x == 10) { } // correct comparison
// Reference assignment — both variables point to same object:
String s1 = "Hello";
String s2 = s1; // s2 points to the same String object
// Strings are immutable so this is safe — but for mutable objects,
// changes through s2 would be visible through s1Compound Assignment Operators
Compound assignment operators combine an arithmetic, bitwise, or shift operation with assignment. x += 5 means x = x + 5. All eleven are listed here:
Java
int x = 20;
x += 5; // x = x + 5 → 25
x -= 3; // x = x - 3 → 22
x *= 2; // x = x * 2 → 44
x /= 4; // x = x / 4 → 11
x %= 3; // x = x % 3 → 2
x = 0b1010_1010; // reset to 170 for bitwise demos
x &= 0b1111_0000; // x = x & mask → 0b1010_0000 = 160
x |= 0b0000_1111; // x = x | mask → 0b1010_1111 = 175
x ^= 0b0000_1111; // x = x ^ mask → 0b1010_0000 = 160
x = 8;
x <<= 2; // x = x << 2 → 32
x >>= 1; // x = x >> 1 → 16
x >>>= 1; // x = x >>> 1 → 8The Hidden Cast in Compound Assignment
The most important and least-known behavior of compound assignment operators: they include an implicit narrowing cast. This is different from the equivalent expanded expression, which would require an explicit cast.
Java
// byte += int — works because of implicit cast:
byte b = 10;
b += 5; // equivalent to: b = (byte)(b + 5) — implicit cast included
System.out.println(b); // 15
// Without compound assignment — explicit cast required:
byte b2 = 10;
// b2 = b2 + 5; // COMPILE ERROR — b2+5 is int, can't assign to byte
b2 = (byte)(b2 + 5); // correct without compound operator
// short behaves the same way:
short s = 1000;
s += 500; // works — implicit cast to short
// s = s + 500; // COMPILE ERROR — requires explicit (short) cast
// The implicit cast can silently overflow:
byte b3 = 100;
b3 += 100; // b3 = (byte)(100 + 100) = (byte)(200) = -56 — wrapped!
System.out.println(b3); // -56
// int *= long — result implicitly cast back to int:
int i = 1000;
long multiplier = 3L;
i *= multiplier; // i = (int)(1000 * 3L) — implicit cast from long to int
System.out.println(i); // 3000 — fine here, but could overflow for large values
// float += double — implicit cast to float:
float f = 1.5f;
f += 0.1; // 0.1 is double, result cast back to float
System.out.println(f); // 1.6 (approximately)Compound Assignment with Strings
The += operator is overloaded for String concatenation, making it the most common compound assignment in Java outside of numeric code.
Java
// String += appends:
String message = "Hello";
message += ", World"; // "Hello, World"
message += "!"; // "Hello, World!"
// In a loop — creates many intermediate String objects:
String result = "";
for (int i = 0; i < 5; i++) {
result += i; // new String created on each iteration
}
System.out.println(result); // "01234"
// For performance in loops, use StringBuilder instead:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i);
}
String result2 = sb.toString(); // "01234"
// += with any type — converts to String via toString():
String s = "Count: ";
s += 42; // "Count: 42"
s += true; // "Count: 42true"
s += 3.14; // "Count: 42true3.14"
s += null; // "Count: 42true3.14null" — null becomes "null"Assignment in Loops and Conditions
Assignment operators appear in specific patterns in loops and conditions that are worth understanding:
Java
// Accumulator pattern — most common use of +=:
int sum = 0;
int[] numbers = {1, 2, 3, 4, 5};
for (int n : numbers) {
sum += n; // accumulate total
}
System.out.println(sum); // 15
// Counter:
int count = 0;
for (String line : lines) {
if (line.startsWith("ERROR")) {
count++; // equivalent to count += 1
}
}
// Running product:
long factorial = 1;
for (int i = 1; i <= 10; i++) {
factorial *= i;
}
// Building a result with |= (flags):
int permissions = 0;
if (canRead) permissions |= READ;
if (canWrite) permissions |= WRITE;
if (canExecute) permissions |= EXECUTE;
// Bit masking with &=:
int flags = 0xFF;
flags &= ~WRITE; // remove write permission
// Assignment in while condition (reading streams):
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
process(buffer, bytesRead);
}Related Topics in Java Basics
Variables in Java
A variable is just a named box in memory that holds a value. Java is strict about what goes in each box — you tell it the type upfront. Once you get this, the rest of Java clicks into place.
Data Types in Java
Java needs to know exactly what kind of data it's dealing with before it can store or process it. Integers, decimals, characters, true/false — each has its own type. Knowing which to use (and why) makes your programs efficient and bug-free.
Primitive Data Types
Java has eight primitive data types — the most basic building blocks for storing data. Unlike objects, primitives are stored directly in memory, making them fast and efficient. Understanding each type, its size, range, and when to use it is fundamental to writing correct Java programs.
Non-Primitive Data Types
Non-primitive data types — also called reference types — are everything beyond Java's eight primitives. Strings, arrays, classes, interfaces, enums, and records all fall into this category. They're more powerful than primitives, but they work differently in memory, comparison, and nullability. Understanding the distinction is essential for writing correct Java.