Top 15 most asked interview question and programs on JAVA String

Top 15 most asked interview question and programs on JAVA String


1. Is String a primitive type or derived type?

Answer: String is a derived type.

2. In how many ways you can create string objects in java?

Top 15 most asked interview question and programs on JAVA String


3. What do you mean by mutable and immutable objects?

Top 15 most asked interview question and programs on JAVA String


4. What is the difference between String, StringBuffer and StringBuilder?

Top 15 most asked interview question and programs on JAVA String


5. Which one will you prefer among “==” and equals() method to compare two string objects?

Top 15 most asked interview question and programs on JAVA String


6. WAP to count the number of occurrences of each character in a string?

class EachCharCountInString
{
	static void characterCount(String inputString)
	{
		//Creating a HashMap containing char as a key and occurrences as  a value

		HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();

		//Converting given string to char array

        char[] strArray = inputString.toCharArray();

        //checking each char of strArray

        for (char c : strArray)
        {
			if(charCountMap.containsKey(c))
			{
				//If char is present in charCountMap, incrementing it's count by 1

				charCountMap.put(c, charCountMap.get(c)+1);
			}
			else
			{
				//If char is not present in charCountMap,
				//putting this char to charCountMap with 1 as it's value

				charCountMap.put(c, 1);
			}
		}

        //Printing the charCountMap

        System.out.println(charCountMap);
	}

    public static void main(String[] args)
    {
       characterCount("Java J2EE Java JSP J2EE");

       characterCount("All Is Well");

       characterCount("Done And Gone");
    }
}

7. WAP remove all white spaces from a string in java?

class RemoveWhiteSpaces
{
	public static void main(String[] args)
	{
		String str = "  Core Java jsp servlets 			jdbc struts hibernate spring  ";

		//1. Using replaceAll() Method

		String strWithoutSpace = str.replaceAll("\\s", "");

		System.out.println(strWithoutSpace);         //Output : CoreJavajspservletsjdbcstrutshibernatespring

		//2. Without Using replaceAll() Method

		char[] strArray = str.toCharArray();

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < strArray.length; i++)
		{
			if( (strArray[i] != ' ') && (strArray[i] != '\t') )
			{
				sb.append(strArray[i]);
			}
		}

		System.out.println(sb);           //Output : CoreJavajspservletsjdbcstrutshibernatespring
	}
}

8. WAP to find duplicate characters in a string?

import java.util.HashMap;
import java.util.Set;

class DuplicateCharactersInString
{
	static void duplicateCharCount(String inputString)
	{
		//Creating a HashMap containing char as key and it's occurrences as value

		HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();

		//Converting given string to char array

        char[] strArray = inputString.toCharArray();

        //checking each char of strArray

        for (char c : strArray)
        {
			if(charCountMap.containsKey(c))
			{
				//If char is present in charCountMap, incrementing it's count by 1

				charCountMap.put(c, charCountMap.get(c)+1);
			}
			else
			{
				//If char is not present in charCountMap,
				//putting this char to charCountMap with 1 as it's value

				charCountMap.put(c, 1);
			}
		}

        //Getting a Set containing all keys of charCountMap

        Set<Character> charsInString = charCountMap.keySet();

        System.out.println("Duplicate Characters In "+inputString);

        //Iterating through Set 'charsInString'

        for (Character ch : charsInString)
        {
			if(charCountMap.get(ch) > 1)
			{
				//If any char has a count of more than 1, printing it's count

				System.out.println(ch +" : "+ charCountMap.get(ch));
			}
		}
	}

    public static void main(String[] args)
    {
       duplicateCharCount("JavaJ2EE");

       duplicateCharCount("Fresh Fish");

       duplicateCharCount("Better Butter");
    }
}

9. Write a java program to reverse each word of a given string?

Using iterative method

String str = "MyJava";

char[] strArray = str.toCharArray();

for (int i = strArray.length - 1; i >= 0; i--)
{
	System.out.print(strArray[i]);     //Output : avaJyM
}

Using StringBuffer class

StringBuffer sbf = new StringBuffer("MyJava");
System.out.println(sbf.reverse());    //Output : avaJyM

10. Write a code to check whether one string is a rotation of another?

public class MainClass
{
	public static void main(String[] args)
	{
		String s1 = "JavaJ2eeStrutsHibernate";

		String s2 = "StrutsHibernateJavaJ2ee";

		//Step 1

		if(s1.length() != s2.length())
		{
			System.out.println("s2 is not rotated version of s1");
		}
		else
		{
			//Step 2

			String s3 = s1 + s1;

			//Step 3

			if(s3.contains(s2))
			{
				System.out.println("s2 is a rotated version of s1");
			}
			else
			{
				System.out.println("s2 is not rotated version of s1");
			}
		}
	}
}

 

  1. Write a code to prove that strings are immutable in java?
