Strings in Java

Array of Strings in Java

Introduction to Strings in Java

A string in Java is a sequence of characters. It is a reference type that represents a character array. Strings are immutable, which means that once they are created, their contents cannot be changed.

Strings are one of the most commonly used data types in Java. They are used to represent a wide variety of data, such as names, addresses, and text messages.

To create a string in Java, you can use the new keyword and the String constructor. For example, the following code creates a string that contains the text "Hello, world!":


  String myString = new String("Hello, world!");
 

You can also create a string by using a string literal. A string literal is a sequence of characters enclosed in double quotes. For example, the following code creates a string literal:


  String myString = "Hello, world!";
 
Here are some of the most common uses of strings in Java:
  • To represent text data, such as names, addresses, and messages.
  • To store configuration information, such as database connection strings and file paths.
  • To process user input, such as form data and search queries.
  • To generate output, such as HTML pages and PDF reports.
Methods of String Class
Method Description
charAt() Returns the character at the specified index.
codePointAt() Returns the code point of the character at the specified index.
compareTo() Compares this string to the specified string and returns an integer indicating which string is greater.
compareToIgnoreCase() Compares this string to the specified string ignoring case and returns an integer indicating which string is greater.
concat() Concatenates this string with the specified string and returns a new string.
contains() Returns true if this string contains the specified substring, false otherwise.
endsWith() Returns true if this string ends with the specified substring, false otherwise.
equals() Returns true if this string is equal to the specified object, false otherwise.
equalsIgnoreCase() Returns true if this string is equal to the specified string ignoring case, false otherwise.
getChars() Copies the characters in this string to the specified character array.
getBytes() Encodes this string using the specified charset and returns a byte array.
hashCode() Returns the hash code of this string.
indexOf() Returns the index of the first occurrence of the specified substring in this string, or -1 if the substring is not found.
indexOf(int, int) Returns the index of the first occurrence of the specified substring in this string, starting at the specified index, or -1 if the substring is not found.
isEmpty() Returns true if this string is empty, false otherwise.
lastIndexOf() Returns the index of the last occurrence of the specified substring in this string, or -1 if the substring is not found.
lastIndexOf(int, int) Returns the index of the last occurrence of the specified substring in this string, starting at the specified index, or -1 if the substring is not found.
length() Returns the length of this string.
matches() Returns true if this string matches the specified regular expression, false otherwise.
replace() Replaces all occurrences of the specified character in this string with the specified new character and returns a new string.
replaceFirst() Replaces the first occurrence of the specified character in this string with the specified new character and returns a new string.
replaceAll() Replaces all occurrences of the specified substring in this string with the specified new string and returns a new string.
replaceFirst() Replaces the first occurrence of the specified substring in this string with the specified new string and returns a new string.
split() Splits this string into an array of strings using the specified delimiter.
startsWith() Returns true if this string starts with the specified substring, false otherwise.
subSequence() Returns a subsequence of this string.
substring() Returns a substring of this string from the specified index to the end of the string.
substring(int, int) Returns a substring of this string from the specified index to the specified

Exercises

Determine the output of the following Code


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name ="Satish";
    String test = "Satish";
    System.out.println(name==test);
  }
}

Output  - true (because both the references are pointing to the 
same object in the String Constant Pool)   

Determine the output of the following Code


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name = new String("Satish");
    String test = new String("Satish");
    System.out.println(name==test);
  }
}

Output - false (references point to different locations on the heap)    

Determine the output of the following Code


  public class javalabclass 
{
  public static void main(String args[])
    {
    String test = "Satish";
    String name = new String("Satish").intern();
    System.out.println(name==test);
  }
}

Output - true (Allocation happens only once inside String Constant Pool.
Both test and name point to the same location inside the pool.)      

use of charAt() method for extracting a character


  public class javalabclass 
{
  public static void main(String args[])
    {
    String sentence = "Satish teaches Java";
    System.out.println(sentence.charAt(0));
    
  }
}
Output - S (character at index 0 is retrieved using charAt(0).)   

