FAQ-JAVA Interview Questions on Strings

   

JAVA Interview Questions for freshers on Strings 

String and Array concepts in Java

A programming interview will be incomplete without a question from Strings.

A String is nothing but a group of characters. Normally we represent String as a character Array. 

Java has an advantage in Strings. It gives a Nice String Class which wraps over the character Array giving a nice set of features and an easier interface to work with.

A direct way to declare a String is as String greeting = "Hello world!";

Similar to arrays, there can be concept wise or problem solving questions that can be asked on this topic

JAVA interview questions on Strings 

Following are few examples of questions that are frequently asked in interviews

1. String operations

Multiple choice questions , where output of a code sample can be asked mostly involves questions on string operations like concatenation, reversing, sub-string calculation etc.

Ex:

What is the output of this expression

"Was it a car or a cat I saw?".sub-string(9, 12)

Sub-string of the above string starts from 9th character starting from 0 and ends at character 12, including spaces . i.e starts with c and ends with r. Therefore, the output will be car.

2. Reverse a string without using builtin functions.

  • This is very simple when we use the builtin function .reverse provided by strings
  • The below example explains how the same can be done without using built in reverse function.
  • The logic is to Initiate an empty String “”. While iterating the input String from the back ,Construct the output reversed,with  char by char concatenation using operator +

public static void main(String a[]){

        String original, reverse = "";

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a string ");

        original = sc.nextLine();

        int length = original.length();

        for ( int i = length - 1; i >= 0; i-- )

            reverse = reverse + original.charAt(i);

        System.out.println("reversed string "+reverse);

    }

 

Output:

Enter a string 

matrix

reversed string xirtam

3. Check if a given string is palindrome without using built in reverse function

  • This program can be asked as an extension to above program, From the above we have already seen how to reverse a string
  • Using .equals method by the String class we check if the String and the reversed String are equal.

       public static void main(String a[]){

String original, reverse = "";

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string ");

original = sc.nextLine();

int length = original.length();

for ( int i = length - 1; i >= 0; i-- )

reverse = reverse + original.charAt(i);

if (original.equals(reverse))

System.out.println("palindrome");

else

System.out.println(" not a palindrome.");

}

 

output:

Enter a string to check if it is a palindrome

madam

Entered string is a palindrome.

4. Why is string called as immutable?

String is immutable in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. There are many advantages of immutable classes.

  • Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

5. How to find duplicate characters in a string and the number of occurences of each

This is also a very popular coding question on the various level of Java interviews and written test, where you need to write code. On difficulty level, this question is at par with palindrome string.

Though we have discussed a simialr question on arrays,using nested loops. doing it on string also works the same way when we treat string as an array of characters(letters). 

But we will see another model where we use Map/HashMap to find the duplicates.

This model will also allow you to get familiar with the concept of Map data structure, which allows you store mappings in the form of key and value.

Here is how the code looks like:(we are using combination as direct input, same can be replced with reading string from console.)

public static void main(String args[])

printDuplicateCharacters("Combination");

public static void printDuplicateCharacters(String str) 

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

char[] charsArray = str.toCharArray();

for(int i=0;i<charsArray.length;i++){

char ch=charsArray[i];

if(Duplicates.containsKey(ch)){

System.out.println("Duplicate character "+ch);

Duplicates.put(ch, Duplicates.get(ch)+1);

} else {

Duplicates.put(ch, 1);

}

}

System.out.println("occurences of each duplciate charcater:");

Set<Character> keys = Duplicates.keySet();

for(Character ch:keys){

if(Duplicates.get(ch) > 1){

System.out.println(ch+"--->"+Duplicates.get(ch));

}

}

The idea here is simple. While adding each character of the string to a hashmap,If the hash map already have any character of the string we simply consider it as duplicate. 

Hashmap we used is of type <Character, Integer> which means the key of the map is a character and the value is an integer, that strores the count

the output for above program which is finding duplicates for the string “combination”  looks like:

Duplicate character i

Duplicate character o

Duplicate character n

occurences of each duplciate charcater:

n--->2

o--->2

i--->2

We use a second data structure set, just to print the stored count of each character. If the question is just to find the duplicates, then we can just avoid the second part.

6. Count the number of vowels and consonants in a string

A simple basic level question which can be solved using the concept of character comparison. 

The code for the program looks like below:

public static void main(String[] args) {

       String input = "This is a test string";

       int vowels = 0, consonants = 0;

       input = input.toLowerCase();

       for(int i = 0; i < input.length(); ++i)

       {

           char ch = input.charAt(i);

           if(ch == 'a' || ch == 'e' || ch == 'i'

               || ch == 'o' || ch == 'u') {

               ++vowels;

           }

           else if((ch >= 'a'&& ch <= 'z')) {

               ++consonants;

           }

       }

       System.out.println("Vowels: " + vowels);

       System.out.println("Consonants: " + consonants);

       }

 

The logic here is very simple. We first convert the string to lowercase to avoid comparison twice for uppercase and lowercase letters. We iterate through each char of the string and compare it with the vowel letters. If not an vowel we add it to consonants count. 

The character equals method compares the ASCII code of the character to match the input char .

We should note that spaces are also treated as chars and hence in else loop we are verifying whether it is an alphabet.

output:

Vowels: 5

Consonants: 12

JAVA Interview Questions and Answers for freshers

 

Read 1483 times Last modified on Tuesday, 24 July 2018 15:45

2 comments

  • posted by kavya Friday, 18 May 2018 18:23

    Hi will share very tricky java string interview questions
    What is the main difference between Java Strings and C, C++ Strings?
    Java Strings C,C++ Strings
    It is not terminated with null character in java. Here strings are terminated with a null character.
    Strings are treated as objects in java. It is considered as a character array.

    Comment Link
  • posted by Ganesh Ponna Thursday, 19 April 2018 15:44

    Hey Brother,


    Thank you! Thank you! Thank you! Your blog was a total game changer!


    I am going to implement the blackbox class "messagePool". Details are as below. I just want to implement it so that the whole application can run.
    // Call messagePool
    Java Code:
    Dac dac = GenericDac.getInstance();
    String result = dac.getMessagePool().getMessage(languageCode, key);

    public abstract interface Dac extends java.io.Serializable{
    public abstract void init(javax.servlet.ServletContext arg0, java.lang.String arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.jos.adf3.core.exception.DacInitException;
    public abstract com.pool.MessagePool getMessagePool();
    }
    public class GenericDac implements Dac{
    private com.pool.MessagePool messagePool;
    }
    Super likes !!! for this amazing post. I thinks everyone should
    bookmark this.
    Merci Beaucoup,

    Comment Link
Login to post comments

Vocabprep Banner

Please key in your e-mail address.

Be up-to-date with the happenings at Conduira!