Java Strings


1. What are the differences between == and equals() in a String class?

The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal).

String s1 = "Program";
String s2 = "Program";
String s3 = new string ("Program");
if(s1 == s2) { //true
System.out.println("equal");
}

if(sl == s3) { //false
System.out.println("equal");
}


2. What are the differences between StringBuffer and StringBuilder?

StringBuilder is not synchronized where as StringBuffer is synchronized. StringBuilder is faster than StringBuffer. So unless we are using strings multiple threads, it is better to use stringbuffer.


3. What is string pool in Java?

Java maintains a pool of string literals called string pool.

JVM stores only one copy of each literal String in a pool. This process is called interning.

When we create a String variable and assign a value to it, the JVM searches the pool for a String of equal value.

If found, the Java compiler will simply return a reference to its memory address, without allocating additional memory.

If not found, it'll be added to the pool (interned) and its reference will be returned.


4. Write a program to find the square of a number given as command line argument.

public class StringTest {
    public static void main(String args[]){
         int n = Integer.parseInt(args[0]);
         System.out.println("the square is "+n*n);
    }
}

The method Integer.parseInt() parses the string and returns the integer stored in the string.

You can also use the method

Integer.valueOf(str)

Integer n = Integer.valueOf(args[0]);
int m= n.intValue();


5. Write a function to reverse a string.

static String reverString(String str){
        int l = str.length();
        char arr[] = str.toCharArray();
        for(int i=0,j=l-1;i<j;i++,j--) {
            char temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        String str2 = new String(arr);
        return str2;
    }

The function converts the string to character array. And then it swaps characters from two ends of the string.

After all characters are swapped, a string is formed using these characters again.

Please note that the loop should continue only for half the lenght - or until i becomes j.


6. What is the output of the following code?

String str = "Hello"
int l=str.length();
for(int i=1;i<=l;i++){
     System.out.println(str.substring(0,i);

H
He
Hel
Hell
Hello

The substring function returns the substring

In the loop, the program prints 1 character , followed 2 characters etc. So the program prints a pyramid.


7. Write a program to remove all the characters 'a' from the given string.

import java.util.Scanner;

public class StringTest {
    static String removeAs(String str){
        String str1 = str.replace("a","");
        str1 = str1.replace("A","");
        return str1;
    }
    public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        str = removeAs(str);
        System.out.println("The string after removing \'a\' "+str);
    }
}

8. Write a program to find if a given string is a palindrome.

import java.util.Scanner;
public class StringTest {   

    boolean isPalindrome(String str){
        int l = str.length();
        for(int i=0,j=l-1;i<j;i++,j--){
            char ch = str.charAt(i);
            char ch2 = str.charAt(j);
            if(ch!=ch2)
                return false;
        }
        return true;
    }
    public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        StringTest obj = new StringTest(); 
        if(obj.isPalindrome(str))
            System.out.println(str+" is a palindrome");
        else
            System.out.println(str+" is not a palindrome");
       
    }
}
A palindrome is a string which reads the same both forwards and backwards.

We are testing 0th character with last character. If they are not matching then we return false - because it will not be palindrome. Next we check first character with last but first character. We continue this process till we reach the middle of the string. If all the characters match with the characters from other end, then the string is a palindrome.


9. Write a function to print the words of string in reverse order.

  void printWordsReverse(String str){
        String arr[] = str.split(" ");
        int l = arr.length;
        for(int i=l-1;i>=0;i--)
            System.out.print(arr[i]+" ");
    }

split() method splits the string into an array of strings dividing at the character given.

In the function, we are dividing the string at spaces which is the word separator. So we get an array of word of the string. Next we print this array in reverse order.


10. Write a program to read a string and find out whether it contains the word program in it- ignoring the case of letters while searching.

class Demo{ 
public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        String testString = "program";
        str = str.toLowerCase();
        if(str.contains(testString)/*str.indexOf(testString)==-1*/){
            System.out.println(str+"  contains the word "+testString);
        }else{
            System.out.println(str+" does not contain the word "+testString);

        }
}

We are converting the string to lower case and searching for the string in lower case, so that the search will ignore case.

It is also possible to use the method indexOf

if (str.indexOf(testString)==-1)
//not found


11. Write a program to read a string and determine if these strings are anagrams. Anagrams are strings which contain same set of characters. e.g. this is us us si isth

import java.util.HashMap;
import java.util.Scanner;
public class Anagram {

    static boolean isAnagram2(String s1,String s2){
        if(s1.length()!=s2.length())
            return false;
        HashMap<Character,Integer> chMap = new HashMap<Character,Integer>();
        char[]arr = s1.toCharArray();
        for(char ch:arr){
            if(chMap.containsKey(ch)){
                int count = chMap.get(ch);
                chMap.replace(ch,count+1);
            }else
                chMap.put(ch,1);
        }
        char[]arr2 = s2.toCharArray();
        for(char ch:arr2){
            if(chMap.containsKey(ch)){
                int count = chMap.get(ch);
                if(count==1){
                    chMap.remove(ch);
                }else {
                    chMap.replace(ch, count - 1);
                }

            }else
                return false;
        }
        if(chMap.size()==0)
            return true;
        else
            return false;
    }
    static boolean isAnagram(String s1,String s2){
        if(s1.length()!=s2.length())
            return false;
        for(char ch:s1.toCharArray()){             
            s2 =s2.replaceFirst(new String(new char[]{ch}),"");
        }
        if(s2.isEmpty())
            return true;
        else
            return false;
    }
    public static void  main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str1 = scanner.nextLine();
        String str2 = scanner.nextLine();
        boolean isAn = isAnagram2(str1,str2);
        if(isAn)
            System.out.println("Strings "+str1+" and "+str2+" are anagrams");
        else
            System.out.println("Strings "+str1+" and "+str2+"are not anagrams");

    }
}

