Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Session 4 - String and Array

Uploaded by

Ayush Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Session 4 - String and Array

Uploaded by

Ayush Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

String Question and Answer

Q1. What is String?

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.

Q2 Is String immutable in java?

Yes, String class is immutable in java. Immutable means once the object is created, its value can not
be changed.

Q3 Is String a keyword in java ?

No, String is not a keyword in java.

Q4 How many objects are created using new keyword?


String str = new String("JavaHungry");

Two objects are created by the above statement. One object in the heap memory and one object in the
String constant pool.

Q5 Write a program to reverse a String in java ?

I have already shared how to reverse a String in java by 6 different ways. [Solution]

Q6 How to convert String to char Array?

You can convert String to char Array using toCharArray() method.

Q7 How many different ways you can create a String object?

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.

String str = "javahungry"; // String literal


String str = new String("javahungry"); // using new operator

Q8 Are String thread-safe in java?

As we know String objects are immutable. It means they are thread-safe also.

Q9 Which class is final among String, StringBuilder and StringBuffer?

All are final classes.

Q10 Is String primitive type or object (derived) type in java?

String is object(derived) type in java.

Q11 Can we use String in switch statement?

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]

Q13 What is the difference between String and StringBuffer in java?

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.

Q14 What is the difference between StringBuilder and StringBuffer in java?

Below are the main differences between StringBuilder and StringBuffer in java.

1. StringBuilder is not thread-safe. StringBuffer is thread-safe.


2. StringBuilder is not synchronized and StringBuffer is synchronized.
3. StringBuilder is faster while StringBuffer is slower as it is thread-safe.

Q15 Explain the difference between below statements:

String str = new String("abc");


String str = "abc";

In the first statement, String str = new String("abc");


JVM will create one object in the heap memory. Another object in the String constant pool, if the
object is not present. Otherwise,if present in the String constant pool ,it will return the reference to it.

In the second statement, String str = "abc";


JVM checks for the string "abc" in the String constant pool. If the string is not present in the constant
pool then it will create a new String object and stores it in pool.
If the string "abc" is found in string constant pool , then it simply creates a reference to it but does not
create a new object.

Q16 How many objects will be created for the following code:

String str1 = "abc";

String str2 = new String("abc");

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";

String str2 = "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:

String str1 = new String("abc");

String str2 = new String("abc");

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.

Hence , a total of 2+1 = 3 objects are created.

Q19 What is String intern() method?

According to Oracle docs,


When the intern method is invoked, if the String constant pool already contains a string equal to the
String object as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise the String object is added to the pool and a reference to the String object is returned.

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.

Q21 Why is String immutable in java ?

There are various reasons to make String immutable in java.


1. Security : String is made immutable to help increase the Security. Sensitive data like
username,password can be stored as the Strings can't be modified once created.

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.

You can check more here.

Q22 How will you create an immutable class in java?


You can create immutable class in java by implementing below points:

1. Make the class final so it can not be extended(inherited)


2. Make all fields private so one can not access them from outside the class.
3. Do not provide setter methods for the variables.
4. Declare all mutable fields as final so that it's value can be assigned only once.

Q23 How will you create mutable String objects in java?

As we have discussed, by using StringBuffer and StringBuilder objects.

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().

Q25 Why String is mostly used as a key in HashMap class?

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.

Q26 Is it possible to call String class methods using String literals?

Yes, It is possible to call String class methods using String literals. For example

"javahungry".indexOf(u)
"javahungry".charAt(0)
"javahungry".compareTo("javahungry")

Q27 How to Split String in java?

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.

Q29 How do you compare two Strings in Java?

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.

String str1 = "abc";

String str2 = new String("abc");

System.out.println(str1 == str2); //false


System.out.println(str1.equals(str2)); //true

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.

Q31 Find out if String has all Unique Characters? [Solution]

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.

Q32 How to Count number of words in the String? [Solution]

This is an important phone interview coding question. Write a java program to count number of words
in the String.

Q33 How to remove all the white-spaces in the String? [Solution]

Write a java program to remove all the white-spaces in the String.

Q34 Print all permutations of 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]

Q35 How to calculate total number of characters in the String?

Write a java program to calculate total number of characters in the String .[Solution]

Q36 How to calculate total number of vowels in String?[Solution]

