Strings
String
In Java, a String is a sequence of characters used to store text such as words, sentences, or any combination of letters, numbers, and symbols.
A String is one of the most commonly used data types in Java and is part of the java.lang package.
A String variable contains a collection of characters surrounded by double quotes (" ").
Strings are used for storing text in Java programs.
Example
public class Main {
Β public static void main(String[] args) {
Β Β // Creating a String variable to store text
Β Β String greeting = "Hello";
Β Β // Printing the value of String variable on screen
Β Β System.out.println(greeting);
Β }
}
String Concatenation
String concatenation in Java means joining two or more strings together to form a single string.
It is commonly used to combine text, variables, and output messages in Java programs.
The + operator can be used between strings to combine them. This is called concatenation.
Example
public class Main {
Β public static void main(String[] args) {
Β Β // Creating first string with a space at the end
Β Β String firstName = "John ";
Β Β // Creating second string
Β Β String lastName = "Doe";
Β Β // Using concat() method to join both strings
Β Β System.out.println(firstName.concat(lastName));
Β }
}
String Methods
String methods in Java are built-in functions used to perform different operations on strings such as finding length, changing case, comparing, searching, and modifying text.
String Methods
- length() β returns the number of characters in a string
- toUpperCase() β converts string to uppercase
- toLowerCase() β converts string to lowercase
- trim() β removes extra spaces from beginning and end
- charAt() β returns character at a specific position
- indexOf() β finds the position of a character or word
- substring() β extracts part of a string
- equals() β compares two strings
- equalsIgnoreCase() β compares strings ignoring case
- contains() β checks if string contains specific text
- replace() β replaces characters or words
- startsWith() β checks starting characters
- endsWith() β checks ending characters
- isEmpty() β checks if string is empty
- concat() β joins two strings