COREJAVA

  

1.What is the difference b/w JVM,JRE and JDK?

JVM(Java Virtual Machine) is used for executing byte code i.e after compilation of any java file .class file will be generated which contains byte code.Now this byte code can be understandable by JVM and it provides runtime environment to execute the byte code.So JVM converts byte to machine code.Java is a Platform independent where as JVM is a platform dependent.

JRE(Java Runtime Environment) consists of JVM,Set of libraries and other files to execute the java files.

JDK(Java Development Kit) contains tools such as java compiler, java application launcher etc.If we want to write a java programs and to compile them JDK is required. But if we want to run the java programs then JRE is enough.

2.Any modifications are possible for public static void main(String args[]) statement?

Yes.We can do below modifications for public static void main(String args[])
  • instead of public static we can also use as static public.

  • instead of args variable we can use any variable.

3.Without public static void main(String args[]),can we compile the program and run the program ?

Yes we can compile, but we cannot run the program.


4.what is the extra operator introduced in java,which is not there in c and c++?

instanceof operator


This operator is used for checking either particular object is belongs to class or not.If the object is belongs to class,then it will return true otherwise it will return false.


ex:
boolean flag=emp instanceof Employee.

Here if emp object is belongs to Employee class,then flag value is true otherwise flag value is false.


5.what is the difference b/w & and && ?

& is a bitwise operator and && is a logical operator.single ampersand(&) always evaluates both arguments whereas the double ampersand(&&) will only evaluate the second argument if the first argument is true.

6.Program for swapping of two numbers without using third variable ?


public class SwapDemo {

public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before Swapping:" + a + " " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("Before Swapping:" + a + " " + b);
}
}

or


public class SwapDemo {

public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before Swapping:" + a + " " + b);
a=a^b;
b=a^b;
a=a^b;
System.out.println("Before Swapping:" + a + " " + b);
}

}


7.what is the output of the following program?


public class Check {
public static void main(String[] args) {
int x = 100;
if (x = 100) {
System.out.println("hii...");
} else {
System.out.println("hello..");
}
}
}

Ans:
There is compilation error at if condition.Because we have used = for comparing x with 100.So instead of comparing it will assigns the 100 to x.If it is c and c++,then condition becomes true.Because any non zero value in c,c++ is treated as true.But in java this is illegal.So we will get compilation error.

8.Program to sort an array of elements?


without using collections:

