Java Strings
Java strings are a collection of characters that are bounded by double quotes.
Example:
public class
Main
{
public static void main(String[] args) {
String
name
=
"Messi";
System.out.println(name);
}
}
Output:
Messi
String Concatenation
In Java, two strings can be concatenated using the
+
operator.
Example:
public class
Main
{
public static void main(String[] args) {
String
firstName
=
"Lionel";
String
lastName
=
"Messi";
System.out.println(firstName + " " + lastName);
}
}
Output:
Lionel Messi
String Methods
Java provides a number of built-in string manipulation methods.
length()
The length method returns the length of a string.
Example:
public class
Main
{
public static void main(String[] args) {
String
greeting
=
"Hello Java";
System.out.println(greeting.length());
}
}
Output:
10
indexOf()
The indexOf() function is employed to locate the index of a given character within a string.
Example:
public class
Main
{
public static void main(String[] args) {
String
greeting
=
"Hello Java";
System.out.println(greeting.indexOf("Java"));
}
}
Output:
6
toUpperCase() and toLowerCase()
The toUpperCase() and toLowerCase() methods are employed to transform a string into uppercase or lowercase letters.
Example:
public class
Main
{
public static void main(String[] args) {
String
greeting
=
"Hello Java";
System.out.println(greeting.toUpperCase());
System.out.println(greeting.toLowerCase());
}
}
Output:
HELLO JAVA
hello java