Java Strings are one of the most commonly used data types in Java programming. They are used to represent a sequence of characters and are immutable, meaning that once a string is created, it cannot be changed.
Strings in Java are represented by the java.lang.String
class. This class provides a number of methods for working with strings, such as concatenation, substring extraction, and searching for specific characters or substrings.
Here is an example of how to create a string in Java:
String myString = "Hello, world!";
In this example, the string "Hello, world!" is assigned to the variable myString
. This string can then be used in various ways, such as printing it to the console:
System.out.println(myString);
This will output the string "Hello, world!" to the console.
Strings in Java can also be concatenated using the
operator:
String firstName = "John"; String lastName = "Doe"; String fullName = firstName " " lastName;
In this example, the strings "John" and "Doe" are concatenated with a space in between to create the string "John Doe". This string is then assigned to the variable fullName
.
Strings in Java can also be compared using the equals()
method:
String str1 = "hello"; String str2 = "HELLO"; if (str1.equals(str2)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are not equal."); }
In this example, the equals()
method is used to compare the strings "hello" and "HELLO". Since these strings are not equal (due to the difference in case), the output will be "The strings are not equal."
Overall, Java Strings are a powerful and versatile data type that are essential for many Java programs. By understanding how to create, manipulate, and compare strings, you can greatly expand your programming capabilities.
Reference: