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

JVM, JRE and JDK in Java

JVM, JRE and JDK are the most basic common concepts to know in java. These are the basic features to understand how Java architecture works? JVM stands for Java Virtual Machine, which doesn't have any physical directories created in java installation. JRE stands for Java Runtime Environment, which creates the directory under Java installation path and also present in JDK. JDK stands for Java Development Kit, which creates the directory in Java installation path and also it has it's own JRE. Since we have already learn that Java is platform independent means if we have implemented any of the java class in one environment, it will be executed in any other environment and provides the same output. But, JVM, JRE and JDK all are platform dependent . So that, for windows, linux, unix, mac, solaris..etc has it's own JVM, JRE and JDK. One will be not compatible with other environments. While installing the Java, we might come to know a bit about JRE and JDK. But, JVM is the other...

Prime, Fibonacci and Factorial number with example in java

Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number. Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number . For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8. The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false. package com . javatbrains . practice ; public class PrimeNumber { public boolean isPrimeNumber ( int number ) { if ( number <= 1 ) return false ; // There's only one ...

How to insert images into database using JDBC?

How to insert images into database table by using JDBC? To know about these topic follow the below lines,           Before going to write a JDBC program for inserting images into database table, we need to create a specific table for inserting images column datatype. For creating the database table, execute the below command in MySQL command prompt. 1 2 3 4 CREATE TABLE ` images ` ( ` image_id ` int ( 11 ) NOT NULL AUTO_INCREMENT, ` image_flag ` int ( 11 ) NOT NULL , ` image ` longblob NOT NULL , PRIMARY KEY ( ` image_id ` ));           After executing the above query in MySQL command prompt, execute the below query to know weather the above table query is created or not. 1 Show tables;            When you have executed the above query that will show you the list of table which all exists in the current database. Current tab...