What is String in Java
In Java, a String
is a class that represents a sequence of characters. It is one of the most commonly used classes in Java and is part of the java.lang
package, which means it is automatically imported into every Java program. Strings in Java are immutable, meaning once a String
object is created, it cannot be changed. If you want to modify a string, you create a new string object.
Creating Strings in Java:
1. Using String Literal:
You can create a string using double quotes. Java automatically converts string literals to String objects.
String greeting = "Hello, World!";
2. Using the new
Keyword:
You can create a string object using the new
keyword, which explicitly creates a new instance of the String class.
String greeting = new String("Hello, World!");
String Methods and Operations:
Strings in Java come with a variety of built-in methods for manipulating and analyzing the content. Here are some common operations and methods related to strings:
1. Concatenation:
Strings can be concatenated using the +
operator.
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // Results in "John Doe"
2. Length:
You can find the length of a string using the length()
method.
String text = "Java Programming";
int length = text.length(); // length is 17
3. Substring:
You can extract a substring from a string using the substring()
method.
String text = "Hello, World!";
String substring = text.substring(7); // Results in "World!"
4. Equality:
Strings should be compared using the equals()
method, not ==
.
String str1 = "hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // true
5. Immutable Nature:
Strings are immutable; their values cannot be changed after creation. When you modify a string, a new object is created.
String original = "Hello";
String modified = original.concat(", World!"); // Creates a new string object
In summary, a String
in Java is a sequence of characters, and it is an important and versatile data type that finds widespread use in Java applications, from simple text manipulation to complex operations involving regular expressions and internationalization.