Determine the length of a String


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name = "Satish";
    System.out.println(name.length());
  }
}

Output - 6 (Determines the number of characters in a String)   

Concatenation of two Strings


  public class javalabclass 
{
  public static void main(String args[])
    {
    String Title ="Dr.";
    String name = "Satish";
    System.out.println(Title.concat(name));
    System.out.println(Title+name);
  }
}

Output
Dr.Satish
Dr.Satish    

Code for comparing two Strings using boolean method equals()


  public class javalabclass 
{
  public static void main(String args[])
    {
    String Title ="Dr.";
    String name = "Satish";
    System.out.println(Title.equals(name));
  }
}

Output - false (two strings are not equal)   

Code for comparing two Strings using compareTo method


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name ="Satish";
    String test_name = "Satish";
  System.out.println(name.compareTo(test_name));
  }
}
Output - 0 (When two strings are equal the output will be 0)   

compareTo method Result - String1 > String2


  public class javalabclass 
{
  public static void main(String args[])
    {
    String string1 ="atish";
    String string2 = "Satish";
    System.out.println(string1.compareTo(string2));
  }
}
Output >0  (Output will be greater than 0 when string1 > string2)     

compareTo method Result - String1 < String2


public class javalabclass 
{
  public static void main(String args[])
    {
    String string1 ="Ratish";
    String string2 = "Satish";
    System.out.println(string1.compareTo(string2));
  }
}
Output  < 0 (Output will be lesser than 0 when string1 < string2)   

Code for finding substring in Java


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name = "Satish";
    System.out.println(name.substring(0, 3));
  }
}

Output  - Sat (from the starting index 0 three characters are retrieved)   

Copying a String to another String


public class javalabclass 
{
  public static void main(String args[])
    {
    String name = "Satish";
    String test_name=name;
    System.out.println(test_name);
  }
}
Output - Satish   

Code for removing leading and trailing spaces in a String


public class javalabclass 
{
  public static void main(String args[])
    {
    String name = " Satish ";
    System.out.println(name.trim());
  }
}

Output- Satish   

Code for replacing a Character in a String


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name = "Satish";
      String replaced = name.replace('S', 'R');
      System.out.println(replaced);
  }
}

Output - Ratish    

Code for searching a string using indexOf method


  public class javalabclass 
{
  public static void main(String args[])
    {
      String name = "Satish teaches Java";
      System.out.println(name.indexOf("Satish"));
  }
}
Output – 0 (Satish occurs at index 0. The index of first occurrence will 
retrieved. If there is no match then a -1 will be returned)   

Code for searching a string using lastIndexOf method


  public class javalabclass 
{
  public static void main(String args[])
    {
      String name = "Satish teaches Java";
      System.out.println(name.lastIndexOf("Java"));
  }
}

Output  15 (Search happens from the end of the String. 
If there is no match then a -1 will be returned)   

Code for converting String cases


  public class javalabclass 
{
  public static void main(String args[])
    {
    String sentence = "Satish teaches Java";
      System.out.println(sentence.toLowerCase());
      System.out.println(sentence.toUpperCase());
  }
}

Output:
satish teaches java
SATISH TEACHES JAVA
   

Code for checking if a string is empty


  public class javalabclass 
{
  public static void main(String args[])
    {
    String sentence = "";
      if(sentence.isEmpty())
      {
        System.out.println("Empty String");
      }
  }
}

Output - Empty String    

Code for converting a Character Array to a String


  public class javalabclass 
{
  public static void main(String args[])
    {
      char a[] = {'S','A','T','I','S','H'};
      String name = new String(a);
      System.out.println(name);
  }
}

Output: SATISH   

Code for converting a String to a Character Array


  public class javalabclass 
{
  public static void main(String args[])
    {
    String name="Satish";
    char c[] = name.toCharArray();
    for(char t: c)
    {
      System.out.print(t);
    }
  }
}

Output : S a t i s h   

Code for searching a String using contains Method


  public class javalabclass 
{
  public static void main(String args[])
    {
    String sentence = "Satish teaches Java";
    System.out.println(sentence.contains("ish"));
  }
}

