0% found this document useful (0 votes)
4 views4 pages

Java Complete Functions CheatSheet

This document is a comprehensive cheat sheet for Java String, Array, ArrayList, and StringBuilder functions, providing examples for each method. It covers key functions such as length(), charAt(), substring(), and various Array methods like sort() and copyOf(). Additionally, it includes ArrayList and StringBuilder methods, making it a useful reference for Java programming.

Uploaded by

abcxyz571e
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

Java Complete Functions CheatSheet

This document is a comprehensive cheat sheet for Java String, Array, ArrayList, and StringBuilder functions, providing examples for each method. It covers key functions such as length(), charAt(), substring(), and various Array methods like sort() and copyOf(). Additionally, it includes ArrayList and StringBuilder methods, making it a useful reference for Java programming.

Uploaded by

abcxyz571e
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Complete Java String, Array, ArrayList & StringBuilder Functions Cheat Sheet

Java String Functions with Examples:

1. length()
String s = "hello";
[Link]([Link]()); // 5

2. charAt(int index)
[Link]([Link](1)); // 'e'

3. substring(int start, int end)


[Link]([Link](1, 4)); // "ell"

4. equals(String s)
[Link]([Link]("hello")); // true

5. equalsIgnoreCase(String s)
[Link]([Link]("HELLO")); // true

6. contains(CharSequence s)
[Link]([Link]("ll")); // true

7. startsWith(String prefix) / endsWith(String suffix)


[Link]([Link]("he")); // true
[Link]([Link]("lo")); // true

8. toLowerCase() / toUpperCase()
[Link]([Link]()); // "HELLO"

9. trim()
String t = " hi ";
[Link]([Link]()); // "hi"

10. replace(char oldChar, char newChar)


[Link]([Link]('l', 'p')); // "heppo"

11. replaceAll(String regex, String replacement)


String s2 = "a1b2c3";
[Link]([Link]("\d", "")); // "abc"

12. split(String regex)


String[] parts = [Link]("e"); // ["h", "llo"]

13. indexOf(char c) / lastIndexOf(char c)


[Link]([Link]('l')); // 2
[Link]([Link]('l')); // 3

14. isEmpty()
String empty = "";
Complete Java String, Array, ArrayList & StringBuilder Functions Cheat Sheet

[Link]([Link]()); // true

15. matches(String regex)


[Link]("abc123".matches("[a-z]+\d+")); // true

16. toCharArray()
char[] ch = [Link]();
// ['h', 'e', 'l', 'l', 'o']

17. compareTo(String s)
[Link]("abc".compareTo("abd")); // Negative (because 'c'<'d')

Java Arrays Utility Class Functions:

1. [Link](array)
int[] a = {3, 1, 2};
[Link](a); // [1, 2, 3]

2. [Link](array)
[Link]([Link](a)); // "[1, 2, 3]"

3. [Link](array, newLength)
int[] b = [Link](a, 5);
// [1, 2, 3, 0, 0]

4. [Link](array, start, end)


int[] c = [Link](a, 1, 3);
// [2, 3]

5. [Link](arr1, arr2)
[Link]([Link](a, b)); // false

6. [Link](array, value)
[Link](b, 7);
// [7, 7, 7, 7, 7]

7. [Link](array, key)
int index = [Link](a, 2);
// index = 1 (only works correctly on sorted arrays)

8. [Link](array)
[Link](a); // faster sort for large arrays

9. [Link](array).sum()
int sum = [Link](a).sum();
// sum = 6
Complete Java String, Array, ArrayList & StringBuilder Functions Cheat Sheet

Java ArrayList Class Methods:

1. add(E e)
List<Integer> list = new ArrayList<>();
[Link](10);

2. add(int index, E element)


[Link](0, 5); // insert 5 at index 0

3. get(int index)
[Link]([Link](0)); // 5

4. set(int index, E element)


[Link](0, 20);

5. remove(int index)
[Link](0);

6. remove(Object o)
[Link]([Link](20));

7. size()
[Link]([Link]());

8. contains(Object o)
[Link](20);

9. indexOf(Object o)
[Link](20);

10. isEmpty()
[Link]();

11. clear()
[Link]();

12. addAll(Collection<? extends E> c)


List<Integer> list2 = new ArrayList<>();
[Link](list);

13. retainAll(Collection<?> c)
[Link](list2); // keep only common elements

14. toArray()
Integer[] arr = [Link](new Integer[0]);

Java StringBuilder Class Methods:


Complete Java String, Array, ArrayList & StringBuilder Functions Cheat Sheet

1. append(String s)
StringBuilder sb = new StringBuilder();
[Link]("Hello");

2. insert(int offset, String s)


[Link](5, " World"); // "Hello World"

3. replace(int start, int end, String s)


[Link](6, 11, "Java"); // "Hello Java"

4. delete(int start, int end)


[Link](5, 10); // "Hello"

5. reverse()
[Link](); // "olleH"

6. toString()
String result = [Link]();

7. length()
int len = [Link]();

