Java INt

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 19

1>What is Difference between throw and throws

throw is used to throw user defined exceptions.


throws: throws is used to throw exception those are handled by
JVM directly.
throws is used in method declaration to
intimate user that, it throw the exception that must
be handled by calling method.
Note: use throws when your method does not handle exception.

2//What is the difference between ArrayList and LinkList

An ArrayList is a List implementation backed by a Java array,


similar to the Vector class. As the number of elements in the
collection increases, the internal array grows to fit them. If there
are lots of growth periods, performance degrades as the old array
needs to be copied into the new array. However, random access is
very quick as it uses an array index to access.
With a LinkedList, the List implementation is backed by a doubly
linked list data structure, allowing easy inserts/deletions
anywhere in the structure, but really slow random accesses as
the access must start at an end to get to the specific position.
Which you use really depends on the type of operations you need
to support.

What is difference between ArrayList and vector?

Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is
thread-safe. In Vector class each method like add(), get(int i) is
surrounded with a synchronized block and thus making Vector
class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold
onto their contents using an Array. When an element is inserted
into an ArrayList or a Vector, the object will need to expand its
internal array if it runs out of room. A Vector defaults to doubling
the size of its array, while the ArrayList increases its array size by
50 percent.

How can Arraylist be synchronized without using Vector?


Ans) Arraylist can be synchronized using:
Collection.synchronizedList (List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
If an Employee class is present and its objects are added in an
arrayList. Now I want the list to be sorted on the basis of the
employeeID of Employee class. What are the steps?
Ans) 1) Implement Comparable interface for the Employee class
and override the compareTo(Object obj) method in which
compare the employeeID
2) Now call Collections. sort() method and pass list as an
argument.
Now consider that Employee class is a jar file.

1) Since Comparable interface cannot be implemented, create


Comparator and override the compare(Object obj, Object obj1)
method .
2) Call Collections.sort() on the list and pass comparator as an
argument.
What is difference between HashMap and HashTable?
Ans) Both collections implements Map. Both collections store
value as key-value pairs. The key differences between the two
are
1. Access to the Hashtable is synchronized on the table while
access to the HashMap isn't. You can add it, but it isn't there by
default.
2. Another difference is that iterator in the HashMap is fail-safe
while the enumerator for the Hashtable isn't. If you change the
map while iterating, you'll know. Fail-safe - if the Hashtable is
structurally modified at any time after the iterator is created, in
any way except through the iterator's own remove method, the
iterator will throw a ConcurrentModificationException
3. HashMap permits null values and only one null key, while
Hashtable doesn't allow key or value as null.
What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix
size. It means that once array is declared as :
int [] intArray= new int[6];
intArray[7] // 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.
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
When to use ArrayList or LinkedList ?
Ans) Adding new elements is pretty fast for either type of list. For
the ArrayList, doing random lookup using "get" is fast, but for
LinkedList, it's slow. It's slow because there's no efficient way to
index into the middle of a linked list. When removing elements,
using ArrayList is slow. This is because all remaining elements in
the underlying array of Object instances must be shifted down for
each remove operation. But here LinkedList is fast, because
deletion can be done simply by changing a couple of links. So an
ArrayList works best for cases where you're doing random access
on the list, and a LinkedList works better if you're doing a lot of
editing in the middle of the list.
Source : Read More - from java.sun
Consider a scenario. If an ArrayList has to be iterate to read data
only, what are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or 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.
Now another question with respect to above question is if
accessing through iterator is slow then why do we need it and
when to use it.
Ans) For loop does not allow the updation in the array(add or
remove operation) inside the loop whereas Iterator does. Also
Iterator can be used where there is no clue what type of
collections will be used because all collections have iterator.

Which design pattern Iterator follows?


