Skip to main content

String interview questions and answers

String interview questions and answers are placed the current post as of my experience in interviews. This will helps who are trying to attend interview as fresher as well as experience. If any one is facing any other questions which are not present in the current page, please drop me an email to "subbareddynallamachu@gmail.com". 

Q1: String is a class or data type?
A: String is a class in java.lang package. But, in java, all classes are also are considered as data types. So we can take String as data type also.

Q2: What is the difference between == and equals() methods in java?
A: == operator compares the references of the String object. It does not compare the content of the object. equals() method compares the contents. While comparing the Strings, equals method should be used as it yields the correct result.

Q3: What is String constant pool?
A: String constant pool is a separate block of memory where the String objects are held by JVM. If a String object is created directly, using assignment operator as:


               
 String s1 = "Hello";


        Then it is stored in String constant pool.

Q4: What is the difference between:

  1. String s1 = new String("abc");
  2. String s2 = "abc";
A: "abc" is known as a string literal. In order to store the string literals a string pool will be created by the JVM. When a string literal is found in a class, it will be added to the string pool. However, if the same literal already exists in the pool, then it uses the existing one in pool, as string object is immutable(cannot be modified).

        In the first case, a new memory space is allocated in the heap on account of the "new" and also allocated in the pool on account of the literal "abc".

        In the second case, when the statement is being compiled, a pointer to the string literal "abc" is stored in s2. However same string had not been present, then it would have created a new instance in the pool and stored the reference.

Q5: What is object reference?
A: Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object. 

Q6: What is the difference between String and StringBuffer class?
A: String class is immutable i.e. it cannot be modified once declared.

StringBuffer class is not immutable and Strings can be appended to the original String. It is more efficient than using String when the String value could be changed.

For example,
              String str = "abc";
        str = str+"def";


        this creates a brand new String and puts the pointer in str.

        StringBuffer strBuff = "abc";
        strBuff.append("def");


        this appends the same string and more efficient.

Q7: Are there any other classes whose objects are immutable?
A: Yes, Classes like Character, Byte, Integer, Float, Double, Long... called 'Wrapper classes' are created as 'immutable'. Classes like Class BigInteger, BigDecimal are also.

Q8: What is the use of StringTokenizer class? A: The StringTokenizer class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish among identifiers, numbers and quoted strings, nor do they recognise and skip comments.

        The set of delimiters(the characters that separate tokens) may be specified either at creation time or on a per-token basis.

      StringTokenizer st = new StringTokenizer("I am subba reddy");
      while(st.hasMoreTokens()){
          System.out.println(st.nextToken());
      }


Prints the following output:
      I
      am
      subba
      reddy


Q9: Are there any other classes whose objects are immutable?
A: Yes, Classes like Character, Byte, Integer, Float, Double, Long... called "Wrapper Classes" are created as immutable. BigInteger, BigDecimal are also immutable.

Q10: What is the difference between StringBuffer and StringBuilder classes?
A: 1. StringBuffer class is synchronised and StringBuilder is not.
2. When the programmer wants to use several threads, he should use StringBuffer as it gives reliable results.
3. If only one thread is used, StringBuilder is preferred, as it improves execution time.


SCJP/OCJP Exam questions related to String:

Q1: What is the output of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Class1 {

 public static void main(String... args) {
  boolean st1 = "JTB" == "JTB";
  boolean st2 = new String("JTB") == "JTB";
  boolean st3 = new String("JTB") == new String("JTB");
  System.out.println(st1 && st2 || st3);
 }

}
Choose only one option:
        a. false
        b. true

Q2: What is the output of the below program?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Class2 {

 public static void main(String... args) {
  boolean st1 = "JTB" == "JTB";
  boolean st2 = new String("JTB").equals(new String("JTB"));
  boolean st3 = "JTB".toString() == "JTB";
  System.out.println(st1 && st2 && st3);
 }

}
Choose only one option:
         a. false
         b. true

Q3: Select which statements are true in below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Class3 {

 public static void main(String... args) {
  StringBuffer sb = new StringBuffer("JTB");
  String s = new String("JTB");
  boolean st1 = s.equals(sb);
  boolean st2 = sb.equals(s);
  boolean st3 = sb.toString() == s;
  boolean st4 = sb.toString().equals(s);
  boolean st5 = s.equals(sb.toString());
 }

}
Your options are:
        a. st1
        b. st2
        c. st3
        d. st4
        e. st5

Q4. Select which statements are true in below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Class4 {

 public static void main(String... args) {
  StringBuffer sb1 = new StringBuffer("JTB");
  StringBuffer sb2 = new StringBuffer("JTB");
  boolean st1 = sb1.equals(sb2);
  boolean st2 = sb1 == sb2;
  String s1 = new String("JTB");
  String s2 = new String("JTB");
  boolean st3 = s1.equals(s2);
  boolean st4 = s1 == s2;
 }

}
Please select which statements are evaluated to true? select only one:
a. st1
b. st2
c. st3
d. st4

Q5: What is the output of the below program?
1
2
3
4
5
6
7
8
9
public class Class5 {

 public static void main(String... args) {
  String st = null;
  System.out.print(null + st);
  System.out.print(st + null);
 }

}
Your options are:
        a. RuntimeException is thrown because of the first print statement
