From switching to Java from Python, It was a bit difficult to get used to the inbuilt libraries and their usage. In this blog, I will be sharing some of the most commonly used inbuilt libraries in Java and short explanation of their usage. This will be helpful for me and those who are new to Java and want to get familiar with the inbuilt libraries.
Basics
Before using the libraries, we need to import them. Most commonly used libraries is java.util and this is all we need for now. We can import the whole library import java.util.*; or we can import specific classes like import java.util.ArrayList; and import java.util.Arrays;.
Math Library
The Math class provides methods for performing basic numeric operations such as exponentiation, logarithms, square roots, and trigonometric functions. It also provides constants such as Math.PI and Math.E.
Some commonly used methods are:
-
Math.max(a, b)- returns the maximum of two numbers. -
Math.min(a, b)- returns the minimum of two numbers. -
Math.abs(a)- returns the absolute value of a number.
example:Math.abs(-5)will return5. -
Math.pow(a, b)- returns(double) the value ofaraised to the power ofb. -
Math.sqrt(a)- returns the square root of a number.
example:Math.sqrt(16)will return4. -
Math.random()- returns(double) a random double value between 0.0 and 1.0. -
Math.round(a)- returns(double) the closest long to the argument, with ties rounding up. -
Math.ceil(a)- returns(double) the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer. -
Math.floor(a)- returns(double) the largest double value that is less than or equal to the argument and is equal to a mathematical integer. -
Math.PI- returns(double) the value of pi equals approximately 3.14159. -
Math.E- returns(double) the value of e equals approximately 2.71828.
Arrays Library
The Arrays class contains various methods for manipulating arrays (such as sorting and searching). To use this library, we need to import java.util.Arrays;.
Some commonly used methods are:
-
Arrays.sort(arr)- sorts the specified array into ascending numerical order.
example:Arrays.sort(arr);will sort the arrayarrin ascending order. TC is O(n log n). It internally uses Dual-Pivot Quicksort for primitive types and Timsort for objects. -
Arrays.equals(arr1, arr2)- returns true if the two specified arrays are equal to one another.
example:Arrays.equals(arr1, arr2);will return true ifarr1andarr2are equal. -
Arrays.fill(arr, value)- assigns the specified value to each element of the specified array.
example:Arrays.fill(arr, 0);will fill the arrayarrwith0. -
Arrays.binarySearch(arr, key)- searches the array for the specified value using the binary search algorithm. The array must be sorted before making this call. -
Arrays.toString(arr)- returns a string representation of the contents of the specified array.
example:Arrays.toString(arr);will return a string representation of the arrayarr. eg[1, 2, 3, 4]becomes"[1, 2, 3, 4]".
Collections Library
The collections library contains static methods for operating on or returning collections. To use this library, we need to import java.util.Collections;.
Some commonly used methods are:
-
Collections.sort(list)- sorts the specified list into ascending order, according to the natural ordering of its elements. -
Collections.reverse(list)- reverses the order of the elements in the specified list. -
Collections.shuffle(list)- randomly permutes the specified list using a default source of randomness. -
Collections.max(collection)- returns the maximum element of the given collection, according to the natural ordering of its elements. -
Collections.min(collection)- returns the minimum element of the given collection, according to the natural ordering of its elements. -
Collections.frequency(collection, element)- returns the number of elements in the specified collection equal to the specified object.
example:Collections.frequency(list, 1);will return the number of times1appears in the listlist.
Note: Collections library is a utils library for collections and it is not a collection itself.
String Library
The String class provides methods for manipulating strings. Import is not required for String class as it is part of java.lang package which is imported by default.
Some commonly used methods are:
-
str.length()- returns the length of the string.
example:str.length();will return the length of the stringstr. -
str.charAt(index)- returns the char value at the specified index.
example:str.charAt(0);will return the first character of the stringstr. -
str.substring(start, end)- returns a new string that is a substring of this string.
example:str.substring(0, 5);will return the substring ofstrfrom index0to index4. Note that the end index is exclusive. -
str.equals(anotherString)- compares this string to the specified object.
example:str.equals("hello");will return true ifstris equal to"hello". -
str.equalsIgnoreCase(anotherString)- compares this string to another string, ignoring case considerations.
example:str.equalsIgnoreCase("hello");will return true ifstris equal to"hello"ignoring case. -
str.contains(sequence)- returns true if this string contains the specified sequence of char values. -
str.indexOf(substring)- returns the index within this string of the first occurrence of the specified substring.
example:str.indexOf("hello");will return the index of the first occurrence of the substring"hello"in the stringstr. If the substring is not found, it will return-1. -
str.replace(oldChar, newChar)- returns a new string resulting from replacing all occurrences ofoldCharin this string withnewChar.
example:str.replace('a', 'b');will return a new string where all occurrences of'a'instrare replaced with'b'. -
str.split(regex)- splits this string around matches of the given regular expression.
example:str.split(" ");will return an array of strings computed by splittingstraround matches of the given regular expression (in this case, a space). -
str.trim()- returns a string whose value is this string, with any leading and trailing whitespace removed.
example:str.trim();will return a new string with leading and trailing whitespace removed fromstr. -
str.toLowerCase()- converts all of the characters in this String to lower case using the rules of the default locale.
example:str.toLowerCase();will return a new string with all characters instrconverted to lower case. -
str.toUpperCase()- converts all of the characters in this String to upper case using the rules of the default locale.
example:str.toUpperCase();will return a new string with all characters instrconverted to upper case. -
str.isEmpty()- returns true if, and only if, length() is 0.
example:str.isEmpty();will return true ifstris an empty string. -
str.isBlank()- returns true if the string is empty or contains only white space codepoints, otherwise false.
example:str.isBlank();will return true ifstris an empty string or contains only white space.
StringBuilder Library
The StringBuilder class provides an API for creating and manipulating strings. It is more efficient than using the String class when we need to concatenate strings in a loop or when we need to modify a string multiple times. Import is not required for StringBuilder class as it is part of java.lang package which is imported by default.
Some commonly used methods are:
-
StringBuilder sb = new StringBuilder();- creates a new StringBuilder object. -
sb.append(str)- appends the specified string to this character sequence.
example:sb.append("hello");will append the string"hello"to the StringBuildersb. -
sb.toString()- returns a string representing the data in this sequence.
example:sb.toString();will return a string representation of the data in the StringBuildersb. -
sb.length()- returns the length of the character sequence.
example:sb.length();will return the length of the character sequence in the StringBuildersb. -
sb.charAt(index)- returns the char value at the specified index.
example:sb.charAt(0);will return the first character of the character sequence in the StringBuildersb. -
sb.substring(start, end)- returns a new string that is a substring of this sequence.
example:sb.substring(0, 5);will return the substring of the character sequence in the StringBuildersbfrom index0to index4. Note that the end index is exclusive. -
sb.delete(start, end)- removes the characters in a substring of this sequence. The substring begins at the specifiedstartand extends to the character at indexend - 1or to the end of the sequence ifendis greater than the length of the sequence.
example:sb.delete(0, 5);will remove the characters in the substring of the character sequence in the StringBuildersbfrom index0to index4. Note that the end index is exclusive. -
sb.insert(offset, str)- inserts the specified string into this character sequence at the specified offset.
example:sb.insert(0, "hello");will insert the string"hello"into the character sequence in the StringBuildersbat index0. -
sb.reverse()- causes this character sequence to be replaced by the reverse of the sequence.
example:sb.reverse();will reverse the character sequence in the StringBuildersb.
Integer / Long / Double Libraries
The Integer, Long, and Double classes provide methods for converting strings to their respective primitive types and vice versa. They also provide methods for parsing strings and for performing various operations on the primitive types. Import is not required for these classes as they are part of java.lang package which is imported by default.
Some commonly used methods are:
-
Integer.parseInt(str)- parses the string argument as a signed decimal integer.
example:Integer.parseInt("123");will return the integer123. -
Integer.toString(i)- returns a string representation of the integer argument.
example:Integer.toString(123);will return the string"123". -
Long.parseLong(str)- parses the string argument as a signed decimal long.
example:Long.parseLong("123456789");will return the long123456789. -
Long.toString(l)- returns a string representation of the long argument.
example:Long.toString(123456789);will return the string"123456789". -
Double.parseDouble(str)- parses the string argument as a double.
example:Double.parseDouble("3.14");will return the double3.14. -
Double.toString(d)- returns a string representation of the double argument.
example:Double.toString(3.14);will return the string"3.14".
Character Library
The Character class provides methods for manipulating characters. Import is not required for Character class as it is part of java.lang package which is imported by default.
Some commonly used methods are:
-
Character.isDigit(ch)- returns true if the specified character is a digit.
example:Character.isDigit('1');will return true because'1'is a digit. -
Character.isLetter(ch)- returns true if the specified character is a letter.
example:Character.isLetter('a');will return true because'a'is a letter. -
Character.isWhitespace(ch)- returns true if the specified character is a whitespace character.
example:Character.isWhitespace(' ');will return true because' 'is a whitespace character. -
Character.toUpperCase(ch)- converts the character argument to upper case using case mapping information from the UnicodeData file.
example:Character.toUpperCase('a');will return'A'. -
Character.toLowerCase(ch)- converts the character argument to lower case using case mapping information from the UnicodeData file.
example:Character.toLowerCase('A');will return'a'. -
Character.isUpperCase(ch)- returns true if the specified character is an uppercase letter.
example:Character.isUpperCase('A');will return true because'A'is an uppercase letter. -
Character.isLowerCase(ch)- returns true if the specified character is a lowercase letter.
example:Character.isLowerCase('a');will return true because'a'is a lowercase letter.
Conclusion
In this blog, we have covered some of the most commonly used inbuilt libraries in Java and their usage. Hopefully, this will be helpful for those who are new to Java and want to get familiar with the inbuilt libraries. I will update this blog with more libraries and their usage in the future.