First method isAnagram does not use extra data structures. It takes each character from first string and removes it from second string. At the end of loop, second string should be empty if they are anagrams. The complexity is O(m*n)

Second method uses a hashmap to store count of each charactes from first string. Then iterating over second string, count of each character is decremented. If the count is zero, the entry is removed. At the end of loop, all the entries in hashmap must have been removed if both strings contain same set of characters. This method has a complexity of O(m+n) where m and n are sizes of first and second string.


12. Write a program to read a string and reverse each word of a string. e.g. hello, welcome to Java programming output should be olleh, emoclew ot avaJ gnimmargorp

import java.util.Scanner;

public class ReverseWords {
    String reverseWords(String str){
        String arr[] = str.split("[ \n\t]");
        for(String st:arr){
            String st2 = reverString(st);
            str = str.replaceFirst(st,st2);
        }
        return str;
    }
  String reverString(String str){
        int l = str.length();
        char arr[] = str.toCharArray();
        for(int i=0,j=l-1;i<j;i++,j--) {
            char temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        String str2 = new String(arr);
        return str2;
    }
    public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        ReverseWords obj = new ReverseWords();
        String outStr = obj.reverseWords(str);
        System.out.println(outStr);
    }

13. Write a program to read a string and convert first letter of each word into upper case. e.g. If the sentence is Java is an object oriented language the output should be Java Is An Object Oriented Language.

import java.util.Scanner;

public class ReverseWords {
    String capitalizeFirstLetter(String st){
        char ch = st.charAt(0);
        ch = Character.toUpperCase(ch);
        String outStr = ch+st.substring(1);
        return outStr;
    }
    String wordCapitalize(String str){
        String arr[] = str.split("[ \n\t]");
        for(String st:arr){
            String st2 = capitalizeFirstLetter(st);
            str = str.replaceFirst(st,st2);
        }
        return str;
    }
    public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        ReverseWords obj = new ReverseWords();
        String outStr = obj.wordCapitalize(str);
        System.out.println(outStr);
    }
}

14. Write a program to print the count of each character in a given string.

  
import java.util.HashMap;
import java.util.Scanner;

public class Abc {
    public void printCount(String str){
        char []arr = str.toCharArray();
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(char ch:arr){
            if(map.containsKey(ch)){
                map.replace(ch,map.get(ch)+1);
            }else{
                map.put(ch,1);
            }
        }
        int s = map.size();
        for(char ch:map.keySet()){
            int count = map.get(ch);
            System.out.println(ch+":"+count);
        }
    }
    public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        Abc obj = new Abc();
        System.out.println("The count of characters in the string are :");
        obj.printCount(str);
    }
}

We use a hashmap to store count of each charactes from string.


15. Write a program to find the first non-repeated character in a given string.

import java.util.HashMap;
import java.util.Scanner;