Output - true (ish is present in the string hence true is returned. If no
match found then false will be returned)   

Code for splitting a String using delimiters


  public class javalabclass 
{
  public static void main(String args[])
    {
    String sentence = "Satish teaches Java";
    String[] result = sentence.split(" ");
    for(String k:result)
    {
      System.out.println(k);
    }
    
  }
}
Output:  
Satish
teaches
Java   

Determine the number of times a given substring exists in the string sasatsasatatsatsatatatsattttassaasatt. Get the substring as input from the user
  • if the user enters "sat" then the number of times sat occurs should be displayed as 6 times.
  • If the user enters the substring "as" then the number times "as" occurs should be displayed as 4 times
  • if the user enters a substring that is not part of the given string then the output should "No such substring in the given string"


  import java.util.Scanner;
public class javalabclass 
{
  public static void main(String args[])
    {
    String test = "sasatsasatatsatsatatatsattttassaasatt";
    System.out.println("Enter the substring");
		Scanner input = new Scanner(System.in);
		String sub = input.next();
    boolean found=false;
    int count=0;
    for(int i=0;i <=test.length()-sub.length();i++)
    {
      if(test.substring(i,i+sub.length()).equals(sub))
      {
        count++;
        found=true;
      }
    }
    if(found)
    {
          System.out.println("The substring occurs "+ count+" times");
    }
    else
    {
      System.out.println("No such substring in the given string");
    }
  }
}

output:
Enter the substring
sas
The substring occurs 2 times   

Create an array name[] and store the following names in the array by initializing it
Satish,Ram,Mathew
Display the output from the array using an enhanced for loop


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
    	//Array of Strings
    	String name[] = {"Satish","Ram","Mathew"};
    	for(String sample : name)
    	{
    		System.out.println(sample);
    	}
    }
}   

Create an array name[] .Store three names in the array by getting the user input. Display the array contents using an enhanced for loop


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
    	//Array of Strings
    	String name[] = new String[3];
    	Scanner obj = new Scanner(System.in);
    	for(int i=0;i<name.length;i++)
    	{
    		System.out.println("Enter the name");
    		name[i]=obj.nextLine();
    	}
    	for(String sample : name)
    	{
    		System.out.println(sample);
    	}

    }
}
   

Create a multidimensional array of strings and initialize it with the following values
vellore 632006
chennai 60025
Display the contents of the array using an enhanced for loop


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
    	  String country[][] = {{"vellore","632006"},{"chennai","600025"}};
       	  for(String[] k:country)
    	  {
    		  for(String m:k)
    		  {
    			  System.out.print(m+" ");
    		  }
    		  System.out.println();
    	  }
    	
    }
}
   

Read input for a multidimensional array from the user. The array should store two rows and two columns of data(strings). Display the output to the user using an enhanced for loop


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
    	  String country[][] = new String[2][2];
    	  System.out.println("Enter the district and zipcode");
    	  Scanner obj = new Scanner(System.in);
    	  for(int i=0;i<country.length;i++)
    	  {
    		  for(int j=0;j<country[i].length;j++)
    		  {
    			  country[i][j]=obj.nextLine();
    		  }
    	  }
    	  for(String[] k:country)
    	  {
    		  for(String m:k)
    		  {
    			  System.out.print(m+" ");
    		  }
    		  System.out.println();
    	  }
    	
    }
}
   

Read input for a multidimensional array from the user. The array should store two rows and two columns of data(strings) as shown below vellore 632006
chennai 60025
Get the district as input from the user. Display the corresponding zip code for the district. If the district is not available in the array then display


  package testProject;
