A String is a class used to declare and initialize the string literals. These string literals are basically the group of characters.
In general, strings are immutable. It means each time we perform any modification in the existing String object or variable it creates a new object and allocates new memory.
String declaration and Initialization
String s1=”Computer”;
String s2=”This is a computer.”;
String s3=”is”;
The simplest way to declare and initialize the String is mentioned above.
Useful Methods of String
Please note that below methods will not perform any change in the original string. Always a new version of string created in the memory.
Method | Example | Description |
---|---|---|
charAt(index) | s1.charAt(2); | Getting specific character from a String based on the index. |
concat(string) | s1.concat(s2); | Concatenate two strings. |
contains(string) | s2.contains(s3); | Checks whether one string is present in another string. |
contentEquals(string) | s2.contentEquals(s4); | Checks the exact match of two strings. |
substring(startIndex) | s2.substring(4); | Getting substring based on start index |
substring(startIndex, endIndex) | s2.substring(4,9); | Getting substring based on start index and end index |
endsWith(string) | s2.endsWith(“ter.”); | To test if a string ends with specific word or character |
length() | s1.length(); | Getting character count in a string. |
valueOf([int],[bool]) | s1.valueOf(10); | Converts the specific type of value into the String format. |
equalsIgnoreCase(string) | s1.equalsIgnoreCase(s5); | Compare two strings with ignoring the case of letters. |
Use of above methods in Coding
public class StringMethods { public static void main(String[] args) { String s1="Computer"; String s2="This is a computer."; String s3="is"; String s4="Computer"; String s5="computer"; // Getting char from string based on index. System.out.println("Character at 4th position: "+s1.charAt(3)); // Concatenate two Strings. System.out.println("Concatenate s1 and s2: "+s1.concat(s2)); // Checks whether one string is present in other string. // Result would be case-sensitive. System.out.println("Checks whether s3 present in s2: "+s2.contains(s3)); System.out.println("Checks whether s1 prsent in S2: "+s2.contains(s1)); // Checks the exact match of two strings. System.out.println("Checks if value of s1 is equal to s2: "+s1.contentEquals(s4)); //Getting substring based on start index System.out.println("Getting substring based on start index:"+s2.substring(4)); //Getting substring based on start index and end index System.out.println("Getting substring based on indces:"+s2.substring(4,9)); // To test if a string ends with specific word or character System.out.println("Check if s2 end with word 'ter': "+s2.endsWith("ter.")); // Getting character count in a string. System.out.println("Total characters in s1: "+s1.length()); //Converts the specific type of value into the String format. //In below example we converted 'i' into the string and concatenate with another value '5' int i=10; System.out.println("Converts integer value to String:"+s1.valueOf(i)+5); // Compare two strings with ignoring the case of letters. System.out.println("Compare strings with ignoring the case: "+s1.equalsIgnoreCase(s5)); } } Output: Character at 4th position: p Concatenate s1 and s2: ComputerThis is a computer. Checks whether s3 present in s2: true Checks whether s1 prsent in S2: false Checks if value of s1 is equal to s2: true Getting substring based on start index: is a computer. Getting substring based on indces: is a Check if s2 end with word 'ter': true Total characters in s1: 8 Converts integer value to String:105 Compare strings with ignoring the case: true
Split() of String
There are some chances where we need to split a single string or sentence into multiple sub-strings. This is different from the substring().
While using split() method we store single string into string array. For example:
System.out.println("Sentence: "+s2);
String[] array=s2.split(" ");
System.out.println("Converted to String Array:-");
for (String string : array) {
System.out.println(string);
}
Output:
Sentence: This is a computer.
Converted to String Array:-
This
is
a
computer.
IndexOf() and lastIndexOf()
Both indexOf() and lastIndexOf() are methods of String object. These methods will be used to get the position or index of a particular character/substring within the target string.
Important Notes:
- Index of a string would start from 0.
- The searching of the character or substring is case sensitive. Means small a and capital A are considered differently.
- When target string or character is not found in the target String. It will always return -1.
- The only difference between these methods in only the way of traversing.
indexOf()
This method returns the first occurrence of the specified character or substring. The traversing would be from starting of the string.
- indexOf(char ch);
- indexOf(String str);
- indexOf(char ch,int fromIndex);
- indexOf(int fromIndex, char ch);
String temp="Strings in Java. Various methods in Java.";
System.out.println("Position of char 'i': "+temp.indexOf('i'));
Output would be 3 as the first letter is appearing at index 3 in the given string.
System.out.println("Position of char 'i' after given index value: "+temp.indexOf('i',5));
Output would be 8 as traversing is getting started after index 5. And the first instance of i is present at index position 8.
lastIndexOf()
This method returns the last occurrence of the specified character or substring. The traversing would be from starting of the string.
- indexOf(char ch);
- indexOf(String str);
String temp="Strings in Java. Various methods in Java."; System.out.println("Position of char 'i' from end: "+temp.lastIndexOf('i')); Output would be 33 as last letter is appearing at index 33 in the given string.
For below methods backward traversing works along with the specified index.
- indexOf(char ch,int fromIndex);
- indexOf(int fromIndex, char ch);
System.out.println("Position of char 'i' after given index value: "+temp.lastIndexOf('i',5));
Output would be 3 as traversing is getting started after index 5 but from backward in the string.
Code Example
/** * */ /** * @author ashok.kumar * */ public class StrIndex { /** * @param args */ public static void main(String[] args) { String temp="Strings in Java. Various methods in Java."; System.out.println("Target String: "+temp); System.out.println("\nExample of indexOf():-"); System.out.println("Position of char 'i': "+temp.indexOf('i')); System.out.println("Position of string 'Java': "+temp.indexOf("Java")); System.out.println("Position of string 'java': "+temp.indexOf("java")); System.out.println("Position of char 'i' after given index value: "+temp.indexOf('i',5)); System.out.println("Position of string 'in' after given index value: "+temp.indexOf("in",13)); System.out.println("\nExample of lastIndexOf():-"); System.out.println("Position of char 'i' from end: "+temp.lastIndexOf('i')); System.out.println("Position of string 'Java': "+temp.lastIndexOf("Java")); System.out.println("Position of string 'java': "+temp.lastIndexOf("java")); System.out.println("Position of char 'i' after given index value: "+temp.lastIndexOf('i',5)); System.out.println("Position of string 'in' after given index value: "+temp.lastIndexOf("in",13)); } } Output: Target String: Strings in Java. Various methods in Java. Example of indexOf():- Position of char 'i': 3 Position of string 'Java': 11 Position of string 'java': -1 Position of char 'i' after given index value: 8 Position of string 'in' after given index value: 33 Example of lastIndexOf():- Position of char 'i' from end: 33 Position of string 'Java': 36 Position of string 'java': -1 Position of char 'i' after given index value: 3 Position of string 'in' after given index value: 8
Related Links:
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.
- Basic Java – 23 || String, StringBuffer & StringBuilder in Java.
- Basic Java – 24 || Exception Handling using Try Catch.
- File Handling | Reading data from word document(.doc or .docx) in JAVA.
- File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.
- File Handling | Writing data into an Excel(.XLSX or .XLS) File.
- File Handling | Implement formatting in Excel using Java.
- File Handling | Copy existing data from one workbook to another workbook in Java.
- File Handling | Reading data from PDF file using JAVA.
- File Handling || Traverse folders and subfolders in Java.
- File Handling || Reading and Writing data from a text file.
- File Handling || Multiple file creation using template based input data.
- Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).
- QnA || How to use Constructors in Abstract class?
- QnA | Difference between Integer and int keywords.
- QnA | Can main method be overloaded?
- QnA | How do I reverse a String/Sentence in Java?
- QnA | Perform Multiplication and Division without * or / or % operators.
- QnA | How do I get the default value of data type?
- QnA | How to split String if it contains period symbol (.) in between?
- Different ways to Reverse a String in Java.
- Copy formatting & style of cells from one sheet to another.
- Getting IP address and Hostname using InetAddress Class.
- User inputs via Command Prompt using arguments of main() method of a class.
- Program for List and ArrayList in Java.
- Useful methods and implementation under Scanner Class.
- Swapping two variable values without using any third variable.
- Difference between int x= 10 and y=010 in Java.
- Parameterized Constructors v/s Setter and Getter function in JAVA.
- Override a Static Method.