8. charAt(int index)
char ch = [Link](0);

Common questions

Powered by AI

The `toCharArray()` method in Java's String class converts the string into an array of characters. This can be particularly useful when detailed manipulation of individual characters is required, as arrays provide mutable elements that can be indexed and modified directly. For instance, a task that requires reversing a string without using additional libraries could first convert the string to a character array, reverse the elements using an algorithm (like two-pointer swap), and then recombine them into a string if needed. This method is also useful for processing each character separately for tasks such as encoding transformations and checksum calculations .

The `String.split(String regex)` method is particularly suitable for cases where a string needs to be divided into multiple substrings based on specific delimiters characterized by regular expressions. It is highly effective when the delimiters are variable or follow complex patterns, allowing for immediate decomposition into an array of strings, which can then be further processed. It acts efficiently when handling input parsing tasks such as reading comma-separated values or splitting sentences by punctuation. In contrast, `StringBuilder` is more suited for iterative character modifications and re-constructions rather than parsing-based decompositions .

The `Arrays.binarySearch(array, key)` function performs a binary search on a sorted array to find the specified `key`. It uses a divide-and-conquer approach, repeatedly dividing the search interval in half. If the value of the `key` is less than the middle element of the interval, it narrows the interval to the lower half. Otherwise, it reduces it to the upper half, until the `key` is found or the interval is empty. The efficiency and algorithm depend on the array being sorted; otherwise, it might not find the correct element or return an unexpected index because the assumptions of ordering used by the binary search algorithm are violated. This is why pre-sorting with `Arrays.sort()` is necessary for accurate results .

The `StringBuilder.replace(int start, int end, String str)` method replaces the characters in a substring of the `StringBuilder` with specified characters. The substring begins at the `start` index and extends to the `end` index, exclusive. This method is particularly useful for dynamically modifying strings without creating new string objects in memory, as would be required by String manipulation. For example, in a `StringBuilder` containing "Hello World", calling `sb.replace(6, 11, "Java")` would alter the string to "Hello Java", effectively substituting "World" with "Java" .

The `ArrayList.addAll(Collection<? extends E> c)` method allows for the consolidation of elements from one collection into another, enhancing list operations by enabling bulk addition. This is advantageous as it simplifies combining collections, reduces overhead compared to adding elements individually in a loop, and maintains operation atomicity. In scenarios requiring the union of two lists—such as consolidating user data or merging search results—using `addAll` increases efficiency and cleanliness of code by minimizing manual iterations, thus enhancing readability and performance .

The `parallelSort` method in the Java Arrays Utility Class is designed for performing a parallel sort on large arrays, which can provide performance improvements by taking advantage of multi-core processors. It sorts the array elements concurrently in separate threads, making it efficient for large datasets. In contrast, `sort` uses a sequential algorithm and is generally suitable for small to moderately sized arrays where the overhead of parallelism doesn't justify potential gains. `parallelSort` should be considered when dealing with large data sets where performance is crucial and the overhead of managing multiple threads is outweighed by the speed of parallel processing .

The `retainAll(Collection<?> c)` method in an ArrayList modifies the list it is called on by keeping only the elements that are also contained in the specified collection `c`, effectively intersecting the two collections. This operation can be useful in filtering a list against a set of permissible values. For example, if you have a list of integers representing IDs and want to keep only those that are approved, provided in another list, calling `retainAll` will efficiently filter the original list. This is especially useful in data processing where you need to match records with allowed keys or validate entries against a whitelist .

The `substring(int start, int end)` method in Java's String class returns a new string that is a subset of the original string, starting from index `start` and ending at index `end`, exclusive. This means the character at the `end` index is not included in the resulting substring. Proper bounds checking should be done to ensure that `start` is non-negative, `start` does not exceed the length of the string, and `end` is greater than `start` but less than or equal to the length of the string. Failure to do so can result in a `StringIndexOutOfBoundsException`. For example, for the string "hello", `s.substring(1, 4)` returns "ell" .

The `equals(String s)` method in Java performs a case-sensitive comparison between two strings, meaning it returns true only if the characters match exactly, including their case. This is appropriate when distinct character cases carry significance, such as passwords or case-sensitive file paths. On the other hand, `equalsIgnoreCase(String s)` performs a case-insensitive comparison, ignoring character case differences. This is particularly useful in scenarios like input validation (e.g., usernames, commands) where users might not adhere to case consistency. Choosing between these methods impacts the logic of applications, especially in contexts where case sensitivity might alter intended functionalities .

The `replaceAll(String regex, String replacement)` method is more effective than `replace(char oldChar, char newChar)` when complex pattern matching is needed. `replaceAll` utilizes regular expressions, allowing for more sophisticated replacements based on patterns rather than just replacing specific characters. This is particularly useful in scenarios where multiple characters fit a specific pattern. For instance, using `replaceAll("\\d", "")` on "a1b2c3" removes all digits, resulting in "abc" . The `replace` method only substitutes all occurrences of a single character with another character and doesn't support regular expressions.

You might also like