import java.util.Scanner;
public class testProject {
	public static void main(String[] args) {		
		 String country[][] = new String[2][2];
    	  System.out.println("Enter the district and zipcode");
    	   Scanner obj = new Scanner(System.in);
    	  for(int i=0;i<country.length;i++)
    	  {
    		  for(int j=0;j<country[i].length;j++)
    		  {
    			  country[i][j]=obj.nextLine();
    		  }
    	  }
    	  System.out.println("Enter the district to search");
    	  String search = obj.nextLine();
    	  boolean found=false;
    	  for(String[] k:country)
    	  {
    		  for(String m:k)
    		  {
    			  if(found)
    			  {
    				  System.out.println(m);
    				  break;
    			  }
    			  if(m.equals(search))
    			  {
    				  found=true;
    				  continue;
    				  
    			  }
    		  }
    		  //System.out.println();
    		  if(found)
    		  {
    			  break;
    		  }
    	  }	
    	  if(!found)
    	  {
    		  System.out.println("No such district in the array");
    	  }
	}
	
}

output (for a valid district) 
Enter the district and zipcode
vellore
632006
chennai
600025
Enter the district to search
vellore
632006

output(for an invalid district)
Enter the district and zipcode
vellore
632006
chennai
600025
Enter the district to search
test
No such district in the array   

Get the Registration Number and CourseName as Strings for each student. A student will enter his registration number and registered course name as input. Consider three students for the exercise. Display the registration number and course name for every student from the array Output Expected:
Enter the Regnumber
111
Enter the course Name
DBMS
Enter the Regnumber
111
Enter the course Name
Java
Enter the Regnumber
112
Enter the course Name
DBMS
The Registration Number and course Name is given below
111
DBMS
111
Java
112
DBMS


  import java.util.Scanner;
public class javalabclass 
{
  public static void main(String args[])
    {
    String courseReg[][] = new String[3][2];
    Scanner input = new Scanner(System.in);

    for(int i=0;i<courseReg.length;i++)
    {
      for(int j=0;j<courseReg[i].length;j++)
      {
        if(j==0)
        {
        System.out.println("Enter the Regnumber");
        courseReg[i][j]=input.next();
        }
        if(j==1)
        {
          System.out.println("Enter the course Name");
          courseReg[i][j]=input.next();
        }
      }
    }
    System.out.println("The Registration Number and course Name is given below");
    for(String k[]:courseReg)
    {
      for(String a:k)
      {
        System.out.println(a);
      }
    }
  }
}

output:
Enter the Regnumber
111
Enter the course Name
java
Enter the Regnumber
112
Enter the course Name
dbms
Enter the Regnumber
111
Enter the course Name
os
The Registration Number and course Name is given below
111
java
112
dbms
111
os   

Read the registration numbers of students and display the number of students who are from scope and site school . Students from SCOPE will have the registration numbers as XXBCEXXXX as the format and SITE School will have XXBITXXXX where X can be any character.


  import java.util.Scanner;
public class javalabclass {

  public static void main(String[] args) {
  
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the number of students:");
    int numStudents=sc.nextInt();
    String students[]=new String[10];
    int scopeStudents=0;
    int siteStudents=0;
    System.out.println("Enter the students registration number:");
    for(int i=0;i < numStudents;i++)
    {
        students[i]=sc.next();
        if(students[i].charAt(2)=='B' && students[i].charAt(3)=='C'&& students[i].charAt(4)=='E')
        {
            scopeStudents++;
        }
        else if(students[i].charAt(2)=='B' && students[i].charAt(3)=='I' && students[i].charAt(4)=='T')
        {
            siteStudents++;
        }
    }
    System.out.println("The number of Scope Students is: "+scopeStudents);
    System.out.println("The number of Site students is: "+siteStudents);
}
}

output:
Enter the number of students:
3
Enter the students registration number:
12BIT1111
12BCE2222
12BME2333
The number of Scope Students is: 1
The number of Site students is: 1   

Read the names of 10 cities and display the cities in the alphabetical order.


  import java.util.Scanner;
public class javalabclass {

public static void main(String[] args) {

  Scanner sc=new Scanner(System.in);
  String cities[]=new String[10];
  System.out.println("Enter the city name:");
  for(int i=0;i < 10;i++)
  {
      cities[i]=sc.next();
  }
  for(int i=0;i <  9;i++)
  {
      for(int j=i+1;j <  10;j++)
      {
          if(cities[j].compareTo(cities[i]) <  0)
          {
              String temp=cities[i];
              cities[i]=cities[j];
              cities[j]=temp;
          }
      }
  }
  System.out.println("City in alphabetical order:");
  for(int i=0;i <  10;i++)
  {
      System.out.println(cities[i]);
  }
}
}