Ans) It follows Iterator design pattern. Iterator Pattern is a type of
behavioral pattern. The Iterator pattern is one, which allows you
to navigate through a collection of data using a common interface
without knowing about the underlying implementation. Iterator
should be implemented as an interface. This allows the user to
implement it anyway its easier for him/her to return data. The
benefits of Iterator are about their strength to provide a common
interface for iterating through collections without bothering about
underlying implementation.
Example of Iteration design pattern - Enumeration The class
java.util.Enumeration is an example of the Iterator pattern. It
represents and abstract means of iterating over a collection of
elements in some sequential order without the client having to
know the representation of the collection being iterated over. It
can be used to provide a uniform interface for traversing
collections of all kinds.
Why is it preferred to declare: List<String> list = new
ArrayList<String>(); instead of ArrayList<String> = new
ArrayList<String>();
Ans) 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. E.g 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
How to sort list in reverse order?
Ans) 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)
How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
What is difference between Iterator and ListIterator?
Iterator: --- Iterator takes the place of Enumeration in the Java
collections framework. One can traverse through the collection
with the help of iterator in forward direction only and Iterators
allow the caller to remove elements from the underlying
collection during the iteration with well-defined semantics
ListIterator:--An iterator for lists that allows one to traverse the
list in either direction.modify the list during iteration and obtain
the iterator's current position in the list. A ListIterator has no
current element. its cursor position always lies between the
element that would be returned by a call to previous() and the
element that would be returned by a call to next(). In a list of
length n there are n+1 valid index values from 0 to n inclusive.
Ex:*
Element(0) Element(1) Element(2) ... Element(n)
*
^
^
^
^
^
* Index: 0
1
2
3
n+1
*

What is java Reflection?

Reflection is commonly used by programs which require the


ability to examine or modify the runtime behavior of applications
running in the Java virtual machine. This is a relatively advanced
feature and should be used only by developers who have a strong
grasp of the fundamentals of the language. With that caveat in
mind, reflection is a powerful technique and can enable
applications to perform operations which would otherwise be
impossible.
Extensibility Features
An application may make use of external, user-defined
classes by creating instances of extensibility objects
using their fully-qualified names.
Class Browsers and Visual Development Environments
A class browser needs to be able to enumerate the
members of classes. Visual development
environments can benefit from making use of type
information available in reflection to aid the developer
in writing correct code.
Debuggers and Test Tools
Debuggers need to be able to examine private
members on classes. Test harnesses can make use of
reflection to systematically call a discoverable set APIs
defined on a class, to insure a high level of code
coverage in a test suite.
Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If
it is possible to perform an operation without using reflection,
then it is preferable to avoid using it. The following concerns
should be kept in mind when accessing code via reflection.
Performance Overhead
Because reflection involves types that are dynamically
resolved, certain Java virtual machine optimizations
can not be performed. Consequently, reflective
operations have slower performance than their nonreflective counterparts, and should be avoided in
sections of code which are called frequently in
performance-sensitive applications.

Security Restrictions
Reflection requires a runtime permission which may
not be present when running under a security
manager. This is in an important consideration for
code which has to run in a restricted security context,
such as in an Applet.
Exposure of Internals
Since reflection allows code to perform operations that
would be illegal in non-reflective code, such as
accessing private fields and methods, the use of
reflection can result in unexpected side-effects, which
may render code dysfunctional and may destroy
portability. Reflective code breaks abstractions and
therefore may change behavior with upgrades of the
platform.

Comparable Example
class Employee implements Comparable{
private int age;
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
/*
Signature of compareTo method is.
public int compareTo(Object object).
compareTo method should return 0 if both objects are equal, 1 if first
grater than other and -1 if first less than the other object of the same
class.
*/
public int compareTo(Object otherEmployee){
/*

If passed object is of type other than Employee, throw


ClassCastException.
*/
if( ! ( otherEmployee instanceof Employee ) ){
throw new ClassCastException("Invalid object");
}
int age = ( (Employee) otherEmployee ).getAge();
if(

this.getAge() > age )

return 1;
else if ( this.getAge() < age )
return -1;
else
return 0;
}
}
public class JavaComparableExample{
public static void main(String args[]){
/*
Create two different Employee objects, so that we can compare both.
*/
Employee one = new Employee();
one.setAge(40);
Employee two = new Employee();
one.setAge(30);
/*
Use compareTo method to determine which employee is younger
*/
if( one.compareTo(two) > 0 ) {
System.out.println("Employee one is elder than employee two !");
} else if( one.compareTo(two) < 0 ) {
System.out.println("Employee one is younger than employee two !");
} else( one.compareTo(two) == 0 ) {
System.out.println("Both employees are same !");
}
}

}
/*
OUTPUT of the above given Java Comparable Example would be :
Employee one is elder than employee two !
*/

