Applying Built-in Methods in Practice
Now that we have a solid understanding of how to call built-in methods in Java, let's explore some practical applications and examples to solidify your knowledge.
String Manipulation
One of the most common use cases for built-in methods in Java is string manipulation. The String
class provides a wide range of built-in methods to perform various operations on strings, such as:
String originalString = " LabEx is the best! ";
String trimmedString = originalString.trim(); // Removes leading and trailing whitespace
String lowercaseString = originalString.toLowerCase(); // Converts the string to lowercase
String replacedString = originalString.replace("best", "greatest"); // Replaces a substring
Mathematical Operations
The Math
class in Java offers a variety of built-in methods for performing mathematical operations, such as:
double radius = 5.0;
double area = Math.PI * Math.pow(radius, 2); // Calculates the area of a circle
int absoluteValue = Math.abs(-10); // Returns the absolute value of a number
double maxValue = Math.max(10.5, 15.2); // Returns the maximum of two values
File I/O
Java's built-in methods also provide functionality for working with files and directories. The File
class and its associated methods can be used for tasks like:
File file = new File("example.txt");
boolean deleted = file.delete(); // Deletes the file
boolean created = file.createNewFile(); // Creates a new file
String[] files = file.list(); // Returns an array of files in a directory
Collections and Data Structures
Java's standard library includes various collection classes, such as ArrayList
, HashMap
, and HashSet
, each with their own set of built-in methods for manipulating and working with data structures.
ArrayList<String> names = new ArrayList<>();
names.add("John"); // Adds an element to the ArrayList
names.remove(0); // Removes the element at index 0
int size = names.size(); // Returns the size of the ArrayList
By exploring these practical examples, you can see how the effective use of built-in methods in Java can simplify your code, improve its readability, and enhance the overall efficiency of your applications.