Strings are immutable, that means we always receive a copy as the output of the function.
String original = "Hello World";
String sub = original.substring(0, 5); // Creates NEW string "Hello"
System.out.println(original); // "Hello World" (unchanged)
System.out.println(sub); // "Hello"String methods that return String
substring(i1, i2)orsubstring(i1)which returns the substring fromi1toi2(or end ofStringis omitted).toLowerCasetoUpperCasestripLeadingundstripTailingremove spaces at the beginning (resp. end) of theString.
String methods that return int
length()returns the number of characters in the string- `indexOf()
String methods that return boolean
String comparisons
Do not compare strings (or any non-primitive types) with
==in Java as this compares their references and not the actual string value. Use.equals()for this.
Arrays
We can initialise arrays directly with the following syntax: int[] test = {1, 2, 3, ..., 4};.
Methods
You can use helper methods from java.util.Arrays:
- To compare arrays, also use
Arrays.equals(1, 2). - Create a copy
Arrays.copyOf(arr, l) - Sort using
Arrays.sort(arr) - To String using
Arrays.toString(arr)orArrays.deepToString(arr).