public class SortingDemo {
public static void sortArray(int array[]) {
for (int i = 0;i<array.length;i++)
{
for (int j = i + 1;j<array.length;j++)
{
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("==sorted elements are==");
for (int i = 0;i<array.length;i++)
System.out.println(array[i]);
}
public static void main(String[] args) {
int a[] = { 100, 67, 23, 89, 3, 5 };
sortArray(a);
}
}


with collections:

import java.util.TreeSet;

public class Sort {
public static void sortArray(int array[]) {
TreeSet ts = new TreeSet();
for (int i = 0;i<array.length;i++)
{
ts.add(array[i]);
}
System.out.println("sorted elements:");
System.out.println(ts);
}
public static void main(String[] args) {
int a[] = { 100, 67, 23, 89, 3, 5 };
sortArray(a);
}

}

9.Program to find biggest element in array?

public class BiggestDemo {
public static void findBiggest(int ar[]) {
int big = ar[0];
for (int i = 0; i if (ar[i] > big) {
big = ar[i];
}
}
System.out.println("biggest is:" + big);

}

public static void main(String[] args) {
int a[] = { 34, 234, 3, 67, 567, 89, 12, 34 };
findBiggest(a);
}
}


10.Program to find sum of max two numbers in the array?

public class FindSumOfMaxTwo {
public static int findSum(int ar[]) {
int firstBig = ar[0];
int secondBig = 0;
for (int i = 0; i if (ar[i] > firstBig) {
secondBig = firstBig;
firstBig = ar[i];
} else if (ar[i] > secondBig) {
secondBig = ar[i];
}
}
return (firstBig + secondBig);
}

public static void main(String[] args) {
int a[] = { 40, 2, 3, 46, 12 };
System.out.println("sum of max two: " + findSum(a));
}
}

11.Program to find pairs of numbers in the array whose sum is equals to given number?


Program WithOut Collections :-

public class FindPairs 
{
public static void main(String[] args) {
int num[]={1,6,2,3,8,4,5,2};
int sum=7;
for(int i=0;i<num.length;i++) {
int first=num[i];
for(int j=i+1;j<num.length;j++) {
int second=num[j];
if((sum==(first+second)))
{
System.out.println("Pair is:"+"("+first+":"+second+")");
}
}
}
}
}

(OR)


Program With Collections:-


import java.util.HashSet;
import java.util.Set;

public class FindPairs{
public static void main(String args[])
{
int arr[]={1,6,2,3,8,4,5,2};
int sum=7; 
Set set=new HashSet();
for(int value:arr)
{
int target=sum-value;

if(!set.contains(target))
{
set.add(value);
}
else
{
System.out.println("Pair is:"+"("+value+":"+target+")");
}
}
}
}


12.What is the difference between creating a String object using = operator and using new operator?

If we create a String object using = operator then String obect will store in string pool with the given content.Here if we create another string object using = operator with same content then same memory location will allocated for the second object also.
If we create a String object using new operator then string object will store in heap with the given content.Here if we create another string using new operator with same content then different memory location will be allocated for the second object.
Consider the below example:

String s1=”hi”;
String s2=new String(“hi”);
String s3=”hi”;
String s4=new String(“hi”);

So now

If(s1==s2) is false.
If(s1==s3) is true
If(s2==s4) is false.
i.e if we use == operator for comparing strings ,then it will compare the memory locations instead of contents.So for comparing the contents we need to use equals() method of String class.
If(s1.equals(s2)) is true.



String interview Questions


1.what is string?

String is group of charecters which is enclosed within double quotes.
ex:
"rama","123","java"

int,float,char,double etc are treated as primitive datatypes but String is not a primitive datatype.It is a derived datatype.
String is not a keyword but it is a Predefined class belongs to java.lang package.

2.In how many ways we can create a string in java?

We can create a string in three ways.
->directly we can assign string litteral to the string object.
String str="hello";
->we can create a string by using new operator.
String str1=new String("hello");
->create a array,then convert into a string.
char ch[]={'h','e','l','l','o'};
String str2=new String(ch);

3.what is the difference between create a string using = operator and new operator?


String str="hello"
In the above case String object str will be created in String constant pool.
String str=new String("hello");
In the above case String object str will be created in Heap.

Whenever we create a string object using string literal, that object is stored in the string constant pool and whenever we create a string object using new keyword, that object is stored in the heap memory.

When we create a string object using string literal,then JVM first checks the content of to be created object. If there exist an object in the pool with the same content, then it returns the reference of that object. It doesn’t create new object. If the content is different from the existing objects then only it creates new object.

But, when we create string objects using new keyword, a new object is created whether the content is same or not.

4.what is the output of below program?

class EqualsCheck
{
public static void main(String args[])
{
String s1="hi";
String s2="hi";
System.out.println(s1==s1); //true
//here s1 object will store in string pool.s2 object content also same as s1 so same reference will be returned to s2.
String s3=new String("hello");
String s4=new String("hello");
System.out.println(s3==s4); //false
//here s3 object will store in heap.though s4 object content is same as s3,but it contains difference reference.
}
}

5.what is the difference between == operator and equals() method?

if we used == operator for comparing two string objects then it wont compare the contents of string objects just it will compare the references of string objects.
if we used equals() method of String class for comparing two string objects then it will compare the contents of string objects but not references.

String s3=new String("hello");
String s4=new String("hello");
System.out.println(s3==s4); //false-reference check
System.out.println(s3.equals(s4)); //true-content check

6.what is immutable and mutable objects?

immutable objects are those whose content cannot be changed or modified once object is created.
ex: String and wrapper class(Integer,Byte,Doutble etc) objects.

mutable object are those whose content can be changed or modified once object is created.
ex:StringBuffer class objects

7.why String class is declared as final and immutable?


->If String class is not declared as final,then its not possible to maintain string pool.
for exampe: 
String s1="hi";
String s2="hi";

Now if we call s2.toUpperCase() ,then Both the objects s1 and s2 will change to HI .
So if one object changes the value ,other objects also will get affected.

->for security reasons i.e we can open the file in java by passing name of the file as argument to the File I/O Classes.
if String is not immutable then anyone can access the file and they can change the file name and get the access to the file.
->By declaring String class as final ,no one can overrides any behaviour of String class.
->Since String objects are immutable,So that it can be used in multi threaded environment.again no need of external synchronization.
->Since String objects are immutable ,so that it can be used in class loading mechanism.If String objects are mutable,then if we loading java.io.Writter could have been changed to "com.xyz.ChangeWriter" .
->We can use String as parameter while fetching database connection like driver name,username,password,url etc.

8)is there any way to send string object from heap to pool?

Yes.If we create a string object using new operator then it will store in heap.By using intern() method of String class it will moved to pool.
Ex:
String s1=”hi”;
String s2=new String(“hi”);
s2=s2.intern();
Now if(s1==s2) returns true.

9)what is the difference between String and StringBuffer?

