Java String Methods
Introduction
In this tutorial, we will explore String methods in Java. Strings are one of the most commonly used classes in Java, and they come with several built-in methods that can make your life as a developer much easier. These methods can help you manipulate, analyze, and operate on strings.
What is a String?
In Java, a String is considered as an object that represents a sequence of characters. The java.lang.String
class is used to create a string object. For example:
String myString = "Hello, World!";
String Methods in Java
Let's delve into some of the most commonly used String methods in Java.
Length Method
The .length()
method returns the length of a string.
String str = "Hello World";
int length = str.length();
System.out.println("Length of the string is: " + length);
charAt Method
The .charAt(index)
method returns the character at the specified index.
String str = "Hello World";
char character = str.charAt(0);
System.out.println("Character at 0 index is: " + character);
concat Method
The .concat(String str)
method concatenates the specified string to the end of this string.
String str1 = "Hello";
String str2 = "World";
String str3 = str1.concat(str2);
System.out.println("Concatenated string is: " + str3);
equals Method
The .equals(Object obj)
method compares this string to the specified object.
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";
System.out.println("str1 equals to str3: " + str1.equals(str3));
System.out.println("str1 equals to str2: " + str1.equals(str2));
toLowerCase and toUpperCase Methods
The .toLowerCase()
and .toUpperCase()
methods convert all the characters in this string to lower case and upper case respectively.
String str = "Hello World";
String lowerStr = str.toLowerCase();
String upperStr = str.toUpperCase();
System.out.println("Lower case string: " + lowerStr);
System.out.println("Upper case string: " + upperStr);
trim Method
The .trim()
method returns a copy of this string with leading and trailing white space removed.
String str = " Hello World ";
String trimmedStr = str.trim();
System.out.println("Trimmed string: " + trimmedStr);
Conclusion
In this tutorial, we've covered some of the most commonly used String methods in Java. Through these methods, Java allows us to easily manipulate and handle strings in our code. However, there are many other String methods available in Java that you can explore.
Remember, practice is key when learning a new programming language, so make sure to try these methods out in different combinations and contexts. Happy Coding!