Write a java program to calculate total number of vowels in String .


for example :
if the original string : " Alive is awesome "
then the number of vowels is : 8

Q37 String concatenation in java?[Solution]

Write different ways for String concatenation in java?


Input: “Java” and “Hungry”
Output: “JavaHungry”

Input: “1234” and “5678”


Output: “12345678”

Q38 Find all possible combinations of String?

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]

Q39 Write a java program to check if the input string is palindrome?


I have already shared the code to check whether input string is palindrome or not. [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).

Why String Constant Pool ?

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?

This is scenario based question. You should give answer StringBuffer.


You can use String also but with every modification and concatenation operation, a new String is
formed as String is immutable. It will lead to the memory allocation issues.
StringBuilder can not be used as it is not synchronized, i.e thread-safe.

So, the clear answer is StringBuffer.

Advanced Level (8+ years)- Java String Interview Questions and Answers

Q42 Why char Array is preferred over String in storing passwords?

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.

Q44 How does substring() method works in java?

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.

Q45 Anagram program in java? [Solution]

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.

Q46 How to Count occurrences of each character in a String in java?[Solution]


Write a java program to count occurrences of each character in String in java. If the String is
"Java Hungry" then the answer should be
{ =1, a=2, r=1, u=1, v=1, g=1, H=1, y=1, J=1, n=1}

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]

Q48 How to remove specific characters in the String? [Solution]

To remove specific characters in the String .For example,

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 .

Q49 How to Convert Signed Integer to String? [Solution]

Here to convert signed int to string in java, two case arises :

1. If number is positive (+ve) :

Input : 84 Output : "84"

2. If number is negative (-ve)


Input : -84 Output : "-84"

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.

Q2 How do you declare an Array in java?

You can declare an Array in java by the following way :

dataType[] arrayVariableName = new dataType[arraySize];


for example for int data type, you can declare an int array as :

int[] temp = new int[256]

Q3 What is the default value of Array for different data types?

Data Type Default value


byte, short, int, long 0
float, double 0.0
boolean false
Any object null

Q4 Can you change size of Array in java after creation?

You can not change the size of Array after creation. Although there are other data-structures which
can change size after creation.

Q5 Can you pass the negative number in Array size?

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.

Q6 Can you declare an Array without Array size?

No, you can not declare Array without Array size. You will get compile time error.

Q7 Where does Array stored in JVM memory ?

Array is an object in java. So, Array is stored in heap memory in JVM.

Q8 Given a primitive Array in java, where does in JVM it is stored?

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.

Q9 What is ArrayStoreException ? When this exception is thrown ?

According to Oracle docs,


ArrayStoreException is a runtime exception. Array must contain the same data type 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.

The following code throws ArrayStoreException :

public class JavaHungry {

public static void main(String args[]) {

Object x[] = new String[3];


x[0] = new Integer(0);
}
}

Q10 What is the difference between ArrayStoreException and ArrayOutOfBoundsException ?

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.

Q11 What are the advantages of Array ?

a. We can sort multiple elements of Array at the same time.

b. Using index, we can access the element of the Array in O(1) time.

Q12 What are the disadvantages of Array?

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.

Q13 Can we use Generics with an Array?

No, we can not use generics with an Array.

Q14 What is an Anonymous Array in Java ? Give example?

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,

Anonymous int array :


new int[] {2,3,4,5,6,7};

Anonymous String array :


new String[]{"Java", "Hungry"};

Q15 Write a program to print elements of Array ?

public class JavaHungry {

public static void main(String args[]) {

int[] rollNumber = { 23, 17, 20, 29, 30 };


for (int temp : rollNumber)
System.out.print(temp+" ");
}
}

Output :
23 17 20 29 30

Q16 Write a program to sort an Array in Java ?


You do not need to write quick sort or merge sort algorithm in order to sort an Array. You can sort an
Array by using Arrays.sort() method. Check out the program below :

import java.util.*;
public class JavaHungry {

public static void main(String args[]) {

int[] rollNumber = { 23, 17, 20, 29, 30 };


Arrays.sort(rollNumber);
for (int temp : rollNumber)
System.out.print(temp+" ");
}
}

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 {

public static void main(String args[]) {

int[] arr1 = {2, 3, 4};


int[] arr2 = {1, 2, 3};

System.out.println(Arrays.equals(arr1 , arr2));

int[] arr3 = {2, 3, 4};

System.out.println(Arrays.equals(arr1 , arr3));
}
}

