Important Top 50 java string interview questions and answers for beginners and experienced in 2023

purchase Lyrica in canada Important Top 50 java string interview questions and answers for beginners and experienced in 2023: The core java string interview questions and answers purchase Ivermectin online are the most commonly asked for Java professionals. The java string interview questions and answers includes interview questions on  immutable strings in java, string interview questions on String vs StringBuffer vs StringBuilder , java string interview questions on string programs, java string interview questions on object creation in string, Character encoding for Strings in java, java string interview questions on thread-safe strings in java, constructors in StringBuffer Class, constructors in StringBuilder Class in java , ensureCapacity() method in the StringBuilder Class, interview question on toString() method in java, java string interview questions on StringTokenizer in java, Constructors of StringTokenizer Class in java, java string interview questions on StringTokenizer class methods in java,java string interview questions to compare two strings in java and many more

 The Core Java Interview Questions are useful for both freshers as well as experienced professionals searching for job opportunities. 

Core Java String Interview Questions & Answers 

 

1) What is String in java ? 

The below given points are to be considered for String in java

  • String is not a Keyword in java
  • String is a class in java defined in java.lang package
  • String is considered immutable and final in java
  • JVM uses StringPool to store all the objects
  • A String Object can be instantiated using double quotes and overloading of “+” operator for concatenation
  • A String is an representation of sequence of char values and an array of characters results same as a string
char[] name ={'m','o','h','i','t'};
String admin =new String(name);

 2) Is String considered a primitive type or derived type in java ?

The primitive types in java are int, short,long,float, double and boolean.

String is considered as a derived type in java as it has its own state and behavior. Strings literals are stored in special memory called as Constant String Pool.

 3) What all interfaces are implemented by String in java ?

The java.lang.String class implements the below given built-in java interfaces

  • Serializable
  • Comparable
  • CharSequence

4) Name few String methods in java ?

The below given are few commonly used string methods available to perform operations in java

  • length()
  • replace()
  • equals()
  • compare()
  • concat()

5) Name String Classes that implements CharSequence Interface in java ?

The CharSequence Interface is used to represent the sequence of char values. The below given String Classes implements the CharSequence interface for string manipulation in java

  • String
  • StringBuffer
  • StringBuilder

6) What are the possible ways to create a string in java ?

A String Object in java can be created as given below:

  • Create String Object using literals: The String object created using literals is stored in constant string pool by JVM. If the created string already exists in constant string pool, then JVM returns the reference from the pool.
String strLiterals ="A Constant value in string variable is called literals";
  • Create String Object using new keyword: The String object created using new keyword is stored in a heap memory by JVM which is a non -string pool and object is referenced from heap memory.
String strVariable = new String("Creating String using new keyword in java ");

7) Describe the benefits of String being immutable in java ?

String in java are immutable and provides the below given advantages:

  • String Objects created are stored in String Pool and cannot be changed which makes it reusable
  • String can be passed as method arguments as its value does not change
  • As String is immutable and thus they are thread-safe
  • String data does not require Synchronization and improves performance

8) Is String Pool eligible for garbage collection in java ?

Yes. All the strings in the String Pool with no reference to the program are eligible for garbage collection

9) Why are Strings considered to be Thread-Safe in java ?

Strings are Immutable which means that string instance won’t get changed across multiple threads and that makes it Thread Safe. For instance, if a thread changes the string value, then a new String object gets created in the heap memory instead of modifying the existing one

10) Explain Character encoding for Strings in java ?

The Character encoding for Strings has been handled differently before or after Java 9 .

Java Version till Java 8: String character encoding till Java 8 is UTF-16 format. The char data type and java.lang.Character objects are defined as fixed-width 16-bit entities

Java 9 Version: The character encoding has been changed from Java 9

1-byte Character : Strings that contain only 1-byte character (8-bit) use Latin-1 encoding
Multi- byte Character: Strings with at least 1 multi-byte character (16-bit) use UTF-16 encoding

11) What is StringBuffer Class in java ?

The StringBuffer class in java is similar to String class except that StringBuffer allows to create mutable string objects which can be changed. For instance , the below given program appends original string

