Skip to toolbar

Basic Java – 14 || Learn about String literals in Java.

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.

MethodExampleDescription
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:
  1. Index of a string would start from 0.
  2. The searching of the character or substring is case sensitive. Means small a and capital A are considered differently.
  3. When target string or character is not found in the target String. It will always return -1.
  4. 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:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:




Leave a Reply

Your email address will not be published. Required fields are marked *

Site Statistics

  • Users online: 0 
  • Visitors today : 4
  • Page views today : 4
  • Total visitors : 49,318
  • Total page view: 67,889

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.