public class StringExamples
{
	public static void main(String[] args)
	{
		String s1 = "JAVA";

		String s2 = "JAVA";

		System.out.println(s1 == s2);         //Output : true

		s1 = s1 + "J2EE";

		System.out.println(s1 == s2);         //Output : false
	}
}

11. How do you convert string to integer and integer to string in java?

Convert String to Integer:

public class StringToInteger
{
	public static void main(String[] args) 
	{
		String s = "2015";
		
		int i = Integer.parseInt(s);
		
		System.out.println(i);          //Output : 2015
	}
}

Convert Integer to String:

public class IntegerToString
{
	public static void main(String[] args) 
	{
		int i = 2015;
		
		String s = Integer.toString(i);
		
		System.out.println(s);     //Output : 2015
	}
}

12. Write a java program to reverse a given string with preserving the position of spaces?

Input: “I Am Not String”  and Output:  “g ni rtS toNmAI”

public class MainClass
{	
	static void reverseString(String inputString)
	{
		//Converting inputString to char array 'inputStringArray'
		
		char[] inputStringArray = inputString.toCharArray();
		
		//Defining a new char array 'resultArray' with same size as inputStringArray
		
		char[] resultArray = new char[inputStringArray.length];
		
		//First for loop : 
		//For every space in the 'inputStringArray', 
		//we insert spaces in the 'resultArray' at the corresponding positions 
		
		for (int i = 0; i < inputStringArray.length; i++) 
		{
			if (inputStringArray[i] == ' ') 
			{
				resultArray[i] = ' ';
			}
		}
		
		//Initializing 'j' with length of resultArray
		
		int j = resultArray.length-1;
				
		//Second for loop :
		//we copy every non-space character of inputStringArray 
		//from first to last at 'j' position of resultArray
		
		for (int i = 0; i < inputStringArray.length; i++)
		{
			if (inputStringArray[i] != ' ') 
			{
				//If resultArray already has space at index j then decrementing 'j'
				
				if(resultArray[j] == ' ')
				{
					j--;
				}
				
				resultArray[j] = inputStringArray[i];
				
				j--;
			}
		}
		
		System.out.println(inputString+" ---> "+String.valueOf(resultArray));
	}
	
	public static void main(String[] args)
	{
		reverseString("I Am Not String");
		
		reverseString("JAVA JSP ANDROID");
		
		reverseString("1 22 333 4444 55555");
	}
}

13. Write a java program to check whether two strings are anagram or not?

Two strings are called anagrams if they contain same set of characters but in different order. For example, “Dormitory – Dirty Room”“keep – peek”,  “School Master – The Classroom”are some anagrams.

public class AnagramProgram
{
	static void isAnagram(String s1, String s2)
	{
		//Removing all white spaces from s1 and s2

		String copyOfs1 = s1.replaceAll("\\s", "");

		String copyOfs2 = s2.replaceAll("\\s", "");

		//Initially setting status as true

		boolean status = true;

		if(copyOfs1.length() != copyOfs2.length())
		{
			//Setting status as false if copyOfs1 and copyOfs2 doesn't have same length

			status = false;
		}
		else
		{
			//Changing the case of characters of both copyOfs1 and copyOfs2 and converting them to char array

			char[] s1Array = copyOfs1.toLowerCase().toCharArray();

			char[] s2Array = copyOfs2.toLowerCase().toCharArray();

			//Sorting both s1Array and s2Array

			Arrays.sort(s1Array);

			Arrays.sort(s2Array);

			//Checking whether s1Array and s2Array are equal

			status = Arrays.equals(s1Array, s2Array);
		}

		//Output

		if(status)
		{
			System.out.println(s1+" and "+s2+" are anagrams");
		}
		else
		{
			System.out.println(s1+" and "+s2+" are not anagrams");
		}
	}

	public static void main(String[] args)
	{
		isAnagram("Mother In Law", "Hitler Woman");

		isAnagram("keEp", "peeK");

		isAnagram("SiLeNt CAT", "LisTen AcT");

		isAnagram("Debit Card", "Bad Credit");

		isAnagram("School MASTER", "The ClassROOM");

		isAnagram("DORMITORY", "Dirty Room");

		isAnagram("ASTRONOMERS", "NO MORE STARS");

		isAnagram("Toss", "Shot");

		isAnagram("joy", "enjoy");
	}
}

Output:

Mother In Law and Hitler Woman are anagrams
keEp and peeK are anagrams
SiLeNt CAT and LisTen AcT are anagrams
Debit Card and Bad Credit are anagrams
School MASTER and The ClassROOM are anagrams
DORMITORY and Dirty Room are anagrams
ASTRONOMERS and NO MORE STARS are anagrams
Toss and Shot are not anagrams
joy and enjoy are not anagrams


15. Can we call String class methods using string literals?

Top 15 most asked interview question and programs on JAVA String

Leave a Reply