package core.java.planforexams.string;

public class StringBufferSample {

	public static void main(String args[]){  
		StringBuffer sb=new StringBuffer("Hello planforexams.com Users ! ");  
		
		//String method t o append the original String
		sb.append("Original String Appended"); //string is appended / modified  
		System.out.println(sb);    // prints Hello planforexams.com Users ! Original String Appended
		
		// String method to insert new String data to the original String
		sb.insert(1, "String added using insert() method");
		System.out.println(sb);   
		
		// String method to reverse the string
		sb.reverse();   
		System.out.println(sb); // prints the string reversed
		
	  
		StringBuffer userName = new StringBuffer("Mohit");
		 // String method to replace the String at specific position
		userName.replace(1,1,"R");  
		System.out.println(userName); // prints MRohit  
	}
}

12) Name few constructors in StringBuffer Class in java ?

ConstructorDescription
StringBuffer()creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str)creates a string buffer with the specified string.
StringBuffer(int capacity)creates an empty string buffer with the specified capacity as length

13) What is StringBuilder Class in java ?

The StringBuilder class in java is similar to String class except that StringBuilder allows to create mutable string objects which can be changed. For instance , the below given program appends original string

package core.java.planforexams.string;
public class StringBuilderSample {
	public static void main(String args[]){ 
		StringBuilder strBuilder=new StringBuilder(":::Original String ::: ! ");  
	 	System.out.println("Current String Capacity :::" + 
                           strBuilder.capacity()); 
	 	//String Method appended
		strBuilder.append("++++Appended++++"); 
		System.out.println(strBuilder);    
		System.out.println("Appended String Capacity :::" + 
                           strBuilder.capacity());
		// String method to insert new String data to the original String
		strBuilder.insert(1, "MMMMMMMMMMMMMM");
		System.out.println(strBuilder);   
		System.out.println(" Modified Capacity :::" + strBuilder.capacity()); 
		
		// String method to reverse the string
		strBuilder.reverse();   
		System.out.println(strBuilder); // prints the string reversed
		StringBuilder userName = new StringBuilder("Mohit");
		 // String method to replace the String at specific position
		userName.replace(1,1,"R");  
		System.out.println(userName); // prints MRohit  
    }
}

14) Name few constructors in StringBuilder Class in java ?

ConstructorDescription
StringBuilder()creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str)creates a string Builder with the specified string.
StringBuilder(int length)creates an empty string Builder with the specified capacity as length.

15) Explain ensureCapacity() method in the StringBuilder Class in java ?

The StringBuilder Clas create a empty String builder with initial capacity of 16. The ensureCapacity() method makes sure that the StringBuilder object stores the minimum capacity than the current available capacity.

For instance, if the StringBuilder object capacity is greater than the initial capacity of 16, then it increase the capacity by by (oldcapacity*2)+2 which mens (16*2) +2 =34

package core.java.planforexams.string;
public class StringBuilderCapacity {
	public static void main(String[] args) {
		StringBuilder sb=new StringBuilder();  
		System.out.println(sb.capacity());//default 16  
		sb.append("Hello");  
		System.out.println(sb.capacity());// No change, still 16   
		sb.append("Mohit Sharma");  // changes (16*2) +2 =34
		System.out.println(sb.capacity());
	}
}

16) Difference between StringBuffer and StringBuilder in java ?

StringBuffer in javaStringbuilder in java
StringBuffer is SynchronizedStringBuilder is not Synchronized and thus not thread safe
StringBuffer is thread-safeStringBuilder is not thread-safe
StringBuffer is less efficient when compared to StringBuilderStringBuilder executes faster than StringBuffer

17) Difference between String and StringBuffer in java ?

String in java Stringbuffer in java
String is immutableStringBuffer is mutable
Creates a new String Object whenever it is appended and thus performs slower in comparison to StringBufferStringBuffer performs better when string is appended multiple times for concatenation
String consumes more memory StringBuffer consumes less memory

18) Explain toString() method in java ?