Output :
false
true

Q18 Which is legal int[] arr or int arr[] ?

Both are legal statements. It is preferred to write int[] arr instead of int arr[].

Q19 Write a program to throw ArrayOutOfBoundsException?

public class JavaHungry {

public static void main(String args[]) {

int[] rollNumber = { 23, 17, 20, 29, 30 };


/* Index below is greater than the size
of the given Array */
int element = rollNumber[6];
for (int temp : rollNumber)
System.out.print(temp+" ");
}
}

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at JavaHungry.main(JavaHungry.java:8)

Q20 Write a program to throw ArrayStoreException ?

public class JavaHungry {


public static void main(String args[]) {

Object x[] = new String[3];


x[0] = new Integer(0);
}
}

Output:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at JavaHungry.main(JavaHungry.java:6)

Q21 What is the difference between Array and ArrayList ?

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.

Q22 What is the difference between Array and LinkedList in java ?

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.

Q24 What are jagged arrays in java?

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 {

public static void main(String args[]) {

int[] arr1 = new int[50];


int[] arr2 = new int[100];
arr1 = arr2;
System.out.println(arr1.length);

}
}

Output :
100

Q26 What are the different ways to copy one Array from another Array?

There are four ways by which we can copy an Array.

a. By using for loop


b. By using clone() method
c. By using Arrays.copyOf() method
d. By using System.arraycopy() method

Q27 Write a program to search a specific element in an 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.*;

public class JavaHungry {

public static void main(String args[]) {

// Sorted Array
int[] arr1 = {1, 2, 3, 4};

/* if element present in Array, binarySearch()


method will return index */
System.out.println(Arrays.binarySearch(arr1, 2));
}
}

Output :
1

Q28 What will happen if you do not initialize an Array?

Array will take default value depending upon the data type.

Q29 How to find duplicate elements in a given Array?

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.*;

public class JavaHungry {

public static void main(String args[]) {

String[] arr1 = {"abc", "java", "javahungry", "java", "javahungry" };

for(int i=0; i < arr1.length-1; i++){


for(int j=i+1; j < arr1.length; j++) {

if(arr1[i].equals(arr1[j]) && i!=j ) {


System.out.println("Duplicate in Array is : "+ arr1[j]);

}
}
}
}
}

Output:
Duplicate in Array is : java
Duplicate in Array is : javahungry

Time Complexity O(n^2) i.e quadratic.

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.

public class JavaHungry {

public static void main(String args[]) {


String[] arr1 = {"abc", "java", "javahungry", "java", "javahungry" };
HashSet<String> set = new HashSet<String>();

for (String val : arr1)


{
if (set.add(val) == false){
System.out.print (val+" ");
}
}
}
}

Output :
java javahungry

Time Complexity O(n)

Q30 What are the different ways to traverse an Array in java?

a. Using for loop


b. Using for each loop

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.

Q32 What is two dimensional Array in java?

An Array of an Array in java is called as two dimensional Array.

Q33 How do you declare a two dimensional Array in java?

int[][] arr = new int[4][4];


The above statement will create a 4 x 4 matrix.

Q34 Can we make Array volatile using volatile keyword?

Yes, we can make an Array volatile. Only variable representing an Array can be made volatile.

Q35 Are Array thread-safe ?

Reading an Array is a thread-safe operation but modifications are not.

Q36 What is the time complexity O(n) of different operations of an Array?

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.

Q39 Find out smallest and largest number in a given Array?

Logic to find the smallest and largest number in a given Array is given below :

a. Create two variables for storing largest and smallest number.


b. Initialize smallest variable with value Integer.MAX_VALUE
c. Initialize largest variable with value Integer.MIN_VALUE
d. In each traversal of for loop, we will compare the current element with the largest and smallest
number. We will update the value.
e. If a number is larger than largest, then it can not be smaller than the smallest. So we can skip if first
condition is true.

import java.util.*;