String class objects are immutable i.e once objects are created
we cannot change or modify the contents.But StringBuffer objects
are mutable i.e we can change or modify contents of
StringBuffer class objects.

10)what is the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder classes are mutable objects.
But difference is StringBuffer class is thread safe where as StringBuiler is not thread safe.


11)How to remove character from string?

public class RemoveChar {
public static void main(String[] args) {
String str="helloojava";
char c='o';//character o needs to remove
String newStr=removeCharacter(str,c);
System.out.println("origianl string:"+str);
System.out.println("new string:"+newStr);
}

private static String removeCharacter(String str, char c) {
if(str==null)
return null;
else
return str.replaceAll(Character.toString(c),"");
}
}

12)Program to count occurrence of each character in String?

import java.util.HashMap;
import java.util.Map;

public class CountChars {
public static void main(String[] args) {
String str1="welcometojava";
String str2="javaissimple";
System.out.println("first string");
Map count1=countchars(str1);
System.out.println(count1);
System.out.println("second string");
Map count2=countchars(str2);
System.out.println(count2);
}

private static Map countchars(String str) {
//create map object to store characters with count
HashMap countMap=new HashMap();
//converting string to char array
char ch[]=str.toCharArray();
//iterate the array
for(char c:ch)
{
if(countMap.containsKey(c))
{
//If char is present in charCountMap, incrementing it's count by 1
countMap.put(c,countMap.get(c)+1);
}
else
{
//If char is not present in charCountMap,
//putting this char to charCountMap with 1 as it's value 
countMap.put(c,1);
}
}
return countMap;
}
}


13)Program to remove white spaces in string?

public class RemoveSpaces {
public static void main(String[] args) {
String s="java is a programming language";
//first way
String withoutSpace=s.replaceAll("\\s","");
System.out.println(withoutSpace);
//second way
char ch[]=s.toCharArray();
StringBuffer sb=new StringBuffer();
for(char c:ch)
{
if((c!=' ')&&(c!='\t'))
{
sb.append(c);
}
}
System.out.println(sb);
}
}


14)Write a program to check given String is pallindrom or not?


public class PallindromCheck {
public static void main(String args[]) {
String original = "malayalam";
String reverse = "";

for (int i = original.length() - 1; i >= 0; i--) {
reverse = reverse + original.charAt(i);
}
System.out.println("reverse is:" + reverse);
if (original.equals(reverse))
System.out.println("pallindrom");
else
System.out.println("not pallindrom");
}
}


                                                   OOPS


1.what are the important features of OOPS?

Generally we have two types of Programming Languges are there.

1.POPL--Procedural Oriented Programming Language.(example:C Langauge)
2.OOPL--Object oriented Programming Langaure.(example:C++,JAVA,.NET etc)


Following are important features of OOPS.

Abstraction
Encapsulation
Inheritance
Polymoprhism


2.what is abstraction?

It is the mechanism of showing the essential details by hidinng the background details.
For example whenever we started a car,we don't know internal mechanism how start button is working.We only know how to start the car with start button.


3.what is encapsulation?

It is the process of binding data members and its methods in a single unit.This can be achieved using class.We can control the access of data members of a class with the help of access specifiers i.e private,default,protected and public.
If we declare any data members as private,then no other classes can access them directly,but they can access with public getter methods indirectly.

4.what is inheritance?

it is the mechanism of re-using the properties(datamembers and methods) from one class to another class.The class which is providing the properties is called as base/parent/super class and the class which taking properties is called as derived/child/sub class.
The advantage of inheritance is re-usability of the class.
We can achieve Inheritance in java using extends keyword.

ex:

class A
{
int x=10;
void m1()
{
System.out.println("x is:"+x);
}
}
class B extends A
{
int y=20;
void m2()
{
System.out.println("y is:"+y);
}
}
class TestInh
{
 public static void main(String args[])
 {
 B b=new B();
 b.m1();
 b.m2();
 }
}

Notes:
-----
In the above example A is base class and B is derived class.
We used extends keyword to inherit the properties from Base class A to derived class B.
So finally after inheritance B class contains two variables(x,y) and two methods(m1,m2).
In inheritance mechanism we always created an object for bottom most(here B) derived class.Because all the properties of base class are avaialable to derived class.but not vice versa.
In java for all the classes Object is the base class.


5.Why java does not support multiple inheritance?

multiple inheritance is nothing but,single derived class can extends more than one base class.Java does not support multiple inheritance in java through classes,but it is achived through interfaces.This is due to diamond problem.
Consider below example to understand diamond problem.


class A
{}
class B extends A
{}
class C extends A
{}
class D extends B,D
{}

Here A is base/super class for B,C and D is derived/sub class for B,C.In this case if any method is inherited from Base class A,then Derived class D will face ambiguity problem i.e from which class i.e B or C ,it shold override that method.To avoid this problem java does not support multple inheritance.


6.what is polymorphism?

Polymorphism is the way of representing one thing in many forms.for example by using add() method we can perform sum of two integers and sum of two floats also.

We have two types of polymorphisms.

1.compiletime polymorphism.
2.runtime polymorphism.

compiletime polymorphism:

In compiletime polymorphism method body is binds with method call at compile time.

ex: method overloading

runtime polymorphism:

In runtime polymorphism method body is binds with method call at run time.

ex: method overriding

7.what is method overloading?

Writing two or more methods with the same name and with different signature is called method overloading.

here signature represents.
1.method name is same ,where as number of parameters may be differ.
2.method name is same ,where as type of parameters may be differ.
3.method name is same ,where as order or sequence of parameters may be differ.

8.what is the output of below program?

class Sample {
void show(Object obj) {
System.out.println("in show:Object");
}
}

public class OverloadTest {
public static void main(String[] args) {
Sample s = new Sample();
s.show(10);//show(Object obj) called
s.show("rama");//show(Object obj) called
s.show(4.5);//show(Object obj) called
}
}

Ans:
in show:Object
in show:Object
in show:Object

So here Object is the base class for all the classes in java.So show(Object obj) is called three times for int,String and double data.


9.what is the output of below program?


class Sample {
void show(Object obj) {
System.out.println("in show:Object");
}
void show(String obj) {
System.out.println("in show:String");
}
void show(int x)
{
System.out.println("in show:int");
}
}
public class OverloadDemo {
public static void main(String[] args) {
Sample s = new Sample();
s.show(10);//show(int x) called
s.show("rama");//show(String obj) called
s.show(4.5);//show(Object obj) called
}
}



Ans:

in show:int
in show:String
in show:Object

So here first specific data type i.e int ,String will be called ,if there is no specific data type then Object will be called.


10.shall we change the returntype in overloading?

Yes.We can change the return type of the overloaded methods.But arguments shold be different.

For example following code will give compilation error "Duplicate method show()"

class Test
{
void show(int x)
{
}
int show(int x)
{

return 0;
}
}

But following code will compile without any errors.Here argument type is changed.(not a matter in method overloadind).But arguments shold be diffrent.

class Test
{
void show(int x)
{
}
int show(float x)
{
return 0;
}
}


11.can we overload main() method?


We know java program execution starts from main() method and this method is called by JVM.

below is the signature of main() method.

public static void main(String args[])

So main() is a static method and in java static methods can be overloaded.So we can overload main() method.But while executing JVM will call only
public static void main(String args[]).Remaining methods needs to be called explicitly.

Example:


public class OverloadTest {
public static void main(String[] args) {
System.out.println("in main:String[]");
int array[]={1,2,3,4};
main(array);//explicitly calling main method with int array as argument
}
public static void main(int[] args) {
System.out.println("in main:int[]");
}
}

Output:
in main:String[]
in main:int[]


12.what is method overriding?

method overriding is the mechanism of wiring two or more methods with same name and same signature(including returntype) in base class and derived class too.

consider below example:

