Java Cheat Sheet Arrays 2 D Strings
Java Cheat Sheet Arrays 2 D Strings
// Initialization:
int[] numbers = new int[5];
// OR
int[] numbers = {1, 2, 3, 4, 5};
Accessing Elements:
// Accessing an element:
nt element = numbers[0]; // Accesses the first element
// Modifying an element:
numbers[0] = 10; // Modifies the first element
Length:
// Length of an array:
int length = numbers.length; // Gives the length of the array
Sorting:
// Using Arrays.sort() method:
Arrays.sort(numbers); // Sorts the array in ascending order
Multidimensional Arrays:
Page 1 of 3
// Accessing elements:
int element = matrix[0][0]; // Accesses the element at the first row and first column
Array Methods:
// toString() method to print array contents:
System.out.println(Arrays.toString(numbers)); // Prints the array contents
Strings in Java
Declaration and Initialization:
// Declaration:
String str;
// Initialization:
String str = "Hello, World!";
Length:
int length = str.length(); // Gives the number of characters in the string
Accessing Characters:
// Accessing a character at a specific index:
char firstChar = str.charAt(0); // Retrieves the character at index 0
Concatenation:
String newString = str + " Welcome!"; // Concatenates two strings
Substrings:
// Extracting a substring:
String substring = str.substring(7); // Extracts substring starting from index 7 to the end
String substring2 = str.substring(7, 12); // Extracts substring from index 7 to 11
Page 2 of 3
Comparison:
boolean isEqual = str.equals("Hello"); // Checks if two strings are equal
boolean isEqualIgnoreCase = str.equalsIgnoreCase("hello"); // Checks if two strings are equal ignoring
case
Conversion:
// Converting other types to string:
int number = 123;
String strNumber = String.valueOf(number); // Converts int to string
Splitting:
String[] parts = str.split(","); // Splits the string by comma into an array
Searching:
int index = str.indexOf("World"); // Finds the index of the substring "World" in the string
Modifying:
String modifiedString = str.replace("World", "Universe"); // Replaces "World" with "Universe"
Page 3 of 3