Understanding the core syntax and behaviors of Java is essential for effective development. This guide covers primtiive type nuances, operator precedence, binary representations, and control flow logic.
Primitive Type Operations
In Java, arithmetic operations on types smaller than int (such as byte or short) result in implicit type promotion. For example, when performing compound assignments or increments, the result is automatically cast back to the original type:
byte counter = 10;
counter += 2; // Equivalent to: counter = (byte)(counter + 2);
counter++; // Equivalent to: counter = (byte)(counter + 1);
Operator Precedence
Java evaluates expressions based on a strict hierarchy. From highest to lowest priority:
- Parentheses
() - Unary operators:
++,--,! - Multiplicative:
*,/,% - Additive:
+,- - Bitwise shifts:
<<,>>,>>> - Relational:
<,>,<=,>=,instanceof - Logical AND/OR:
&,|,^ - Short-circuit operators:
&&,|| - Ternary and Assignment operators
Binary Arithmetic and Bitwise Shifts
Computers process numbers using two's complement. For positive numbers, the sign-magnitude, one's compliment, and two's complement representations are identical. For negative numbers, the two's compliment is derived by inverting the bits of the absolute value and adding one.
<<(Arithmetic Left Shift): Multiplies by 2; shifts bits left and fills the right with 0.>>(Arithmetic Right Shift): Divides by 2; preserves the sign bit.>>>(Logical Right Shift): Fills the leftmost bits with 0 regardless of the sign.
Control Flow Examples
Leap Year Logic
A year is a leap year if it is divisible by 400, or divisible by 4 but not by 100.
int year = 2024;
boolean isLeap = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
if (isLeap) {
System.out.println(year + " is a leap year.");
}
Switch Statements
The switch statement supports byte, short, int, char, enum, and String. Note that without a break statement, execution "falls through" to subsequent cases.
int status = 1; // Example status
switch (status) {
case 0:
System.out.println("Fail");
break;
case 1:
System.out.println("Pass");
break;
default:
System.out.println("Invalid input");
}
Calculating Narcissistic Numbers (Armstrong Numbers)
A Narcissistic number is a number that is the sum of its own digits each raised to the power of the number of digits. The following implementation checks for 3-digit Narcissistic numbers using Math.pow.
int num = 153;
int digit1 = num % 10;
int digit2 = (num / 10) % 10;
int digit3 = (num / 100) % 10;
double sum = Math.pow(digit1, 3) + Math.pow(digit2, 3) + Math.pow(digit3, 3);
if (num == (int)sum) {
System.out.println(num + " is a Narcissistic number.");
}