class Base
{
void show()
{
System.out.println("base:show");
}
}
class Derived extends Base
{
void show()
{
System.out.println("derived:show");
}
}
public class OverrideTest {
public static void main(String[] args) {
Derived d=new Derived();
d.show();
}
}

Output:
derived:show

So here base class show() method is overriden by derived class show() method.
In this case if we want to call base class show() method also then we can use super keyword in derived class as show below.

class Derived extends Base
{
void show()
{
super.show();//calls base class show method
System.out.println("derived:show");
}
}


13.Any compilation errors in below code?


class Base
{
void show()
{
System.out.println("base:show");
}
}
class Derived extends Base
{
private void show() //compilation error--cannot reduce the visibility of inherited method from Base
{
System.out.println("derived:show");
}
}

Ans:
There is a compilation error at Derived class show() method.Because we cannot reduce the visibility.Here Base class show() method is declared with default access specifier and Derived class show() method id declared with private access specifier.Since private has less visibility than default.So we got error.

for example if we declare base class show() method with private,then no error.
or
   if we declare derived class show() method defaut(this is default access specifier),protected or public ,then no error.


14.Any compilation errors in below code?


import java.io.IOException;

class Base
{
void show() throws IOException
{
System.out.println("base:show");
}
}
class Derived extends Base
{
void show() throws Exception //compilation error
{
System.out.println("derived:show");
}
}

Because Overriding method cannot throw higher exception than overriden method.Below code will compile without any errors.

import java.io.IOException;

class Base
{
void show() throws Exception
{
System.out.println("base:show");
}
}
class Derived extends Base
{
void show() throws IOException
{
System.out.println("derived:show");
}
}

This rule is only for checked exceptions.


15.Can we override static method?

Overriding is an example of runtime polymorphism i.e method binding will happen at runtime.But static method bonded at compiletime.So it is not possible to override static method.

for example below code will give compilation error.


class Base
{
static void show() 
{
System.out.println("base:show");
}
}
class Derived extends Base
{
void show()  //compilor error-instance method cannot override static method
{
System.out.println("derived:show");
}
}

But we can define same static method with same signature in derived class also.This is called method hidning.

for example:

class Base
{
static void show() 
{
System.out.println("base:show");
}
}
class Derived extends Base
{
static void show()  
{
System.out.println("derived:show");
}
}

output:
derived:show

16.Can we override private method?

No.private methods and private datamembers are accessable only with in the same class.But these are not visbile to outside the class.So they are not avialble to subclass.

17.Can we override final method?

No.Its not possible to override final methods.If we try to override,we will get compilation error.

18.Can we change the arguments list and return type in method overriding in subclass?
No.We cannnot change the returntype and argument list in subclass while overriding.But from java 5, new feature intriduced i.e co-variant retuntype.

co-variant returntype means overriden method can use return type as subclass of returntype of original method.

To understand better,consider below example:

class Base
{
Object show() 
{
System.out.println("base:show");
return null;
}
}
class Derived extends Base
{
String show()  
{
System.out.println("derived:show");
return null;
}
}

Above code will compile without any errors.Becaise String is subclass of Object.We can use subclass as returntype.








Collection Framework




1.What is Collection Framework?

The Java Collections Framework is a group of interfaces and classes which helps in storing and processing the data efficiently.
All the classes and interfaces of Collection Framework is implemented in java.util package.

2.List out few important classes and interfaces in collection framework?

interfaces:
----------
Collection
List
Set
Map
Queue

classes:
-------
ArrayList
Vector
LinkedList
HashSet
LinkedHashSet
TreeSet
HashMap
Hashtable
LinkedHashMap
TreeMap
PriorityQueue


Still we have another classes and interfaces are there in collection framework.

3.what is the base interface in Collection Framework?

Collection inteface is base interface in Collection Framework and it is belongs to java.util package.
Collection inteface extends Iterable interface.(Iterable interface is belongs to java.lang package)

4.What is the difference between Collection and Collections?

Collection is root interface in the collection hierarchy.This means that every single class implementing Collection in any form is part of the Java Collections Framework.

Collections is merely an utility method class for doing certain operations.
for example adding thread safety to your ArrayList instance by doing this:

List list = Collections.synchronizedList(new Arraylist());