b. RuntimeException is thrown because of the second print statement
c. nullnullnullnull
d. nullnull
e. compilation error

Q6: What is the output of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Class6 {

 public static void main(String... args) {
  StringBuffer sb1 = new StringBuffer("JTB");
  StringBuffer sb2 = new StringBuffer(sb1);
  if (sb1.equals(sb2))
   System.out.println("true");
  else
   System.out.println("false");
 }

}
Your options are:
        a. true
        b. false

Q7: What is the result of compiling and running of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Class7 {

 public static void main(String... args) {
  String s1 = null;
  String s2 = null;
  if (s1 == s2)
   System.out.print("A");
  if (s1.equals(s2)) 
   System.out.print("B");
 }

}
Your options are:
a. "AB" will be printed
b. "A" will be printed followed be a NullPointerException thrown
c. "B" will be printed
d. No output is produced

Q8: What is the compilation and execution of the below program?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Class8 {

 public static void main(String... args) {
  String a = "JTB";
  String b = "JTB";
  String c = new String("JTB");
  System.out.print(a == b);
  System.out.print(a == c);
  System.out.print(b.equals(c));
  System.out.print(b.equals(a));
 }

}
Your options are:
        a. Compilation error

        b. falsefalsetruetrue

        c. truetruetruetrue

        d. truefalsetruetrue

Q9: What is the output of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Class9 {

 public static void main(String... args) {
  String stmt = "JTB is there to help you";
  for (String token : stmt.split("//s")) {
   System.out.print(token + " ");
  }
 }

}
Your options are: 
        a. JTB is there to help you
        b. JTB i there to help you
        c. No output is produced
        d. Compilation error

Q10: What is the compilation and execution of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Class10 {

 public static void main(String[] args) {
  Pattern p = Pattern.compile("[a-f]\\d+");
   Matcher m = p.matcher("ab34ef0");
   while(m.find()) {
   System.out.print(m.start()+" "+m.group());
   }
 }

}
Your options are:
        a. 0 ab345 f0
        b. 0 ab344 ef0
        c. 1 b35 f0
        d. 1 b345 f0


Q11: What is the compilation and execution of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Class11 {

 public static void main(String... args) {
  String s = "";
  Integer x = 5;
  StringBuffer sb = new StringBuffer();
  if (x < 15)
   s.concat("JTB");
  else
   sb.append("JTB");
  System.out.print(s + sb);
 }

}
Your options are: 
        a. JTB
        b. JTB JTB
        c. No output is produced
        d. Compilation error

Q12: What is the compilation and executions of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Class12 {

 public static void main(String... args) {
  String s = "";
  Integer x = 5;
  StringBuffer sb = "";
  if (x < 0)
   s.concat("JTB");
  else
   sb.append("JTB");
  System.out.print(s + sb);
 }

}
Your options are:
        a. JTB
        b. JTB JTB
        c. No output is produced
        d. Compilation error

Q13: What is the compilation and execution of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.util.Scanner;

public class Class13 {

 public static void main(String... args) {
  Scanner scan = new Scanner("JTB 2016, 123 false");
  while (scan.hasNext()) {
   if (scan.hasNextInt())
    System.out.print("Int");
   if (scan.hasNextBoolean())
    System.out.print("Boolean");
   scan.next();
  }
 }

}
Your options are:
        a. IntBooleanInt
        b. IntBoolean
        c. IntInt
        d. Compilation error

Q14: What is the output of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Class14 {

 public static void main(String... args) {
  String str = "www.";
  StringBuffer sb = new StringBuffer("javatbrains");
  sb.insert(11, ".com");
  str.concat("JTB");
  if (sb.length() > 10 || str.equals("javatbrains")) {
   sb.insert(0,str);
   System.out.print(sb);
  }
 }

}
Your options are: 
        a. www.
        b. javatbrains
        c. .com
        d. www.javatbrains.com

Q15: What is the compilation and execution of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Class15 {

 public void m(String s){
  System.out.println("String Method");
 }
 
 public void m(StringBuffer sb){
  System.out.println("StringBuffer Method");
 }
 public static void main(String... args) {
  Class15 c15 = new Class15();
  c15.m(null);
 }

}
Your options are:
        a. StringBuffer Method
        b. String Method
        c. null
        d. compilation error
        e. Runtime Exception

Q16: What is the output of the below program?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Class16 {

 public static void main(String... args) {
  String jtb = "www.javatbrains.com";
  Pattern p = Pattern.compile(".{4}a+(s)*");//line 8
  Matcher m = p.matcher(jtb);
  while (m.find()) {
   System.out.print(m.start());
  }
 }
}
Your options are:
        a. www.javatbrins.com
        b. compilation error in line8
        c. 17
        d. Runtime exception due line 8

Q17: Select the common methods which are defined for both type String and StringBuffer?

Choose app the answers that are apply:
        a. toString()
        b. length()
        c. append(String)
        d. trim()
        d. equals(Object)

Q18: Which of the following methods can be invoked by an object of Pattern class?

choose all the answers that apply:
        a. compile
        b. matches
        c. group
        d. toString

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...