Introduction Java Strings
Welcome to our journey into the world of Java Strings. In this blog post, we will explore the power and flexibility of Strings in Java, a fundamental aspect of any Java program.
What is a Java String?
A String in Java is an immutable object that represents a sequence of characters. The java.lang.String class is used to create a string object. Java String
String greeting = “Hello, World!”;
Creating Strings
In Java, we can create Java Strings in two ways:
- String Literal: Java String literal is created by using double quotes.
Example:
String s1 = “Hello”;
2. By new keyword: Java String is created by using a keyword new.
Example:
String s2 = new String(“Hello”);
Java String Methods
Java provides several methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Here are a few:
- length(): The length() method returns the length of a string object.
Example:
String s = “Hello”;
System.out.println(s.length()); // Outputs 5
- concat(String otherString): The concat() method combines specified string at the end of this string. It returns combined string.
Example :
String s1 = “Hello”;
String s2 = “World”;
System.out.println(s1.concat(s2)); // Outputs HelloWorld
- charAt(int index): The charAt() method returns a char value at the given index number. The index number starts from 0 and goes up to n-1, where n is length of the string.
Example:
String s = “Hello”;
System.out.println(s.charAt(0)); // Outputs H
Complete Example using Various Java String methods
Example :
public class Main {
public static void main(String[] args) {
// Creating a string
String str = “Hello, World!”;
// Empty String
String emptyStr = “”;
System.out.println(“Is the string empty? ” + emptyStr.isEmpty()); // Outputs true
// Compare To
String str1 = “Apple”;
String str2 = “Banana”;
System.out.println(str1.compareTo(str2)); // Outputs -1
// Concat
String str3 = “Hello, “;
String str4 = “World!”;
System.out.println(str3.concat(str4)); // Outputs “Hello, World!”
// Endswith
String str5 = “Hello, World!”;
System.out.println(str5.endsWith(“!”)); // Outputs true
// Equals
String str6 = “Hello, World!”;
String str7 = “Hello, World!”;
System.out.println(str6.equals(str7)); // Outputs true
// Replace
String str8 = “Hello, World!”;
System.out.println(str8.replace(‘!’, ‘.’)); // Outputs “Hello, World.”
}
}
Conclusion
Strings in Java provide a wide range of operations that can be performed on a sequence of characters. Understanding Java Strings is crucial for any Java programmer. So, dive into coding and unleash the power of Java Strings!