toString() method enables an object to be represented as string in java. The java compiler also internally invokes the toString() method to print an object value.

toString() method can be overridden to return the object value as per user implementation need.

For instance, the below java program overrides toString() to print the firstName and lastName

package core.java.planforexams.string;

public class ToStringExample {
	 private String firstName;
	 private String lastName; 
	 // Class Constructor with arguments 
	 ToStringExample( String firstName, String lastName){  
		 this.firstName=firstName;  
		 this.lastName=lastName;  
	 }
	// Override the toString() method
	public String toString(){  
		  return firstName +" "+lastName ;
		 }  
	// Class Main method Call
	public static void main(String[] args) {
		ToStringExample fullname = new ToStringExample("Mohit", "Sharma");
		 System.out.println("Full name is :::" + fullname);
      // compiler invokes the override toString() -> fullname.toString()
	}
}

19) What is StringTokenizer in java ?

The StringTokenizer class in java enables to break the string into separate tokens using the delimeter

package core.java.planforexams.string;
import java.util.StringTokenizer;

public class StringTokenizerExample {

	public static void main(String[] args) {
		StringTokenizer strTokenizer = new StringTokenizer("This is StringTokenizer Example");  
	     while (strTokenizer.hasMoreTokens()) {  
	         System.out.println(strTokenizer.nextToken());  
	     }  
	}
}

20) What are the Constructors of StringTokenizer Class in java ?

String tokenizer ConstructorConstructor Description
StringTokenizer(String str)provides StringTokenizer with specified string
StringTokenizer(String str, String delim)provides StringTokenizer with specified string and delimeter
StringTokenizer(String str, String delim, boolean returnValue)provides StringTokenizer with specified string, delimeter and boolean returnValue. When true, delimiter characters are considered to be tokens. When false, delimiter characters serve to separate tokens.

21) What are the StringTokenizer class methods in java ?

The below given are the StringTokenizer class methods

stringtokenizer methodSTRINGTOKENIZER METHOD Description
boolean hasMoreTokens()indicates if there is more tokens available
String nextToken()indicates the next token from the StringTokenizer object with return type as String
String nextToken(String delim)returns the next token based on the delimeter
boolean hasMoreElements()indicates if there is more tokens available
Object nextElement()indicates the next token from the StringTokenizer object with return type as Object
int countTokens()returns the total token count

22) Write a string program to return a char value at given index in java ?

The java string provides charAt() method which returns a char value at given index number

package core.java.planforexams.string;

public class StringCharAtExample {

	public static void main(String[] args) {
		String site ="planforexams.com";  
		char ch=site.charAt(0); 
		System.out.println("Char at index 1 is :: " + ch);  
		char ch2=site.charAt(2); 
		System.out.println("Char at index 2 is :: " + ch2); 
		char ch3=site.charAt(4); 
		System.out.println("Char at index 3 is :: " + ch3); 
	}
}

Output:
Char at index 0 is :: p
Char at index 2 is :: a
Char at index 4 is :: f

23) Write a program to compare two strings in java ?

The java string provides compareTo(String str) method which compares the given string with the current string. The string comparison is performed on the Unicode values of each character in the string

Lets Consider 2 strings as One and Two, then the below values could be returned from the string comparison

if One > Two, returns positive number
if One < Two, returns negative number
if One == Two, returns 0

package core.java.planforexams.string;
public class CompareStringExample {
 	public static void main(String[] args) {
		String str1="abdakadabda";  
		String str2="abcdeasbdcs";  
		String str3="abdakadabda";
		System.out.println(" String 1 comaprison with String 2::" + str1.compareTo(str2));  // returns 1 - Not equal
		System.out.println(" String 1 comaprison with String 3::" + str1.compareTo(str3));  // returns 0 -equal
	}
}

24) Write a program to concatenate strings in java ?

The java string provides concat(String str) method which allows to concatenate the given string at the end of the existing string

package core.java.planforexams.string;
public class ConcatenateStringExample {
	public static void main(String[] args) {
		String stringConcatenation="Original String";  
		stringConcatenation.concat("Cannot modify the existing string object");  
		System.out.println(stringConcatenation);  
		stringConcatenation=stringConcatenation.concat("::::: modifies the string with creation of new string object ::::");  
		System.out.println(stringConcatenation);  
	}
}

