Useful Java Methods for General
Programming
1. String Class
The String class represents character strings. All string literals in Java programs, such as
"abc", are implemented as instances of this class. Strings are immutable.
int length()
Description: Returns the length of the string.
Complexity: O(1)
Example: String s = "hello";
int len = [Link](); // 5
----------------------------------------
char charAt(int index)
Description: Returns the character at the specified index. Throws
IndexOutOfBoundsException if index is out of range.
Complexity: O(1)
Example: char c = [Link](1); // 'e'
----------------------------------------
String substring(int beginIndex, int endIndex)
Description: Returns a new string that is a substring of this string. The substring begins at
the specified beginIndex and extends to the character at index endIndex - 1.
Complexity: O(n)
Example: String sub = [Link](0, 2); // "he"
----------------------------------------
boolean equals(Object another)
Description: Compares this string to the specified object. The result is true if and only if the
argument is not null and is a String object that represents the same sequence of characters.
Complexity: O(n)
Example: boolean b = [Link]("hello"); // true
----------------------------------------
boolean equalsIgnoreCase(String another)
Description: Compares this String to another String, ignoring case considerations.
Complexity: O(n)
Example: boolean b = [Link]("HELLO"); // true
----------------------------------------
int indexOf(String str)
Description: Returns the index within this string of the first occurrence of the specified
substring. Returns -1 if not found.
Complexity: O(n * m)
Example: int idx = [Link]("l"); // 2
----------------------------------------
boolean contains(CharSequence s)
Description: Returns true if and only if this string contains the specified sequence of char
values.
Complexity: O(n * m)
Example: boolean exists = [Link]("ell"); // true
----------------------------------------
String trim()
Description: Returns a string whose value is this string, with any leading and trailing
whitespace removed.
Complexity: O(n)
Example: String t = " hi ".trim(); // "hi"
----------------------------------------
String replace(CharSequence target, CharSequence replacement)
Description: Replaces each substring of this string that matches the literal target sequence
with the specified literal replacement sequence.
Complexity: O(n)
Example: String r = [Link]("l", "p"); // "heppo"
----------------------------------------
String replaceAll(String regex, String replacement)
Description: Replaces each substring of this string that matches the given regular
expression with the given replacement.
Complexity: O(n)
Example: String s = "a1b2c3";\nString r = [Link]("\\d", "#"); //
"a#b#c#"
----------------------------------------
String[] split(String regex)
Description: Splits this string around matches of the given regular expression.
Complexity: O(n)
Example: String[] parts = "a,b,c".split(","); // ["a", "b", "c"]
----------------------------------------
String toLowerCase() / toUpperCase()
Description: Converts all of the characters in this String to lower/upper case using the rules
of the default locale.
Complexity: O(n)
Example: String lower = "JAVA".toLowerCase(); // "java"
----------------------------------------
char[] toCharArray()
Description: Converts this string to a new character array.
Complexity: O(n)
Example: char[] chars = [Link](); // ['h', 'e', 'l', 'l', 'o']
----------------------------------------
static String join(CharSequence delimiter, CharSequence... elements)
Description: Returns a new String composed of copies of the CharSequence elements joined
together with a copy of the specified delimiter.
Complexity: O(n)
Example: String joined = [Link]("-", "a", "b", "c"); // "a-b-c"
----------------------------------------
static String format(String format, Object... args)
Description: Returns a formatted string using the specified format string and arguments.
Complexity: O(n)
Example: String fmt = [Link]("Age: %d", 25); // "Age: 25"
----------------------------------------
1.1. Regular Expressions Guide
Regular expressions are patterns used to match character combinations in strings. In Java,
backslashes must be escaped (e.g., use \\d instead of \d).
Character Classes
Construct Description
[abc] Matches 'a', 'b', or 'c'
[^abc] Negation: matches any character except 'a',
'b', or 'c'
[a-z] Range: matches any lowercase letter from
'a' to 'z'
[a-zA-Z] Matches any letter (lowercase or
uppercase)
[0-9] Matches any digit
Predefined Character Classes
Construct Description
\\d A digit: [0-9]
\\D A non-digit: [^0-9]
\\s A whitespace character: [ \t\n\x0B\f\r]
\\S A non-whitespace character: [^\\s]
\\w A word character: [a-zA-Z_0-9]
\\W A non-word character: [^\\w]
Quantifiers
Construct Description
X? X occurs once or not at all
X* X occurs zero or more times
X+ X occurs one or more times
X{n} X occurs exactly n times
X{n,} X occurs at least n times
X{n,m} X occurs at least n but not more than m
times
Boundary Matchers
Construct Description
^ Beginning of a line
$ End of a line
\\b Word boundary
\\B Non-word boundary
Logical Operators
Construct Description
XY X followed by Y
X|Y Either X or Y
(X) X, as a capturing group
Regex Examples
Email Validation: [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}
Phone Number (10 digits): \\d{10}
Date (yyyy-mm-dd): \\d{4}-\\d{2}-\\d{2}
Remove non-alphanumeric: [Link]("[^a-zA-Z0-9]", "")
----------------------------------------
2. Integer Class
The Integer class wraps a value of the primitive type int in an object. It also provides several
methods for converting an int to a String and a String to an int.
static final int MIN_VALUE
Description: A constant holding the minimum value an int can have, -2^31.
Complexity: N/A
Example: int min = Integer.MIN_VALUE; // -2147483648
----------------------------------------
static final int MAX_VALUE
Description: A constant holding the maximum value an int can have, 2^31-1.
Complexity: N/A
Example: int max = Integer.MAX_VALUE; // 2147483647
----------------------------------------
static int parseInt(String s)
Description: Parses the string argument as a signed decimal integer. Throws
NumberFormatException if not parsable.
Complexity: O(n)
Example: int val = [Link]("123"); // 123
----------------------------------------
static String toString(int i)
Description: Returns a String object representing the specified integer.
Complexity: O(n)
Example: String str = [Link](123); // "123"
----------------------------------------
static Integer valueOf(int i)
Description: Returns an Integer instance representing the specified int value. This method
should generally be used in preference to the constructor Integer(int), as this method is
likely to yield significantly better space and time performance by caching frequently
requested values.
Complexity: O(1)
Example: Integer i = [Link](10);
----------------------------------------
static int compare(int x, int y)
Description: Compares two int values numerically. Returns 0 if x==y, value less than 0 if x <
y, and value greater than 0 if x > y.
Complexity: O(1)
Example: int cmp = [Link](5, 10); // -1
----------------------------------------
static int max(int a, int b)
Description: Returns the greater of two int values.
Complexity: O(1)
Example: int m = [Link](5, 10); // 10
----------------------------------------
static int min(int a, int b)
Description: Returns the smaller of two int values.
Complexity: O(1)
Example: int m = [Link](5, 10); // 5
----------------------------------------
static int bitCount(int i)
Description: Returns the number of one-bits in the two's complement binary representation
of the specified int value.
Complexity: O(1)
Example: int bits = [Link](3); // 2 (binary 11)
----------------------------------------
3. Character Class
The Character class wraps a value of the primitive type char in an object.
static boolean isLetter(char ch)
Description: Determines if the specified character is a letter.
Complexity: O(1)
Example: boolean b = [Link]('a'); // true
----------------------------------------
static boolean isDigit(char ch)
Description: Determines if the specified character is a digit.
Complexity: O(1)
Example: boolean b = [Link]('1'); // true
----------------------------------------
static boolean isWhitespace(char ch)
Description: Determines if the specified character is white space according to Java.
Complexity: O(1)
Example: boolean b = [Link](' '); // true
----------------------------------------
static char toUpperCase(char ch)
Description: Converts the character argument to uppercase.
Complexity: O(1)
Example: char c = [Link]('a'); // 'A'
----------------------------------------
static char toLowerCase(char ch)
Description: Converts the character argument to lowercase.
Complexity: O(1)
Example: char c = [Link]('A'); // 'a'
----------------------------------------
static String toString(char c)
Description: Returns a String object representing the specified char.
Complexity: O(1)
Example: String s = [Link]('x'); // "x"
----------------------------------------
static int getNumericValue(char ch)
Description: Returns the int value that the specified Unicode character represents.
Complexity: O(1)
Example: int val = [Link]('5'); // 5
----------------------------------------
4. Arrays Class
This class contains various methods for manipulating arrays (such as sorting and
searching).
static void sort(primitive[] a)
Description: Sorts the specified array into ascending numerical order. Uses Dual-Pivot
Quicksort.
Complexity: O(n log n)
Example: int[] arr = {3, 1, 2};
[Link](arr); // [1, 2, 3]
----------------------------------------
static int binarySearch(primitive[] a, primitive key)
Description: Searches the specified array for the specified value using the binary search
algorithm. The array must be sorted prior to making this call. Returns index of the search
key, if it is contained in the array; otherwise, (-(insertion point) - 1).
Complexity: O(log n)
Example: int idx = [Link](arr, 2);
----------------------------------------
static boolean equals(primitive[] a, primitive[] a2)
Description: Returns true if the two specified arrays are equal to one another.
Complexity: O(n)
Example: boolean eq = [Link](arr1, arr2);
----------------------------------------
static void fill(primitive[] a, primitive val)
Description: Assigns the specified value to each element of the specified array.
Complexity: O(n)
Example: [Link](arr, 0); // [0, 0, 0]
----------------------------------------
static String toString(primitive[] a)
Description: Returns a string representation of the contents of the specified array.
Complexity: O(n)
Example: [Link]([Link](arr)); // "[1, 2, 3]"
----------------------------------------
static <T> List<T> asList(T... a)
Description: Returns a fixed-size list backed by the specified array.
Complexity: O(1)
Example: List<String> list = [Link]("a", "b");
----------------------------------------
static primitive[] copyOf(primitive[] original, int newLength)
Description: Copies the specified array, truncating or padding with zeros (if necessary) so
the copy has the specified length.
Complexity: O(n)
Example: int[] copy = [Link](arr, 5);
----------------------------------------
5. Math Class (General Utilities)
The Math class contains methods for performing basic numeric operations.
static int abs(int a)
Description: Returns the absolute value of an int value.
Complexity: O(1)
Example: int val = [Link](-10); // 10
----------------------------------------
static double pow(double a, double b)
Description: Returns the value of the first argument raised to the power of the second
argument.
Complexity: O(1) usually
Example: double val = [Link](2, 3); // 8.0
----------------------------------------
static double sqrt(double a)
Description: Returns the correctly rounded positive square root of a double value.
Complexity: O(1) usually
Example: double val = [Link](16); // 4.0
----------------------------------------
static int max(int a, int b)
Description: Returns the greater of two int values.
Complexity: O(1)
Example: int m = [Link](5, 10); // 10
----------------------------------------
static int min(int a, int b)
Description: Returns the smaller of two int values.
Complexity: O(1)
Example: int m = [Link](5, 10); // 5
----------------------------------------
6. Scanner Class
A simple text scanner which can parse primitive types and strings using regular
expressions.
String next()
Description: Finds and returns the next complete token from this scanner.
Complexity: N/A
Example: Scanner sc = new Scanner([Link]);
String s = [Link]();
----------------------------------------
int nextInt()
Description: Scans the next token of the input as an int.
Complexity: N/A
Example: int i = [Link]();
----------------------------------------
String nextLine()
Description: Advances this scanner past the current line and returns the input that was
skipped.
Complexity: N/A
Example: String line = [Link]();
----------------------------------------
boolean hasNext()
Description: Returns true if this scanner has another token in its input.
Complexity: N/A
Example: while([Link]()) { ... }
----------------------------------------
7. Random Class
An instance of this class is used to generate a stream of pseudorandom numbers.
int nextInt(int bound)
Description: Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive).
Complexity: O(1)
Example: Random rand = new Random();
int r = [Link](10); // 0-9
----------------------------------------
double nextDouble()
Description: Returns the next pseudorandom, uniformly distributed double value between
0.0 and 1.0.
Complexity: O(1)
Example: double d = [Link]();
----------------------------------------