Explore topic-wise InterviewSolutions in Current Affairs.

This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.

1.

Can we use a string in the switch case in java?

Answer»

Yes, Java ALLOWS you to use strings in switch case conditions. Below is a Java PROGRAM that shows the use of string in switch case.

Example:

public class StringinSwitchCase { public static VOID main(String[] args) { String fruit = "APPLE"; switch(fruit) { case "Mango": System.out.println("Sweet"); break; case "Apple": System.out.println("Delicious"); break; case "ORANGE": System.out.println("Luscious"); break; default: System.out.println("Not a fruit"); } }}

Output: 

Delicious
2.

What is the use of the substring() method in Java?

Answer»

The substring method is used to RETURN substring from a SPECIFIED string. This method takes TWO parameters i.e., beginIndex (the starting index) and endIndex (the ending index). In the case of substring(), method startIndex is inclusive and endIndex is exclusive.

Syntax: 

substring(int beginIndex, int endIndex)

Or

substring(int beginIndex)

Here, 

  • beginIndex: Index that marks the starting of subsequence and it is inclusive.
  • endIndex: Index that marks the ending of subsequence and it is exclusive.

Example:

IMPORT java.lang.Math;public class InterviewBit{ // driver code public static void main(String args[]) { String str = "Scaler by InterviewBit"; //prints substring from 7th index System.out.print("Returns: "); System.out.println(str.substring(7)); // prints substring from 0-6, exclusive 6TH index System.out.print("Returns: "); System.out.println(str.substring(0, 6)); // prints the substring from 10-22, exclusive 22th index System.out.print("Returns: "); System.out.println(str.substring(10, 22)); } }

Output: 

Returns: by InterviewBitReturns: ScalerReturns: InterviewBit
3.

Is it possible to compare Strings using the == operator? If so, what is the risk involved?

Answer»

Yes, you can compare strings using the == operator. One can use == operators for reference comparison (address comparison). The majority of the time, DEVELOPERS compare strings with the == operator, instead of using the equals() method, resulting in an error.

Example:

PUBLIC class StringComparison{ public STATIC void main(String args[]) { String str1="Scaler"; String str2="Scaler"; String str3=new String("Scaler"); System.out.println(str1==str2); //true because both POINTS to same memory allocation  System.out.println(str1==str3);  //false because str3 refers to instance CREATED in heap System.out.println(str1.equals(str3)); //true because both share same content  //even if both are different string objects } }

Output: 

truefalsetrue
4.

What is the difference between str1 == str2 and str1.equals(str2)?

Answer»

JAVA offers both the equals() method and the "==" operator for comparing objects. However, here are some differences between the two:

  • Essentially, equals() is a method, while == is an operator.
  • The == operator can be used for comparing references (addresses) and the .equals() method can be used to compare content. To put it simply, == checks if the objects point to the same memory location, whereas .equals() compares the values of the objects.

Example:

public class StringComparison{ public STATIC void main(STRING[] args) { String str1=new String("Scaler"); String str2=new String("Scaler"); System.out.println(str1 == str2); System.out.println(str1.equals(str2)); }}

Output:

falsetrue

In this example, two different String objects are being created, str1 and str2.

  • If str1 and str2 are compared using the == operator, then the result will be false, because both have different addresses in the memory. Both must have the same address in the memory for the result to be true.
  • If you use the equals method, the result is true since it's only comparing the values GIVEN to str1 and str2, even though they are different objects.
5.

In Java, how can two strings be compared?

Answer»

In Java, there are several ways for comparing two strings. The following are a few of them:

  • String Equals Method: In this method, the strings are compared based on the values within them. If the values of the two strings are the same, it returns true; otherwise, it returns false. This method is case-sensitive.

Syntax:

str1.equals(STR2);

For example: 

Input 1= ScalerInput 2= InterviewBitOutput= falseInput 1= ScalerInput 2= ScalerOutput= trueInput 1= ScalerInput 2= scalerOutput= false
  • String Equals Ignore Case: By USING this method, the two strings are compared without taking into account the case (upper or lower). It returns true if the two values are the same and not null.

    Syntax:
str1.equalsIgnoreCase(str2);

For Example:

Input 1= ScalerInput 2= InterviewBitOutput= falseInput 1= ScalerInput 2= ScalerOutput= trueInput 1= ScalerInput 2= scalerOutput= true
  • Object Equals Method: The method returns true if its arguments are equal, otherwise, it returns false. Accordingly, if both arguments are null, the RESULT is true, and if just one argument is null, the result is false.

Syntax: 

Object.equals(str1, str2)

For example: 

Input 1= ScalerInput 2= InterviewBitOutput= falseInput 1= ScalerInput 2= ScalerOutput= trueInput 1= ScalerInput 2= nullOutput= falseInput 1= nullInput 2= nullOutput= True
  • String Compare To Method: This method compares input strings with each other. Upon comparison, the following VALUE is RETURNED:
  1. If (str1>str2), a positive value is returned.
  2. If (str1==str2), 0 is returned.
  3. If (str1<str2), a negative value is returned.

Syntax:

str1.compareTo(str2)

Example: 

Input 1= InterviewBitInput 2= ScalerOutput= -10Input 1= ScalerInput 2= ScalerOutput= 0Input 1= ScalerInput 2= InterviewBitOutput= 10
6.

State the difference between StringBuffer and StringBuilder in Java.

Answer»

StringBuffer and StringBuilder are two Java classes for manipulating strings. These are mutable OBJECTS, i.e., they can be modified, and provide various methods such as insert(), substring(), delete(), and append(), for String manipulation.

  • StringBuffer: The StringBuffer class was created by the Java Team when they REALIZED the need for an EDITABLE string object. Nevertheless, StringBuffer has all methods synchronized, MEANING they are thread-safe. Therefore, StringBuffer allows only one thread to access a method at once, so it is not possible to call StringBuffer methods from two THREADS simultaneously, which means it takes more time to access. The StringBuffer class has synchronized methods, making it thread-safe, slower, and less efficient than StringBuilder. The StringBuffer class was introduced in Java 1.0.
    • Syntax:
StringBuffer var = new StringBuffer(str);
  • StringBuilder: It was at that point that the Java Team realized that making all methods of StringBuffer synchronized wasn't the best idea, which led them to introduce StringBuilder. The StringBuilder class has no synchronized methods. Unlike StringBuffer, StringBuilder does not offer synchronized methods, which makes it less thread-safe, faster, and more efficient. StringBuilder was introduced in Java 1.5 in response to StringBuffer's shortcomings.
    • Syntax: 
StringBuilder var = new StringBuilder(str);
7.

State the difference between String and StringBuffer.

Answer»

String objects in Java are immutable and final, so we can't change their value after they are created. Since STRINGS are commonly used in applications, we need to PERFORM several operations on them such as substring(), equals(), indexof(), toUppercase(), etc. Each time we manipulate a string, a new String object is created, and all PREVIOUS objects will be garbage, placing a strain on the garbage collector. This is why The Java team developed StringBuffer. A StringBuffer is a mutable object, meaning it can be changed, but the string is an immutable object, so it cannot be changed once it has been created. 

  • String

Syntax:

String str1="InterviewBit";String str2=new String("Scaler");Scanner str3=new Scanner(System.in);String str4=str3.nextLine();

Example: Concatenation Example of String. A string class takes longer to perform a concatenation operation than a string buffer class.

public class Scanner{ public STATIC void MAIN(String []args) { StringBuilder stbu=new StringBuilder(); //Initial object size System.out.println(stbu.capacity()); String str="Scaler"; System.out.println(str); String str1 = new String("InterviewBit"); System.out.println(str1); str1 += " Articles"; //string update System.out.println(str1); }}

Output:

16ScalerInterviewBitInterviewBit Articles
  • StringBuffer

Syntax:

StringBuffer var = new StringBuffer(str);

Example: Concatenation Example of StringBuffer. String buffer class perform concatenation operations more quickly than string classes.

public class StringBuffer{ public static void main(String []args) { StringBuilder stbu=new StringBuilder(); //Initial object size System.out.println(stbu.capacity()); StringBuffer stbr= new StringBuffer("InterviewBit"); System.out.println(stbr); stbr.append(" Articles"); //string update System.out.println(stbr); stbr=new StringBuffer("Scaler"); System.out.println(stbr); }}

Output:

16InterviewBitInterviewBit ArticlesScaler
8.

What does the string intern() method do in Java?

Answer»

If you apply the intern() method to a few strings, you will ensure that all strings having the same content share the same memory. As soon as a String object is invoked with intern(), it first checks if the string value of the String object is already present in the string pool and if it is AVAILABLE, then the reference to that string from the string CONSTANT pool is returned. If not, a new string object is added to the string pool, and a reference to it is returned.

Example:

String str1 = new String("Scaler by InterviewBit").intern(); //LINE1 String str2 = new String("Scaler by InterviewBitt").intern(); //Line2 System.out.println(str1 == str); //prints true

As you can see, the intern() method is invoked on the String objects. When Line1 is executed, memory is allocated within the SCP. In line 2, no new string objects are created in the SCP because str1 and str2 have the same content. As a result, the reference to the object created in line1 is returned. This MEANS that str1 and str2 both point to the same memory. Therefore, the print statement prints true.

9.

Is String immutable or final in Java? If so, then what are the benefits of Strings being Immutable?

Answer»

Yes, Strings are immutable in Java. Immutable objects MEAN they can't be changed or ALTERED once they've been created. HOWEVER, we can only modify the reference to the string object. The String is immutable in Java because of many reasons LIKE security, CACHING, synchronization and concurrency, and class loading.

10.

Explain String pool in Java.

Answer»

String Pool, also known as SCP (String Constant Pool), is a special storage space in Java heap memory that is used to store unique string objects. Whenever a string object is created, it FIRST CHECKS whether the String object with the same string value is already present in the String pool or not, and if it is available, then the reference to the string object from the string pool is returned. Otherwise, the new string object is ADDED to the string pool, and the respective reference will be returned.

As SHOWN in the above image, two Strings s1 and s2 are created with the values "Apple" and "Mango". Therefore, when the third String S3 containing the value "Apple" is created, instead of creating a new object, the existing object reference will be returned. Here, s1==s2 is false both strings s1 and s2 refer to different string values from the string pool i.e. apple and mango. We can see that s1==s3 is true because both strings s1 and s3 refer to a single string value from a string pool i.e., apple. 

11.

State the difference between String in C and String in Java.

Answer»
  • String in C: In C, strings are just arrays of characters, and they are terminated with a /0, which is why we commonly refer to them as "null-terminated". Strings in C, like "ABC$%", actually consist of 6 characters 'a' 'b' 'c' '$' '%' and '/0', but these can be EASILY manipulated.
  • String in Java: Java treats Strings as objects, not arrays. String objects are created using the java.lang.String CLASS. String objects in Java are immutable; you cannot modify their contents. This means whenever we manipulate a String object, the new String is created rather than the original string being modified.
12.

Is String a primitive or derived type in Java?

Answer»

Strings are derived data types. Strings are Java objects that REPRESENT sequences of characters. STRING objects are CREATED using the java.lang.String class. There are MANY functions that need to be called upon when processing a string, such as substring(), indexof(), equals(), TOUPPERCASE(), etc, which primitives types do not have.

13.

How to declare a string in Java?

Answer»

String DECLARATION in Java can be DONE in TWO ways:

  • By string LITERAL: Double quotes are used to create Java String literals. 
    • Example: String str= "SCALER";  
  • By new keyword: Keyword "new" is used to create a Java string.
    • Example: String str=new String ("Scaler");
Previous Next