25) Write a string program with contains() in java ?

The java string provides contains(CharSequence char) method which check the sequence of char values in the given string. Contains() return true if the sequence of char value found in the string, else return false

package core.java.planforexams.string;
public class StringContainExample {
  public static void main(String[] args) {
  String message="String contain() method tutorial for planforexams user";  
		System.out.println(message.contains("method tutorial"));  
		System.out.println(message.contains("java"));  		
	}
}
Output: 
true
false

26) Write a string program to implement getBytes() in java ?

The java string getBytes() method returns the byte array which is a sequence of bytes. For instance, the below given program retrieves the byte[] and prints each received sequence of bytes

package core.java.planforexams.string;
public class StringGetByteExample {
	public static void main(String[] args) {
      // Define a String with constant value
		String name ="Mohit Sharma";
		// Create a byte array to get byte for each character in the string
		byte[] nameBytes=name.getBytes();  
		// Print the received byte using loop
		for(int incr=0;incr<nameBytes.length;incr++){  
		System.out.println(" Byte Value for each Character in name:: " + nameBytes[incr]);  
		}  	
	}
}
Output:
Byte Value for each Character in name:: 77
 Byte Value for each Character in name:: 111
 Byte Value for each Character in name:: 104
 Byte Value for each Character in name:: 105
 Byte Value for each Character in name:: 116
 Byte Value for each Character in name:: 32
 Byte Value for each Character in name:: 83
 Byte Value for each Character in name:: 104
 Byte Value for each Character in name:: 97
 Byte Value for each Character in name:: 114
 Byte Value for each Character in name:: 109
 Byte Value for each Character in name:: 97

27) Write a string program to implement getChar() in java ?

The java string getChars() method enables to copy the string content into a specified char[]

String getChar() method syntax:
public void getChars(int srcStartIndex, int srcEndIndex, char[] destination, int dstBeginIndex)
where
srcStartIndex – depicts start index of the source string
srcEndIndex – depicts end index of the source string
srcStartIndex – depicts total character length of the char[]
srcStartIndex – depicts start index of the char[]

package core.java.planforexams.string;
public class GetCharArrayFromStringExample {
	public static void main(String[] args) {
         // Create a String with Constant Value
        String retrieveCharArray = new String("This is an example for getChar()");  
   // Define the char[]  to read the total characters from the string
    char[] retrieveCharValues = new char[7];  
     try{  
 // Call getChars() with the index values for the Source String and Char []
        	retrieveCharArray.getChars(11, 18, retrieveCharValues, 0);  
           System.out.println(retrieveCharValues);  
        }catch(Exception ex){
        	 System.out.println(ex);
        	}          
	}
}     
Output:
example      

28) Which String classes create mutable objects in java ?

The below given String Classes can be used for creating mutable string objects

  • StringBuffer
  • StringBuilder

29) How many string objects are created in the below given code?

String first = “Dummy”;
String second = “Dummy”;

Only One String object is created as string literals are created once and then referenced if already exist in the constant string pool

30) How many string objects are created in the below given code?

String first = “Dummy”;
String second = new String(“Dummy”);

The code will generate 2 object , one object for String literal “Dummy” and another string object with the new Keyword for value “Dummy”

31) Where the String pool is located ?

The string pool is located inside the heap memory only. JVM reserves memory for string pool which store the string literals

32) Define String intern ?

String Intern is the string object created in the string constant pool. The intern() allows to create a exact copy of the heap memory string object in the string constant pool. This process is called as interning.

String first = "Dummy";
String second = new String("Dummy");
// second string object references first object from string pool
second = second.intern() ;   

33) Write a string program using startsWith() and endsWith() in java ?

34) What are the advantages of using String Literals in java ?

String literals does not create object when lietral value already exist and provides the existing object from the string constant pool which makes it memory efficient

Leave a Reply

Your email address will not be published. Required fields are marked *

*