Welcome, Cosmic Coder! Today, we are venturing into the realm of Java's built-in functions — pre-packaged tools that will turbocharge your coding experience. Our journey includes acquainting ourselves with built-in functions, their variations uses, tips, and some hands-on coding.
Built-in functions are like freebies in Java. They are built-in and ready to use. You just call them, and they respond, making your programming life easier!
Java offers a wide range of built-in functions that mostly fit under three categories — Math, String, and Array. Let's dive in!
Java strings carry built-in methods for manipulation:
-
str.length(): Measures the size of stringstr. For example,"Hello!".length() = 6. -
str.charAt(index): Finds the character at theindex-thlocation of stringstr. For example,"Hello!".charAt(0) = 'H'. -
str.substring(startIndex, endIndex): Carves out a part of the narrativestrfromstartIndex(inclusive) toendIndex(exclusive). For example,"Hello".substring(1, 3) = "el". -
str.concat(anotherStr): MergesstrandanotherStrinto one string. For example,"Hello".concat(" world") = "Hello world". -
str.equals(anotherStr): Checks ifstrandanotherStrmatch completely. For example,"Hello".equals("Hello") = true.
Some built-in functions in Java live inside utility classes that need to be imported before you can use them. An import statement at the top of your file tells Java where to find these classes. For array helper functions, you need to add import java.util.Arrays; at the top of your file. Without this line, Java won't recognize the Arrays class and your code won't compile. (Note: The Math and String functions we covered earlier don't require an import because they are part of Java's core java.lang package, which is automatically available.)
Java arrays come with built-in functions:
Arrays.toString(arr): Translatesarrinto a string.Arrays.sort(arr): Organizesarrin ascending order, much like arranging books alphabetically. For example,