public class JavaHungry {


public static void main(String args[]) {

// Given Array
int[] inputArr = {10,43,27,98,75,59,191};

// Setting largest value


int largest = inputArr[0];

// Setting smallest value


int smallest = inputArr[0];

// Iterate through the Given Array


for( int number : inputArr ) {
if(number > largest) {
largest = number;
}
else if (smallest > number) {
smallest = number;
}
}
System.out.println("Largest and Smallest numbers are "
+ largest +" "+smallest);
}
}

Output :
Largest and Smallest numbers are 191 10

Q40 How to reverse an Array in java ? (solution)

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?

public class JavaHungry {

public static void main(String args[]) {

// Given Array
int[] inputArr = {10,43,27,98,75,59,191};

int sum = 0;

//Iterating through the Array


for(int num : inputArr) {
sum = sum + num;
}

System.out.println(sum);

}
}

Output :
503

Q42 How to convert HashSet to Array in java ? (solution)

You can convert HashSet to Array using toArray() method.


Q43 How do you separate zeros and non-zeros in a given Array in java?

Logic to separate zeros and non-zeros is given below :

a. Initialize variable counter to 0.


b. Iterating inputArr from left to right. If inputArr[i] is not zero then assign inputArr[i] to
inputArr[counter].
c. Increment the counter by 1.
d. Assign the remaining elements with 0 value.

import java.util.*;

public class JavaHungry {

public static void main(String args[]) {

// Given Array
int[] inputArr = {0,10,43,27,0,98,75,59,191,0};

int counter = 0;

//Iterating through the Array

for(int i=0;i < inputArr.length;i++) {


if(inputArr[i] != 0) {
inputArr[counter] = inputArr[i];
counter++;
}
}

while (counter < inputArr.length) {


inputArr[counter] = 0;
counter++;
}

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,

String[] cityNames ={"Boston", "Chicago", "San Francisco", "New York"};


/* One liner - Array to ArrayList conversion*/
ArrayList<String> cityList= new ArrayList<String>

(Arrays.asList(cityNames));

There is another way to convert Array to ArrayList using addAll() method. For details check here.

Q45 How to convert Array to TreeSet in java ? (solution)

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.

Q46 How to convert ArrayList to String Array in java ? (solution)

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);

// Iterate Array to Second last element

for(int i=0; i < inputArray.length; i++) {


// Print second last element
if(i == inputArray.length- 2)
System.out.println(inputArray[i]);
}
}
}

Output :
98

Q48 How to check if Array contains the desired value or not ?

Suppose we have a String Array temp.


String[] temp = new String[]{"D","H","B","R"};

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.*;

public class JavaHungry {

public static void main(String args[]) {


String[] inputArray = new String[]{"D","H","B","R"};

System.out.println(isExist(inputArray,"B")); // true

System.out.println(isExist(inputArray,"G")); // false

public static boolean isExist(final String[] array, final String obj) {


return Arrays.asList(array).contains(obj);
}
}

Below java program uses equals() method to check whether inputArray contains the desired element.

import java.util.*;

public class JavaHungry {

public static void main(String args[]) {

String[] temp = new String[]{"D","H","B","R"};

System.out.println(isExist(temp,"B")); // true
System.out.println(isExist(temp,"G")); // false

public static boolean isExist(final String[] array, final String obj) {


for (String str : array) {
if(str.equals(obj))
return true;
}
return 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.*;

public class FirstRepeating {

public static void main(String args[]) {

int[] arr = new int[]{1,2,3,4,5,7,4,9};


firstRepeating(arr);
}

public static void firstRepeating(int[] arr) {

int minimum = -1;


HashSet set = new HashSet();
for (int i = arr.length-1 ;i >=0 ;i--) {
if(set.contains(arr[i]))
minimum = i;
else
set.add(arr[i]);
}
if(minimum != -1){
System.out.println("first repeating element is : "+ arr[minimum]);
}
}
}

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.

public class FirstNonRepeating {

public static void main(String args[]) {

int[] arr = new int[]{1,2,3,4,5,1,2,3,5,9};


System.out.println(firstNonRepeating(arr,arr.length));
}

public static int firstNonRepeating(int[] arr, int length) {


int j;
for (int i=0; i < length ;i++) {
for(j=0; j < length ;j++) {
if (arr[i]==arr[j] && i!=j) {
break;
}
}
if (j == length)
return arr[i];
}
return -1;
}
}

Output :
4

You might also like