The main difference is that Collection is base interface which you may use in your code as a type for object (although I wouldn't directly recommend that) while Collections just provides useful operations for handling the collections.

5.What are implemented classes for List,Set,Map interfaces?

 List interface implemented classes:
ArrayList,Vector,LinkedList

Set inteface implemented classes:
HashSet,TreeSet,LinkedHashSet

Map interface implemented classes:
HashMap,Hashtable,TreeMap,LinkedHashMap

6.What are the collection classes are thread safe or synchronized?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe). 

7.What is difference between Arrays and ArrayList ? 

Arrays are created of fix size whereas ArrayList is of not fix size. 

ex:
int array[]= new int[10]; 
array[11] // will give ArraysOutOfBoundException. 
Also the size of array cannot be incremented or decremented.


But with arrayList the size is variable. 
Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at 
runtime. 

ex:
List list = new ArrayList(); 
list.add(1); 
list.add(3); 
list.remove(0) // will remove the element from the 1st location.

ArrayList is one dimensional but array can be multidimensional. 
int[][][] intArray= new int[3][2][1]; // 3 dimensional array 


8.What is the difference between ArrayList and Vector?


1.ArrayList is not synchronized and Vector is synchronized.So ArrayList is faster than Vector.
2.ArrayList uses Iterator interface to traverse the elements.Vector uses Enumeration interface to traverse the elements. 
But it can use Iterator also.

9.When to use ArrayList and LinkedList?

LinkedList is fast for adding and deleting elements, but slow to access a specific element.
ArrayList is fast for accessing a specific element but can be slow to add to either end, and especially slow to delete in the middle.
insert and remove operations give good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Hence if there is a requirement
of frequent addition and deletion in application then LinkedList is a best choice.
Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so If there are less add and remove 
operations and more search operations requirement, ArrayList would be your best bet.


10.What is the difference between ArrayList and LinkedList?

-->
ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n).
Because ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list.On the other side LinkedList implements doubly linked list which requires the traversal 
through all the elements for searching an element. 

-->
LinkedList remove operation gives O(1) performance while ArrayList gives variable performance: O(n) in worst case (while removing first element)
and O(1) in best case (While removing last element).LinkedList element deletion is faster compared to ArrayList.
Because LinkedList’s each element maintains two pointers (addresses) which points to the both neighbor elements in the list.
Hence removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be 
removed. 
While In ArrayList all the elements need to be shifted to fill out the space created by removed element.

-->
insert() or add(Object) operation : Insertions in LinkedList are generally fast as compare to ArrayList.

In LinkedList adding or insertion is O(1) operation . While in ArrayList, if array is full i.e worst case, there is extra cost of 
resizing array and copying elements to the new array , which makes runtime of add operation in ArrayList O(n) , 
otherwise it is O(1).

-->
ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence 
the memory consumption is high in LinkedList comparatively.


similarities between ArrayList and LinkedList:

Both ArrayList and LinkedList are implementation of List interface.
They both maintain the elements insertion order which means while displaying ArrayList and LinkedList elements the result set 
would be having the same order in which the elements got inserted into the List.
Both these classes are non-synchronized and can be made synchronized explicitly by using Collections.synchronizedList method.
The iterator and listIterator returned by these classes are fail-fast (if list is structurally modified at any time after the 
iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a 
ConcurrentModificationException).


11)What are the way we have to read the data from ArrayList and which is the fastest? 

We can read the data from ArrayList in two ways.

1.using for loop 
2.using iterator of ArrayList.
The first option is faster than using iterator. Because value stored in arraylist is indexed access.
So while accessing the value is accessed directly from the index. 

12)If reading the data using iterator is slow then why do we need it and when to use it?

If we read the data using For loop ,then it does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does.

13)Why is it preferred to declare: List list = new ArrayList(); instead of ArrayList = new ArrayList()?

It is preferred because:
If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that. 
The most important one – If a function is declared such that it takes list.
Ex: void showDetails(List list).
When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.


14)How to sort list in reverse order? 

To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class
with reverseOrder(). 
Then, pass the reverse Comparator to the sort() method. 

List list = new ArrayList(); 
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp) 

15)How to sort list of strings - case insensitive? 

 using Collections.sort(list, String.CASE_INSENSITIVE_ORDER); 

16)Can a null element added to a set ? 

 A null element can be added only if the set contains one element because when a second element is added then as per set
defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.

17)How to convert array to list?

we can use asList() method of Arrays class to convert array to list.

