Data Types in Java
Java categorizes data types into primitive and reference types. Primitive types include eight basic categories: byte, short, int, long, float, double, char, and boolean. Reference types encompass classes like String.
Java ensures consistent memory allocation across platforms, with int always occupying four bytes. Unlike C, Java consolidates long and long long into a single long type, which uses eight bytes.
The IDE offers extensive error detection, though some subtle issues may persist. To distinguish long literals from int, append an uppercase L to the value:
long a = 10L;
Integer operations that result in decimal values require explicit decimal notation, such as 10.0. Floating-point numbers follow IEEE 754 standards, where float literals must end with f to differentiate them from default double values.
For smaller types like byte and short, direct assignment works when within range. However, larger type assignments require casting:
byte b1 = 10;
byte b2 = 20;
int sum = b1 + b2; // Avoids implicit promotion to int
Characters in Java use Unicode, occupying two bytes, allowing support for Chinese characters. Booleans cannot be converted to integers or vice versa.
String concatenation follows left-to-right evaluation, with the + operator acting as a concatenator upon encountering strings:
String result = "Hello" + 5 + "World"; // Results in "Hello5World"
Modulo operations with floating-point numbers produce decimal results:
System.out.println(11.5 % 2); // Outputs 1.5
Divsiion by zero throws an arithmetic exception. Type conversions should be explicit between comaptible types.
Bitwise Operations
Right shift fills with sign bit; unsigned right shift fills with zeros. Java lacks unsigned left shift.
Conditional Operator
The ternary operator evaluates expressions:
boolean flag = true == true ? false ? true : false : true;
Variable Arguments
Methods can accept variable arguments using int... syntax:
public static int add(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
Input Handling
Use Scanner for input:
Scanner input = new Scanner(System.in);
int value = input.nextInt();
next() stops at whitespace, while nextLine() reads entire lines. When mixing input methods, consume leftover newline characters:
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline
String name = scanner.nextLine();
Control Flow
Loop termination in Java uses Ctrl+D instead of EOF.
Random Number Generation
Generate random numbers using the Random class:
Random random = new Random();
int guess = random.nextInt(100); // [0, 100)
Arrays
Arrays are objects with fixed sizes:
int[] array = {1, 2, 3, 4};
int[] another = new int[10];
Access elements via indices, and use .length to get size:
int size = array.length;
Assignments happen through index access. Null references do not point to valid objects:
int[] arr = null;
// arr.length would throw NullPointerException
Boolean arrays default to false:
boolean[] flags = new boolean[5]; // All elements false
Enhanced for loops simplify iteration:
for (int element : array) {
System.out.print(element + " ");
}
Array parameters pass references, modifying contents affects original:
public static void modify(int[] arr) {
arr[0] = 99;
}
Array Utilities
Utilize Arrays class for common operations:
int[] arr = {1, 2, 3, 4, 5};
String str = Arrays.toString(arr);
Binary search requires sorted arrays:
int pos = Arrays.binarySearch(arr, 10); // Returns negative index if not found
Fill arrays with specific values:
Arrays.fill(arr, 9); // Fill all elements
Arrays.fill(arr, 0, 3, 9); // Fill range
Copy arrays using built-in methods:
int[] copy = Arrays.copyOf(arr, arr.length);
int[] range = Arrays.copyOfRange(arr, 0, 3);
Multi-dimensional Arrays
Two-dimensional arrays in Java can be irregular:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
int[][] irregular = new int[2][];
irregular[0] = new int[]{1, 3, 5};
irregular[1] = new int[]{1, 2, 3, 4, 5};
Iterate over rows and columns:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Convert to string using deepToString():
System.out.println(Arrays.deepToString(matrix));
Enhanced for loops also work with nested structures:
for (int[] row : matrix) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
Null checks are essential before accessing multi-dimensional arrays.