Session 4 - String and Array
Session 4 - String and Array
String is a class in java which is present in java.lang package. According to Oracle docs,
The String class represents character strings. Strings are constant, their values cannot be changed after
they are created.
Yes, String class is immutable in java. Immutable means once the object is created, its value can not
be changed.
Two objects are created by the above statement. One object in the heap memory and one object in the
String constant pool.
I have already shared how to reverse a String in java by 6 different ways. [Solution]
You can create a String object using two ways. First is using new operator and second is using
string literal. Objects created using new operator are stored in the heap memory while
string literals are stored in the string constant pool.
As we know String objects are immutable. It means they are thread-safe also.
Yes, you can use String in switch statement in java 7. Prior to java 7 , you had to use if-else
statements to achieve the task.
Intermediate Level (2-7 years)- Java String Interview Questions and Answers
Q12 Write a program to reverse a String in java without using reverse() method?
This is a very important question. Please make sure you have gone through this before appearing for
the interview. I have already shared how to reverse a String in java by 6 different ways. [Solution]
This is one of the most asked question in the java developer interview.
String is immutable in java. Once created its value can not be changed. StringBuffer is mutable.
Check what is the difference between String and StringBuffer in java.
Below are the main differences between StringBuilder and StringBuffer in java.
Q16 How many objects will be created for the following code:
Two objects are created. Object created using new operator is stored in the heap memory (str2).
Object created using String literal str1 is stored in the string constant pool.
Q17 How many objects will be created for the following code:
String str1 = "abc";
Only one object is created. String str1 will create a new object in String constant pool, while String
str2 will create a reference to the String str1.
Q18 How many objects will be created for the following code:
Three objects are created. For the first statement(str1) two objects are created one in String constant
pool and one in heap memory.
But for the second statement(str2), compulsory 1 new object is created in heap memory but no new
object is created in string constant pool as it is already present.
The task of intern() method is to put String (which is passed to the intern method) into string constant
pool.
Q20 What are mutable and immutable objects in java?
Mutable objects value can be changed. StringBuilder and StringBuffer are the examples of the
mutable objects.
Immutable objects value can not be changed once created. String is an immutable class in java.
2. Class loading : String objects are used for Class loading. It is possible that wrong class has been
loaded in the JVM, if the String is mutable i.e modifiable.
3. Thread Safe : Immutable Strings are thread-safe. Synchronization is not required when we use
them in the multithreading environment.
Q24 What is the difference between Java String and C,C++ Strings ?
In C and Java both programming language treat String object as char Array.
Java String is an object while C String is a NULL terminated character array. Java String object
allows calling different methods like toUpperCase(), length(), substring().
String is mostly used as a key in HashMap class because it implements equals() and hashCode()
methods which is required for an Object to be used as key in HashMap.
Yes, It is possible to call String class methods using String literals. For example
"javahungry".indexOf(u)
"javahungry".charAt(0)
"javahungry".compareTo("javahungry")
You can use split() method of java.lang.String class or StringTokenizer to split a comma separated
String. String split() method is easier to use and better because it expects a regular expression and
returns an array of String which you can manipulate in the program code.
Q28 Write a java program to find the first non repeated character in the String? [Solution]
This is the starting question for the product companies, so make sure you go through it. Write a java
program to find the first non repeated character in the String.
Use equals() method to compare two Strings.Avoid using "==" operator. The main reason to use
equals() method is that it always compare String values i.e content. == operator compares the
reference in the memory. Check the difference between == and equals() method in java.
Q30 Explain the difference between str1.equals("abc") and "abc".equals(str1), where str1 is
any String object?
If str1 value is "abc" then both statements will give the result true. Main difference between the two
statement arises when we pass str1 value as NULL. If the str1 is null then first statement will throw
null pointer exception while second statement will return false.
Write a java program to find out if the given String has all Unique Characters. There are 5 ways to
determine String has all Unique Characters.
This is an important phone interview coding question. Write a java program to count number of words
in the String.
Write a java program to find all the permutations of the given String. Permutation is the all possible
combinations of the Strings possible for any word. [Solution]
Write a java program to calculate total number of characters in the String .[Solution]
Write a java program to find all possible combinations of String. This question can be asked in the
phone interview, so make sure you go through it.[Solution]
Q40 What is String Constant Pool? Why java provided String Constant pool as we can store
String in the heap memory?
String constant pool is the memory space allocated in the heap memory to store the objects which are
created using String literals. String constant pool is unique, there are no two String o objects which
has the same value(content).
String constant pool increases the reusability of the existing String objects.
It also saves memory as no two objects with same content are created.
Q41 There are lot of String concatenation and String modification operations in my code.
Which class should I use among String,StringBuffer and StringBuilder? Given I also want
thread-safe code?
Advanced Level (8+ years)- Java String Interview Questions and Answers
One of the main reason to prefer char Array over String is security risk of stealing passwords. Since
String are reusable in the constant pool , there are high chances that they remain in the memory for the
long duration. Anyone who has access to the memory dump can find the password in clear text.
That's why password should be encrypted.
Q43 What is Character encoding? Explain the difference between UTF-16 and UTF-8?
When you want to represent Character using bytes, character encoding is used.
The UTF-16 uses 2 bytes or 16 bits to represent a character while UTF-8 uses 1 byte or 8 bits to
represent a character.
substring shares the same character array as String. It can lead to the memory leak if the original
String is quite big and not necessary to retain in the memory. It is unintentionally retained by
substring as substring is smaller in size.It results in the prevention of large array being garbage
collected.
Write a java program to check whether two given strings are anagram. If two strings contain same set
of characters but in different order then the two strings are called anagram.
Q47 Convert Lowercase to Uppercase in java and Uppercase to Lowercase without using built
in method ?
Write a java program to convert Lowercase to Uppercase and vice versa in a given String. [Solution]
If the original string is "Alive is awesome" and the user inputs string to remove "alwsr" then it
should print "ive i eome" as output .
If the original string is "Learning never stops" and the user inputs string to remove "estp" then
the it should print "Larning nvr o" as output .
That's it for today, if you find any new interview questions on String then please mention in the
comments, I will add it to the above post. Thanks for reading top 50 java string interview questions
and answers.
Q50 Find the length of the String without using length() method? [Solution]
Write a java program to find out the length of the String without using length() method.
Q1 What is an Array?
1. Array is a collection of similar data types. It can not have different data type. It can hold
both primitive types (int, float, double) and object references.
2. It is fixed in length i.e static in nature.
3. Arrays are created on the heap memory not on the stack.
4. Accessing an invalid index of an Array will cause exception.
You can not change the size of Array after creation. Although there are other data-structures which
can change size after creation.
No, you can not pass the negative number as Array size. If you pass a negative number in Array size
then you will not get the compiler error. Instead, you will get the NegativeArraySizeException at run
time.
No, you can not declare Array without Array size. You will get compile time error.
This is a follow-up question of Q7. An Array will always be an object on heap memory, even if the
Array is declared to hold primitive elements.
This exception is thrown to indicate that an attempt has been made to store the wrong type of object
into an array of objects. In other words, if you want to store the integer Object in an Array of String
you will get ArrayStoreException.
ArrayStoreException is thrown if you are trying to add incompatible data type. For example, if you
try to add an integer object to String Array, then ArrayStoreException is thrown.
ArrayOutOfBoundsException is thrown when an attempt is made to access the Array with illegal
index. For example, illegal index means if the index is either negative or greater than or equal to the
size of the Array.
b. Using index, we can access the element of the Array in O(1) time.
a. To create an Array, contiguous memory is required. It is possible in JVM that the memory is
available to accommodate Array but memory available is not contiguous.
b. The Array is static data structure. It is of fixed size. We can not increase or decrease the size of the
Array after creation.
An array without any name (or reference) is called an Anonymous Array. They are useful for the
scenarios where we need one time usage of Array. For example,
Output :
23 17 20 29 30
import java.util.*;
public class JavaHungry {
Output :
17 20 23 29 30
Q17 Write a program to check whether two given Arrays are equal, given both contains same
data type and same length ?
To check whether two given arrays are equal or not , we can use Arrays.equals() method. Check the
program below :
import java.util.*;
public class JavaHungry {
System.out.println(Arrays.equals(arr1 , arr2));
System.out.println(Arrays.equals(arr1 , arr3));
}
}
Output :
false
true
Both are legal statements. It is preferred to write int[] arr instead of int arr[].
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at JavaHungry.main(JavaHungry.java:8)
Output:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at JavaHungry.main(JavaHungry.java:6)
Array is static in size i.e of fixed length. Size can not be changed after declaration. ArrayList is
dynamic in nature. If you add elements to an ArrayList, it will automatically increase its size.
Array can contain both primitive and Object data types. ArrayList does not contain primitive data
types. It only contains object entries.
You can find the 8 difference between Array and ArrayList here.
Memory required for storing the same number of elements in Array is less as compared to LinkedList.
Array only stores the data of the element whereas LinkedList stores data plus the address of the next
node.
Array requires contiguous memory allocation where as LinkedList elements are present all over the
heap memory. Unlike Array, LinkedList does not have limitation of contiguous memory.
You can find more differences between Array and LinkedList here.
Q23 How to find the missing number in a given Array from number 1 to 100 ?
This question is a popular interview question. I have shared the code with explanation here.
Arrays containing arrays of different length is known as jagged arrays. Multidimensional arrays are
also known as jagged arrays. For example,
Q25 There are two arrays object one containing 100 elements and another containing 50
elements. Both are of same data type. Can we assign one Array to another Array.
Yes, an Array of 100 elements can be assigned to an Array of 50 elements in java. The only criteria is
that both arrays of same data type. It is because at the time of assigning the values compiler looks for
the data type of Array not the size of Array.
import java.util.*;
public class JavaHungry {
}
}
Output :
100
Q26 What are the different ways to copy one Array from another Array?
You can use binarySearch(int[], int) method. This method internally uses binary search algorithm.
It is prerequisite for binary search algorithm to have elements sorted. In the given example I have
taken an already sorted Array.
import java.util.*;
// Sorted Array
int[] arr1 = {1, 2, 3, 4};
Output :
1
Array will take default value depending upon the data type.
There are many ways by which you can find the duplicates in an Array. I am sharing two ways
a. using for loop and compare
b. using HashSet
import java.util.*;
}
}
}
}
}
Output:
Duplicate in Array is : java
Duplicate in Array is : javahungry
HashSet does not allow duplicate elements. You can traverse the array and insert each element into
the HashSet. Add elements using add() method. If it returns true then continue to traverse the array.
Otherwise if false then print out the duplicate value.
Output :
java javahungry
Q31 Is this a legal way to define arrays int[] arr = new int [4]{1, 2, 3, 4};
This is invalid way to initialize an Array in Java. You can not provide the size of the Array when you
are declaring the elements in it.
Yes, we can make an Array volatile. Only variable representing an Array can be made volatile.
a. Access operation : O(1) This means very fast given the index of the element.
b. Search operation : O(n) where n represents the number of elements in an Array.
c. Insertion operation : O(n) where n represents the number of elements in an Array.
b. Deletion operation : O(n) where n represents the number of elements in an Array.
Q37 Given two arrays, find the intersection between them? (solution)
Intersection means common elements. We need to find common elements between two given arrays.
For example :
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {2, 3, 4, 7, 8};
Output : 2, 3, 4
You can find the code here.
Q38 Find the missing number in an Array between 1 to 100. Given only one number is
missing. (solution)
This question is very popular among interviewers. It is one of the simplest question in Array topic.
This question is generally asked during telephonic interview or as a warm up question in face to face
round of interviews.
One of the ways to solve this problem is to calculate sum of all numbers from 1 to 100 then subtract it
from the sum of all the numbers in given array. Difference would be the missing number.
Logic to find the smallest and largest number in a given Array is given below :
import java.util.*;
// Given Array
int[] inputArr = {10,43,27,98,75,59,191};
Output :
Largest and Smallest numbers are 191 10
You will find this type of questions during telephonic round of interview or early rounds of face to
face interview. Make sure you go through this question before appearing for the interview.
Q41 Write a program to sum all the values of a given Array in java?
// Given Array
int[] inputArr = {10,43,27,98,75,59,191};
int sum = 0;
System.out.println(sum);
}
}
Output :
503
import java.util.*;
// Given Array
int[] inputArr = {0,10,43,27,0,98,75,59,191,0};
int counter = 0;
System.out.println(Arrays.toString(inputArr));
Output:
[10, 43, 27, 98, 75, 59, 191, 0, 0, 0]
Q44 How to convert Array to ArrayList in java ? (solution)
The easy way to convert Array to ArrayList is using Arrays class asList() method. You need to pass
the Array to the asList() method as argument. For example,
(Arrays.asList(cityNames));
There is another way to convert Array to ArrayList using addAll() method. For details check here.
To convert Array to TreeSet in java, first we need to convert Array to List using Arrays class asList()
method. After converting Array to List, pass the list object to TreeSet constructor. That's it , Array
has been converted to TreeSet. You can confirm by printing out the values of TreeSet object.
There are two ways to convert ArrayList to String Array in java. First method is using ArrayList get()
method and second is using toArray() method. You can check both of the methods here.
Q47 Write a program to find second largest element in a given Array in java?
The easiest way to solve this problem by using sorting. Sort the given Array and then iterate to the
second last element.
import java.util.*;
public class LargestSmallest
{
public static void main(String[] args)
{
// Given Array
int inputArray[] = new int[] {10,43,27,98,75,59,191};
// Sort Array
Arrays.sort(inputArray);
Output :
98
If desired value exists in the temp Array then below method will return true otherwise false. The
below program uses contains() method to check whether inputArray contains the desired element or
not.
import java.util.*;
System.out.println(isExist(inputArray,"B")); // true
System.out.println(isExist(inputArray,"G")); // false
Below java program uses equals() method to check whether inputArray contains the desired element.
import java.util.*;
System.out.println(isExist(temp,"B")); // true
System.out.println(isExist(temp,"G")); // false
Q49 Write a program to find the first repeating number in an integer Array?
a. Logic is declare a variable minimum. Iterate through the Array in reverse order i.e from last
element to first element. Add elements to the HashSet one by one.
b. If repeated value occurs then store the index of the repeated value to the minimum variable.
import java.util.*;
Output :
first repeating element is : 4
Q50 Write a program to find the first non-repeating number in an integer Array?
Compare one element with rest of the remaining elements. If value does not match then exit the
iteration and print the value.
Output :
4