Comparator Example

/*
Java Comparator example.
This Java Comparator example describes how java.util.Comparator interface
is implemented to compare Java user defined classe's objects.
These Java Comparator is passed to Collection's sorting method ( for
example Collections.sort method)to perform sorting of Java user defined
classe's objects.
*/
import java.util.*;
/*
java.util.Comparator interface declares two methods,
1) public int compare(Object object1, Object object2) and
2) boolean equals(Object object)
*/
/*
We will compare objects of the Employee class using custom comparators
on the basis of employee age and name.
*/
class Employee{
private int age;
private String name;
public void setAge (int age){
this.age=age;
}
public int getAge(){
return this.age;

}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
/*
User defined java comaprator.
To create custom java comparator Implement Comparator interface and
define compare method.
The below given comparator compares employees on the basis of their age.
*/
class AgeComparator implements Comparator{
public int compare(Object emp1, Object emp2){
//parameter are of type Object, so we have to downcast it to Employee
objects
int emp1Age = ( (Employee) emp1).getAge();
int emp2Age = ( (Employee) emp2).getAge();
if( emp1Age > emp2Age )
return 1;
else if( emp1Age < emp2Age )
return -1;
else
return 0;
}
}
/*
The below given comparator compares employees on the basis of their name.
*/
class NameComparator implements Comparator{
public int compare(Object emp1, Object emp2){
//parameter are of type Object, so we have to downcast it to Employee
objects

String emp1Name = ( (Employee) emp1 ).getName();


String emp2Name = ( (Employee) emp2 ).getName();
//uses compareTo method of String class to compare names of the employee
return emp1Name.compareTo(emp2Name);
}
}
/*
This Java comparator example compares employees on the basis of
their age and name and sort it in that order.
*/
public class JavaComparatorExample{
public static void main(String args[]){
/*
Employee array which will hold employees
*/
Employee employee[] = new Employee[2];
//set different attributes of the individual employee.
employee[0] = new Employee();
employee[0].setAge(40);
employee[0].setName("Joe");
employee[1] = new Employee();
employee[1].setAge(20);
employee[1].setName("Mark");
System.out.println("Order of employee before sorting is");
//print array as is.
for(int i=0; i < employee.length; i++){
System.out.println( "Employee " + (i+1) + " name :: " +
employee[i].getName() + ", Age :: " + employee[i].getAge());
}
/*
Sort method of the Arrays class sorts the given array.
Signature of the sort method is,
static void sort(Object[] object, Comparator comparator)
IMPORTANT: All methods defined by Arrays class are static. Arrays class
serve as a utility class.

*/
/*
Sorting array on the basis of employee age by passing AgeComparator
*/
Arrays.sort(employee, new AgeComparator());
System.out.println("\n\nOrder of employee after sorting by employee age
is");
for(int i=0; i < employee.length; i++){
System.out.println( "Employee " + (i+1) + " name :: " +
employee[i].getName() + ", Age :: " + employee[i].getAge());
}
/*
Sorting array on the basis of employee Name by passing NameComparator
*/
Arrays.sort(employee, new NameComparator());
System.out.println("\n\nOrder of employee after sorting by employee name
is");
for(int i=0; i < employee.length; i++){
System.out.println( "Employee " + (i+1) + " name :: " +
employee[i].getName() + ", Age :: " + employee[i].getAge());
}
}
}
/*
OUTPUT of the above given Java Comparable Example would be :
Order of employee before sorting is
Employee 1 name :: Joe, Age :: 40
Employee 2 name :: Mark, Age :: 20
Order of employee after sorting by employee age is
Employee 1 name :: Mark, Age :: 20
Employee 2 name :: Joe, Age :: 40
Order of employee after sorting by employee name is
Employee 1 name :: Joe, Age :: 40
Employee 2 name :: Mark, Age :: 20
*/

Comparable: A comparable object is capable of comparing itself


with another object. The class itself must implements the
java.lang.Comparable interface in order to be able to
compare its instances.

Comparator: A comparator object is capable of comparing two


different objects. The class is not comparing its instances, but
some other classs instances. This comparator class must
implement the java.lang.Comparator interface.
Do we need to compare objects?
The simplest answer is yes. When there is a list of objects,
ordering these objects into different orders becomes a must in
some situations. For example; think of displaying a list of
employee objects in a web page. Generally employees may be
displayed by sorting them using the employee id. Also there will
be requirements to sort them according to the name or age as
well. In these situations both these (above defined) concepts will
become handy.
How to use these?
There are two interfaces in Java to support these concepts, and each of these has one method to be
implemented by user.
Those are;
java.lang.Comparable: int compareTo (Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1.

positive this object is greater than o1

2.

zero this object equals to o1

3.

negative this object is less than o1

java.lang.Comparator: int compare (Object o1, Objecto2)


This method compares o1 and o2 objects. Returned int value has the following meanings.
1.

positive o1 is greater than o2

2.

zero o1 equals to o2

3.

negative o1 is less than o1

java.util.Collections.sort (List) and java.util.Arrays.sort (Object[]) methods can be used to sort


using natural ordering of objects.
java.util.Collections.sort (List, Comparator) and java.util.Arrays.sort (Object[], Comparator)
methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First
well write a simple Java bean to represent the Employee.

Next well create a list of Employees for using in different sorting requirements. Employees are added
to a List without any specific order in the following class.
import java.util.*;

public class Util {

public static List<Employee> getEmployees() {


List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}

Sorting in natural ordering


Employees natural ordering would be done according to the employee id. For that, above Employee
class must be altered to add the comparing ability as follows.

public class Employee implements Comparable<Employee> {


private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
.
}

The new compareTo() method does the trick of implementing the natural ordering of the instances. So
if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens
according to the ordering done inside this method.
Well write a class to test this natural ordering mechanism. Following class use the
Collections.sort(List) method to sort the given list in natural order.
import java.util.*;

public class TestEmployeeSort {

public static void main(String[] args) {


List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}

private static void printList(List<Employee> list) {


System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}

Run the above class and examine the output. It will be as follows. As you can see, the list is sorted
correctly using the employee id. As empId is an int value, the employee instances are ordered so that
the int values ordered from 1 to 8.
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40

Sorting by other fields


If we need to sort using other fields of the employee, well have to change the Employee classs
compareTo() method to use those fields. But then well loose this empId based sorting mechanism.
This is not a good alternative if we need to sort using different fields at different occasions. But no
need to worry; Comparator is there to save us.

By writing a class that implements the java.lang.Comparator interface, you can sort Employees using
any field as you wish even without touching the Employee class itself; Employee class does not need
to implement java.lang.Comparable or java.lang.Comparator interface.

Sorting by name field


Following EmpSortByName class is used to sort Employee instances according to the name field. In
this class, inside the compare() method sorting mechanism is implemented. In compare() method we
get two Employee instances and we have to return which object is greater.

public class EmpSortByName implements Comparator<Employee>{


public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Watch out: Here, String classs compareTo() method is used in comparing the name fields (which are
Strings).

Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method
instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how
the EmpSortByName comparator is used inside sort method.
import java.util.*;

public class TestEmployeeSort {

public static void main(String[] args) {

List coll = Util.getEmployees();


//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}

private static void printList(List<Employee> list) {


System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());

}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name
String field. Youll see that these are sorted alphabetically.

You might also like