public class NonRepeating {
    char firstNonRepeating(String str){
        char [] arr = str.toCharArray();
        HashMap<Character,Integer> map = new HashMap<>();
        for (char ch :arr){/*create a map of characters and frequencies*/
            if(map.containsKey(ch)){
                int count = map.get(ch);
                map.replace(ch,count,count+1);
            }else{
                map.put(ch,1);
            }
        }
        for(char ch:arr){
            int frequency = map.get(ch);
            if(frequency==1)
                return ch;
        }
        return (char) -1;
    }
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the string:");
        String str = scanner.nextLine();
        NonRepeating obj = new NonRepeating();
        char nonRepChr = obj.firstNonRepeating(str);
        if((int)nonRepChr!=-1)
            System.out.println("The first non-repeating character is "+nonRepChr);
        else
            System.out.println("There are no such characters");
    }
}

16. How do you check if the first string contains the second string?

There are two String methods which allow you to perform this operation.

1) indexOf() method

string1.indexOf(string2) returns the index of second string in first string. If first string does not contain second string, the method returns -1

e.g
String s1 = "Helloworld";
String s2 = "world";
int i1 = s1.indexOf(s2);/* returns 5*/
int i2 = s1.indexOf("Java");/*returns -1*/

2) contains() method
This method returns true if the first string contains second string and false otherwise

boolean b = s1.contains(s2);//true
b = s1.contains("program");//false


17. How do you find if the string contains only digits?

import java.util.Scanner;

public class OnlyDigits {
public static void main(String args[]) {
System.out.println("Enter a string:");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
boolean onlyDigits = str.matches("\\d+");
if(onlyDigits==true)
System.out.println("The string contains only digits");
else
System.out.println("no");
}
}

The regular expression \\d+ matches the string for 1 or more digits. If the string has other characters, then the method returns false.


18. Write a recursive function to reverse a string.

 String reverseString(String s){
        if(!s.isEmpty()){
            return  reverseString(s.substring(1))+s.substring(0,1);
        }else
            return "";
    }

Here we are taking substring from 2 character to end of string and adding the first character to the end of it. This is done recursively. 

19. Write a program to search for a value in an array using binary search.

import java.util.Scanner;

public class BinSearch {
    static boolean binSearch(int searchVal,int [] arr,int start,int end){
        if(start>end)
            return false;
        int mid = (start+end)/2;
        if(arr[mid]==searchVal)
            return true;
        else if(arr[mid]>searchVal){
            return binSearch(searchVal,arr,start,mid-1);
        }else{
            return binSearch(searchVal,arr,mid+1,end);
        }

    }
    public static void main(String args[]){
        int len;
        System.out.println("Enter the size of the array");
        Scanner scanner = new Scanner(System.in);
        len = scanner.nextInt();
        int arr[] = new int[len];
        for(int i=0;i<len;i++){
            System.out.println("arr["+i+"]=");
            arr[i] = scanner.nextInt();
        }
        System.out.println("Enter value to be searched:");
        int sv = scanner.nextInt();
        boolean found = binSearch(sv,arr,0,len-1);
        if(found){
            System.out.println("the value is found in array");
        }else{
            System.out.println("the value is not found in array");
        }

    }
}

Remember that binary search works only with sorted arrays.

And for an array of size n, the maximum number of iterations is log(n), So its complexity is O(logn)


20. Write a program to convert a string to a integer using the following rules. 1) discard all the leading spaces 2) the string may optionally contain leading sign character -12 +998 are valid 3) After these, if the next character is not a digit, then the return value must be 0 4) If there are alphabets or other characters after digits, the conversion should stop. e.g. -12ab89 = -12 ab129 = 0 890jkl = 890

import java.util.Scanner;

public class Atoi {
    int stringToInteger(String str){
        str = str.trim();
        char arr[] = str.toCharArray();
        int len = arr.length;
        int sum = 0;
        boolean isNegative = false;
        int i=0;
         if(arr[0]=='-' ){
            isNegative = true;i++;
        }else if(arr[0]=='+'){
            i++;
        }
        for(;i<len;i++){
            if(!Character.isDigit(arr[i])){
                break;/* we have a non-digit. stop conversion*/
            }
            sum = sum*10+(arr[i]-48);/*unicode value of 0 is 48*/
        }
        if(isNegative)
            return -1*sum;
        return sum;
    }
    public static void main(String args[]){
        String str;
        System.out.println("Enter a string");
        Scanner scanner = new Scanner(System.in);
        str = scanner.nextLine();
        Atoi obj = new Atoi();
        System.out.println("THe number is "+obj.stringToInteger(str));
    }
}

21. What is string pool in Java?


It is a special region in memory where all string constants are stored.

The JVM stores only one copy of a particular String in the pool
When creating a new String, the JVM searches in the pool for a String having the same value
If found, the JVM returns the reference to that String without allocating any additional memory
If not found, then the JVM adds it to the pool (interns it) and returns its reference