Java String Manipulation with EXAMPLE

What are Strings in Java?

A string in literal terms is a series of characters. Hey, did you say characters, isn’t it a primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an array of characters.

So my above string of “ROSE” can be represented as the following –

Java String

Why use Strings?

One of the primary functions of modern computer science, is processing human language.

Similarly to how numbers are important to math, language symbols are important to meaning and decision making. Although it may not be visible to computer users, computers process language in the background as precisely and accurately as a calculator. Help dialogs provide instructions. Menus provide choices. And data displays show statuses, errors, and real-time changes to the language.

As a Java programmer, one of your main tools for storing and processing language is going to be the String class.

String Syntax Examples

Now, let’s get to some syntax,after all, we need to write this in Java code isn’t it.

String is an array of characters, represented as:

//String is an array of characters
char[] arrSample = {'R', 'O', 'S', 'E'};
String strSample_1 = new String (arrSample);

In technical terms, the String is defined as follows in the above example-

= new (argument);

Now we always cannot write our strings as arrays; hence we can define the String in Java as follows:

//Representation of String
String strSample_2 = "ROSE";

In technical terms, the above is represented as:

= ;

The String Class Java extends the Object class.

String Concatenation:

Concatenation is joining of two or more strings.

Have a look at the below picture-

String Syntax Examples

We have two strings str1 = “Rock” and str2 = “Star”

If we add up these two strings, we should have a result as str3= “RockStar”.

Check the below code snippet,and it explains the two methods to perform string concatenation.

First is using “concat” method of String class and second is using arithmetic “+” operator. Both results in the same output

public class Sample_String{
  public static void main(String[] args){
//String Concatenation
String str1 = "Rock";
String str2 = "Star";
//Method 1 : Using concat
String str3 = str1.concat(str2);
System.out.println(str3);
//Method 2 : Using "+" operator
String str4 = str1 + str2;
System.out.println(str4);
}
}

Expected Output:

RockStar
RockStar

Important Java string methods:

Java string methods

Let’s ask the Java String class a few questions and see if it can answer them:

String “Length” Method

How will you determine the length of given String? I have provided a method called as “length”. Use it against the String you need to find the length.

public class Sample_String{
  public static void main(String[] args){  //Our sample string for this tutorial
  String str_Sample = "RockStar";
  //Length of a String
  System.out.println("Length of String: " + str_Sample.length());}}

Expected Output:

Length of String: 8

String “indexOf” Method

If I know the length, how would I find which character is in which position? In short, how will I find the index of a character?

You answered yourself, buddy, there is an “indexOf” method that will help you determine the location of a specific character that you specify.

public class Sample_String{
  public static void main(String[] args){//Character at position
String str_Sample = "RockStar";
System.out.println("Character at position 5: " + str_Sample.charAt(5));
//Index of a given character
System.out.println("Index of character 'S': " + str_Sample.indexOf('S'));}}

Expected Output:

Character at position 5: t
Index of character 'S': 4

String “charAt” Method

Similar to the above question, given the index, how do I know the character at that location?

Simple one again!! Use the “charAt” method and provide the index whose character you need to find.

public class Sample_String{
  public static void main(String[] args){//Character at position
String str_Sample = "RockStar";
System.out.println("Character at position 5: " + str_Sample.charAt(5));}}

Expected Output:

Character at position 5: t

String “CompareTo” Method

Do I want to check if the String that was generated by some method is equal to something that I want to verify with? How do I compare two Strings?

Use the method “compareTo” and specify the String that you would like to compare.

Use “compareToIgnoreCase” in case you don’t want the result to be case sensitive.

The result will have the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

public class Sample_String{
  public static void main(String[] args){//Compare to a String
String str_Sample = "RockStar";
  System.out.println("Compare To 'ROCKSTAR': " + str_Sample.compareTo("rockstar"));
  //Compare to - Ignore case
  System.out.println("Compare To 'ROCKSTAR' - Case Ignored: " + str_Sample.compareToIgnoreCase("ROCKSTAR"));}}

Expected Output:

Compare To 'ROCKSTAR': -32
Compare To 'ROCKSTAR' - Case Ignored: 0

String “Contain” Method

I partially know what the string should have contained, how do I confirm if the String contains a sequence of characters I specify?

Use the method “contains” and specify the characters you need to check.

Returns true if and only if this string contains the specified sequence of char values.

public class Sample_String{
  public static void main(String[] args){  //Check if String contains a sequence
String str_Sample = "RockStar";
  System.out.println("Contains sequence 'tar': " + str_Sample.contains("tar"));}}

Expected Output:

Contains sequence 'tar': true

String “endsWith” Method

How do I confirm if a String ends with a particular suffix? Again you answered it. Use the “endsWith” method and specify the suffix in the arguments.

Returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object.

public class Sample_String{
  public static void main(String[] args){  //Check if ends with a particular sequence
String str_Sample = "RockStar";
  System.out.println("EndsWith character 'r': " + str_Sample.endsWith("r"));}}

Expected Output:

EndsWith character 'r': true

String “replaceAll” & “replaceFirst” Method

I want to modify my String at several places and replace several parts of the String?

Java String Replace, replaceAll and replaceFirst methods. You can specify the part of the String you want to replace and the replacement String in the arguments.

public class Sample_String{
  public static void main(String[] args){//Replace Rock with the word Duke
String str_Sample = "RockStar";
System.out.println("Replace 'Rock' with 'Duke': " + str_Sample.replace("Rock", "Duke"));}}

Expected Output:

Replace 'Rock' with 'Duke': DukeStar

String Java “tolowercase” & Java “touppercase” Method

I want my entire String to be shown in lower case or Uppercase?

Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be converted.

public class Sample_String{
  public static void main(String[] args){//Convert to LowerCase
String str_Sample = "RockStar";
System.out.println("Convert to LowerCase: " + str_Sample.toLowerCase());
//Convert to UpperCase
System.out.println("Convert to UpperCase: " + str_Sample.toUpperCase());}}

Expected Output:

Convert to LowerCase: rockstar
Convert to UpperCase: ROCKSTAR

Important Points to Note:

  • String is a Final class; i.e once created the value cannot be altered. Thus String objects are called immutable.
  • The Java Virtual Machine(JVM) creates a memory location especially for Strings called String Constant Pool. That’s why String can be initialized without ‘new’ keyword.
  • String class falls under java.lang.String hierarchy. But there is no need to import this class. Java platform provides them automatically.
  • String reference can be overridden but that does not delete the content; i.e., if

String h1 = “hello”;

h1 = “hello”+”world”;

then “hello” String does not get deleted. It just loses its handle.

  • Multiple references can be used for same String but it will occur in the same place; i.e., if

String h1 = “hello”;

String h2 = “hello”;

String h3 = “hello”;

then only one pool for String “hello” is created in the memory with 3 references-h1,h2,h3

  • If a number is quoted in ” “ then it becomes a string, not a number anymore. That means if

String S1 =”The number is: “+ “123”+”456″;

System.out.println(S1);

then it will print: The number is: 123456

If the initialization is like this:

String S1 = “The number is: “+(123+456);

System.out.println(S1);

then it will print: The number is:579

That’s all to Strings!