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.

How many objects will be created for the following codes:

Answer»

A. 

String str1 = "abc"; //Line1String str2 = new String("abc"); //Line2

B.

String str1 = "abc"; //Line1String str2 = "abc"; //Line2

C.

String str1 = new String("abc"); //Line1String str2 = new String("abc"); //Line2
  • For A: In this case, TWO objects will be created. We know that WHENEVER a Java string is created using a new keyword, then two objects will be created i.e. one in the Heap Area and another one in the String constant pool. When the line1 is executed, the new string object str1 gets created and stored in the string constant pool. However, when line2 is executed, only one object is created using a new operator that gets stored in the heap memory (str2). This is because String constant pool already has a String object with the same string value (abc), and therefore, the reference of the string str1 from the string constant pool is returned.
  • For B: In this case, one object will be created. Here, for line1 (str1), one new object will get created in String constant pool, WHEREAS for line 2, string str2 will create a reference to the String str1 because the string constant pool already has a String object str1 with the same string value (abc).
  • For C: In this case, three objects will be created. In the case of line1 (str1), two objects are created, one in the string constant pool and one in the heap memory. As for line 2 (str2), one new object is created and stored in heap memory, but not in the string constant pool because a String constant pool object str1 already has the string object str1 with the same string value (abc).
2.

How do you check whether a String is empty in Java?

Answer»

The Java String class contains a particular method for determining whether or not a string is empty. The isEmpty() method DETERMINES whether or not a string has zero length. In the case where the length of the string is zero, it returns true, or else it returns false.

Example:

PUBLIC class StringEmpty{ // Function to determine if String is empty public static boolean isStringEmpty(String str) { //Use the isEmpty() method //to determine if the string is empty. if (str.isEmpty()) return true; else return false; } public static void main(String args[]) { String STR1="InterviewBit"; //non-empty string String STR2=""; //empty string System.out.println("Str1 \"" + str1 + "\" is empty? " + isStringEmpty(str1)); System.out.println("Str2 \"" + str2 + "\" is empty? " + isStringEmpty(str2)); }}

OUTPUT

Str1 "InterviewBit" is empty? falseStr2 "" is empty? true
3.

How can we convert string to StringBuilder?

Answer»

The append() method can be used to convert String to StringBuilder, and the toString() method can be used to convert StringBuilder to String. Below is a Java program to convert a string array to ONE StringBuilder object using the append method.

Example: 

public CLASS StringToStringBuilder { public static void main(String ARGS[]) { String strs[] = {"Scaler", "by", "InterviewBit!"}; StringBuilder SB = new StringBuilder(); sb.append(strs[0]); sb.append(" "+strs[1]); sb.append(" "+strs[2]); System.out.println(sb.toString()); }}

Output

Scaler by InterviewBit!
4.

In Java, how do you convert a string to an integer and vice versa?

Answer»

There is an Integer class in the JAVA lang package that provides different methods for converting strings to INTEGERS and VICE versa. The parseInt() method allows you to convert a String into an integer and the toString() method allows you to convert an Integer into a String. Below is a Java PROGRAM to convert a string to an integer and vice versa.

Example: 

public class StringtoInteger { public static void main(String args[]) { String STR1 = "1296"; int i= Integer.parseInt(str1); System.out.println(i); String str2 = Integer.toString(i); System.out.println(str2); }}

Output:

12961296
5.

How can a Java string be converted into a byte array?

Answer»

The getBytes() METHOD allows you to convert a string to a BYTE array by encoding or converting the specified string into a sequence of bytes using the default charset of the PLATFORM. Below is a Java program to convert a Java String to a byte array.

Example:

import java.util.Arrays;public CLASS StringToByteArray { public static void main(String[] args) { String STR = "Scaler"; byte[] byteArray = str.getBytes(); // print the byte[] elements System.out.println("String to byte array: " + Arrays.toString(byteArray)); }}

Output:

String to byte array: [83, 99, 97, 108, 101, 114]
6.

What do you mean by StringJoiner?

Answer»

STRINGJOINER is a Java class that allows you to construct or create a SEQUENCE of strings (characters) that are separated by delimiters LIKE a hyphen(-), comma(,), etc. Optionally, you can also pass suffix and prefix to the char sequence.

Example: 

// importing StringJoiner class import java.util.StringJoiner; public class ExampleofStringJoiner{ public static void main(String[] args) { StringJoiner joinStrings = new StringJoiner(",", "[", "]"); // passing comma(,) and square-brackets as DELIMITER // Adding values to StringJoiner joinStrings.add("Scaler"); joinStrings.add("By"); joinStrings.add("InterviewBit"); System.out.println(joinStrings); } }

OUTPUT

[Scaler,By,InterviewBit]
7.

Explain the string subSequence method.

Answer»

The Java STRING subSequence() method is a built-in function that RETURNS a charSequence (a subsequence) from a string.

8.

Why char array is preferred over a String in storing passwords?

Answer»

There are various reasons why a char array rather than a string should be used to store passwords. The following are a few of them:

  • Strings are immutable: The content of Strings cannot be modified/overwritten because any modification will result in the creation of a new String. As a result, we should always save sensitive DATA like passwords, Social Security NUMBERS, and so on in a char[] array rather than a String.
  • Security: Because String is immutable, storing the password as plain text keeps it in memory until it is cleaned up by the garbage collector. As string uses SCP (String Constant Pool) for re-usability of a string, it's possible that it'll remain in memory for a long time, and anyone with access to the SCP or memory DUMP can simply identify or retrieve the password in plain text. That's another reason why we should use an encrypted password instead of plain text.
  • Logfile safety: With an array, the data can be erased or WIPED up, overwritten and the password will not be present ANYWHERE in the system. Whereas, when using plain String, the chances of mistakenly printing the password to monitors, logs, or other insecure locations are substantially higher.
9.

What is the best way to split a string in Java?

Answer»

Split() is a Java method for breaking a string based on a Java string delimiter (specified REGEX). For example, a space or a comma(,) will usually be used as the Java string split attribute to break or split the string.

Syntax: 

string.split(String regex, INT limit)

Here,

  • regex: String is DIVIDED at this specified regex.
  • limit (optional parameter): Controls or limits the number of resulting substrings. Split() returns all potential substrings if the limit parameter is not specified or is 0.

Example:

public class SplitString { public static void main(String[] ARGS) { String str = "Scaler by InterviewBit"; // split string from space String[] result = str.split(" "); for (int i=0; i < result.length; i++) { System.out.println(result[i]); } }}

Output: 

ScalerbyInterviewBit
10.

Why is a string used as a HashMap key in Java?

Answer»

Basically, the HashMap object can store key-value pairs. When creating a HashMap object and storing a key-value pair in that object, you will notice that while storing, the hash code of the key will be calculated, and its calculated value will be placed as the resultant hash code of the key. Now, when the key is passed to fetch its value, then the hash code of the key is calculated again, and if it's equal to the value of the hash code initially calculated, the initial value placed as the resultant hash code of the key is RETRIEVED or fetched.

Let's say we utilized a variable as a key to store DATA and then changed the value of that variable. In this case, since we have altered the key, the hash code calculated of the current key will not match the hash code at which its value was ORIGINALLY stored. This makes RETRIEVAL impossible. String values are immutable, so once they've been created, they can't be changed. As a result, it is recommended to use Strings as HashMap KEYS.

11.

Is String thread-safe in Java?

Answer»

Strings are immutable objects, which means they can't be changed or altered once they've been created. As a result, whenever we manipulate a String OBJECT, it creates a new String rather than modifying the original string object. In Java, every immutable object is thread-safe, which means String is also thread-safe. As a result, MULTIPLE THREADS can access a string. For INSTANCE, if a thread MODIFIES the value of a string, instead of modifying the existing one, a new String is created, and therefore, the original string object that was shared among the threads remains unchanged.

12.

What are the different string methods in Java?

Answer»

There are various string operations in Java that allow us to work with strings. These methods or operations can be USED for string handling in Java as well as string manipulation in Java. Some of such methods are as follows:

  • split(): Split/divide the string at the specified regex.
  • compareTo(): COMPARES two strings on the basis of the Unicode value of each string character.
  • compareToIgnoreCase(): Similar to compareTo, but it also ignores case differences.
  • length(): Returns the length of the specified string.
  • substring(): Returns the substring from the specified string.
  • equalsIgnoreCase(): Compares two strings IGNORING case differences.
  • contains(): CHECKS if a string contains a substring.
  • trim(): Returns the substring after removing any leading and trailing whitespace from the specified string.
  • charAt(): Returns the character at specified index.
  • toLowerCase(): Converts string characters to lower case.
  • toUpperCase(): Converts string characters to upper case.
  • concat(): Concatenates two strings.
Previous Next