Output:
Enter the city name:
Delhi
Vellore
Chennai
Mumbai
Pune
Jaipur
Bengaluru
Trivandrum
Amritsar
Hyderabad
City in alphabetical order:
Amritsar
Bengaluru
Chennai
Delhi
Hyderabad
Jaipur
Mumbai
Pune
Trivandrum
Vellore   

Count the number of times a word occurs in a sentence


  package javaprogrammingdemo;
public class javalabclass{
    public static void main(String args[]) 
    {
    	String sentence = "hello hello hi hello hi";
    	String words[] = sentence.split(" ");
    	boolean first_flag = true;
    	boolean found=false;
    	int count=0;
    	String wordstore[][]=new String[100][100];
    	int lastrow=0,lastcol=0;
    	
    		wordstore[0][0]=words[0];
    		count++;
    		wordstore[0][1]=Integer.toString(count);
     
    		for(int i=1;i<words.length;i++)
    		{
    			found=false;
    			for(int j=0;j<wordstore.length;j++)
    			{  
    				
	    			 if(wordstore[j][0]!=null)
	    			 {
		    			 if(wordstore[j][0].equals(words[i]))
		    			  {
		    				count = Integer.parseInt(wordstore[j][1]);
		    				count++;
		    				wordstore[j][1]=Integer.toString(count);
		    				found=true;
		    			  }
    			     }
    		     }
    			 if(found==false)
    			 {
    				 lastrow++;
    				 wordstore[lastrow][0]=words[i];
    				 wordstore[lastrow][1]=Integer.toString(1);
    			 }
    		}
    		for(String[] m:wordstore)
    		{
    			for(String t:m)
    			{
    				if(t!=null)
    				{
    				 System.out.println(t);
    				}
    			}
    		}
    			
    	}
}

output
hello
3
hi
2   

Get a sentence from the user.
a) Get the string the user wants to search from the sentence. Display the number of times the string occurs in the sentence.
b) Get the string to find and replace from the sentence. Display the sentence by replacing the string to the user.
For instance if the user enters "Learning Java is easy as all programs in java is not difficult" .If he wishes to replace java with python the output should be "Learning python is easy as all programs in python is not difficult."


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
    	   System.out.println("Enter the sentence");
 	       Scanner obj = new Scanner(System.in);
    	   String s = obj.nextLine();
    	   String words[] = s.split(" ");
    	   //count the number of times a word occurs in the sentence 
    	   boolean found=false;
    	   System.out.println("Enter the words to search for");
    	   String search = obj.nextLine();
    	   int count=0;
    	   for(String m: words)
    	   {
    		   if(search.equals(m))
    		   {
    			   count++;
    			   found = true;
    		   }
    	   }
    	   if(found==false)
    	   {
    		   System.out.println("The string not found in the sentence");
    	   }
    	   else
    	   {
    		  System.out.println("The number of times the word occurs is "+count);
    	   }
    	   boolean foundreplace=false;
    	   System.out.println("Enter the string to find");
    	   String find = obj.nextLine();
    	   System.out.println("Enter the string to replace");
    	   String repl = obj.nextLine();
    	   for(String m: words)
    	   {
    		   if(m.endsWith(find))
    		   {
    			   System.out.print(repl+" ");
    			   foundreplace=true;
    		   }
    		   else
    		   {
    			   System.out.print(m+" ");
    		   }
    	   }
    	   System.out.println();
    	   if(foundreplace==false)
    	   {
    		   System.out.println("Didnt find the string so displayed the original sentence without replacement");
    	   }
    	}
}

Output
Enter the sentence
java learning is easy for java learners
Enter the words to search for
java
The number of times the word occurs is 2
Enter the string to find
java
Enter the string to replace
python
python learning is easy for python learners