18) How to remove duplicate elements from arrayList?

 As we know List inteface allows duplicates and Set inteface does not allows duplicate elements.
So to remove duplicates from ArrayList,we can convert ArrayList to Set and by converting back to ArrayList.
If we want to maintain insertion order of arraylist elements,then better to use LinkedHashSet.(Since HashSet does not maintain
insertion order).
If we are deleting duplicates while iterating then better to use Iterator's remove method and not ArrayList's remove method.
(because it throws ConcurrentModificationException).


simple example:


with collections:

public class ArrayListRemoveDuplicate {
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add(10);
al.add(20);
al.add(10);//duplicate
System.out.println("with duplicates:"+al);
Set s=new LinkedHashSet(al);
System.out.println("without duplicates:"+s);
}
}


19) How to convert arrayList to string?


import java.util.ArrayList;

public class ListtoString {
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add("one");
al.add("two");
al.add("three");
al.add("four");

StringBuilder sb=new StringBuilder();

for(String s:al)
{
sb.append(s);
}
System.out.println("string is:"+sb.toString());
}
}


or

We can also use StringUtils class methods like collectionToCommaDelimitedString(list),collectionToDelimitedString(list, "|"),
StringUtils.collectionToDelimitedString(list, ":");


20)what is the difference between ArrayList and HashSet?


Differences:

1.ArrayList class implements List Interface,Where as HashSet class implements Set interface.
2.ArrayList class is ordered collection,But HashSet is un ordered collection.
3.ArrayList allows duplicate values,where as HashSet does not allow duplicate values.
4.In ArrayList we can retrieve the elements by using get(index) and we can remove the elements by using remove(index).But HashSet
does not provide get() method.

Similarities:

1.Both ArrayList and HashSet are not synchronized and not recommended to use in multi threading environment.
2.We can traverse both ArrayList and HashSet using Iterator inteface.
3.Both ArrayList and HashSet are fail-fast they will throw ConcurrentModificationException if ArrayList or HashSet is modified 
structurally once Iterator has been created.


21)How to make ArrayList read only ?

We can create read only collection by using Collections.unmodifiableCollection() method.
After this if we try to perform any operations like add(),remove() and set() with and without using Iterator or ListIterator 
interfaces ,then it will throw UnsupportedOperationException.

ArrayList al=new ArrayList();

Collection readOnlyCollection=Collections.unmodifiableCollection(al);
readOnlyCollection.add("java");//raises java.lang.UnsupportedOperationException


22)How to convert an ArrayList to Array?


we can use toArray() method of ArrayList class to convert the ArrayList to array.

ArrayList al=new ArrayList();
al.add("c");
al.add("c++");
al.add("java");
Object array[]=al.toArray();
for(Object o:array)
{
System.out.println(o);
}


23)How to replace element in ArrayList with new element?


We can use set() method from ArrayList to replace any element with new element.

ArrayList al = new ArrayList();

al.add("a");

al.add("b");

al.add("c");

al.add("d");

System.out.println(al); 

al.set(2, "z");//now index position 2 (value is c) is replaced with z

System.out.println(al);


24)How to get the portion of the ArrayList?

We can use subList() method of ArrayList to get the portion of ArrayList.
The returned subList is backed by original ArrayList. That means any changes made to subList will be reflected in original 
ArrayList or Vice-Versa.

ArrayList al = new ArrayList();
al.add("a");  
al.add("b");  
al.add("c");  
al.add("d");  
System.out.println("full list:"+al); 
List portion=al.subList(1, 3);
System.out.println("portion:"+portion);
portion.set(1, "z");//replaces index 2 (value c with z)
System.out.println("modified full list:"+al);
System.out.println("modified portion:"+portion);


output:

full list:[a, b, c, d]
portion:[b, c]
modified full list:[a, b, z, d]
modified portion:[b, z]


25)How to join two ArrayLists?


We can use addAll() method which takes Collection type as an argument to join two ArrayLists.
This method will appends all elements of passed Collection to the end of Invoking collection.
addAll() method will take index position also to add at specific position.


26)How to find middle element from the list?


import java.util.ArrayList;

public class FindMiddle {

public static void main(String[] args) {
ArrayList al=new ArrayList();

for(int i=0;i<al.size;i++) {
al.add(i);
}

int middle=al.size()/2;

System.out.println("middle element:"+al.get(middle));

}

}

Comments

Popular posts from this blog