What is the Internal implementation of ArrayList?

Internal implementation of ArrayList is:

import java.util.Arrays;

public class MyArrayList 
{
private Object[] myStore;
private int actSize=0;
public MyArrayList() {
	// TODO Auto-generated constructor stub
	myStore = new Object[10];
}
public Object get(int index)
{
	if(index < actSize)
	{
		return myStore[index];
	}
	else {
		throw new ArrayIndexOutOfBoundsException();
	}
}
public void add(Object obj) {
	if(myStore.length-actSize<=5)
	{
		increaseListSize();
}
myStore[actSize++] = obj;		
}
public Object remove(int index)
{
	if (index < actSize)
	{
	Object obj = myStore[index];
	myStore[index]=null;
	int temp = index;
 	while (temp < actSize)
	{
	myStore[temp]=myStore[temp+1];
	myStore[temp+1]= null;
	temp++;
	}
	actSize--;
	return obj;
	}
	else
	{
	throw new ArrayIndexOutOfBoundsException();
	}
}
public int size()
{
return actSize;	
}
private void increaseListSize() 
{
myStore = Arrays.copyOf(myStore, myStore.length*2);
System.out.println("\n new length : "+myStore.length);
}
public static void main(String[] args) {
	MyArrayList mal= new MyArrayList();
	mal.add(new Integer(2));
	mal.add(new Integer(15));
	mal.add(new Integer(25));
	mal.add(new Integer(48));
	mal.add(new Integer(24));
	for (int i = 0; i < mal.size(); i++) 
	{
		System.out.print(mal.get(i)+" ");
	}
	mal.add(new Integer(001));
	System.out.println("element at index 5: "+mal.get(5));
	System.out.println("list size: "+mal.size());
	System.out.println("removeing element at 2: "+mal.remove(2));
	for (int i = 0; i < mal.size(); i++)
	{
	System.out.print(mal.get(i)+" ");	
	}
}
}


==========================================================================

Output:

2 15 25 48 24 
 new length : 20
element at index 5: 1
list size: 6
removeing element at 2: 25
2 15 48 24 1 

What is Java Collections Framework? List out some benefits of Collections framework?

Ans:

To over come the limitations of arrays we should go for collection.

If we want to represent group of individual objects in a single entity then we should go for collection. Collection interface and is a root interface of collection framework.

Collections are growbable in nature, based on requirement we can increase or decrease the size of collections; we hold both homogeneous & heterogeneous elements.

Every collection class implemented based on some data structure, hence readymade method support is available for every requirement, being a programmer we have to use this method and we are not responsible to participate implementation.


What is synchronization?

Ans

Synchronization is a keyword that is applicable only for method and blocks. Synchronization is the process of allowing threads to execute one after one.

Java support multiple threads to be executed, synchronization is a process which keep all current threads in execute to be in synch. Synchronization avoids memory consistence error caused due to inconsistent view of shared memory.

Example

class SOP
{
 public static void print(String s)
 {
 System.out.println(s+"\t"); 
 }
}
  class TestThread extends Thread
 {
 String name;
 Synchronised synchronised;
 public TestThread(String name,Synchronised synchronised)
 {
  this.synchronised=synchronised;
  this.name=name;
 start();
 }
 @Override 
 public void run() {
  // TODO Auto-generated method stub
  synchronised.test(name);
 }
}
public class Synchronised 
{
public synchronized void test(String name)
{
for(int i= 0; i<10;i++)
{
SOP.print(name+":: "+i);
try{
 Thread.sleep(500);
}
catch(Exception e)
{
 SOP.print(e.getMessage());
}
}
}
public static void main(String[] args) {
 Synchronised synchronised = new Synchronised();
 new TestThread("THREAD1", synchronised);
 new TestThread("THRED2", synchronised);
 new TestThread("thred3", synchronised);
 
}
}

====================================================================================

Output

THREAD1:: 0 
THREAD1:: 1 
THREAD1:: 2 
THREAD1:: 3 
THREAD1:: 4 
THREAD1:: 5 
THREAD1:: 6 
THREAD1:: 7 
THREAD1:: 8 
THREAD1:: 9 
thred3:: 0 
thred3:: 1 
thred3:: 2 
thred3:: 3 
thred3:: 4 
thred3:: 5 
thred3:: 6 
thred3:: 7 
thred3:: 8 
thred3:: 9 
THRED2:: 0 
THRED2:: 1 
THRED2:: 2 
THRED2:: 3 
THRED2:: 4 
THRED2:: 5 
THRED2:: 6 
THRED2:: 7 
THRED2:: 8 
THRED2:: 9

Difference between throw, throws, throwable in java?

Ans

Throw in java:

Throw is a keyword in java which is used to throw exception manually, using throw keyword you can throw an exception from any method or block but that exception must be of the java.lang.Throwable class or it’s sub class

Throw an exception using throw keyword:

class  ThrowandThrowableException
{
void method()throws Exception
{
Exception e = new Exception();
throw e;
}
}

Throws in java:

Throw is also a keyword in java which is used in the method signature to indicate that this method may throw mentioned exception.

Syntax:

retun_type method_name(parameter list) throws exception list
{
//list of staements
}

Note:

By using throw keyword in java you can’t throw more than one exception but using throws you can declare multiple exceptions.

Throw syntax:

throw new ArithmeticException(“an integer should not be divided by zero ”);
throw new   IOException(“connection failed”);

Throws syntax:

throws  IOException, ArithmeticException, NullPointerExcepion, ArrayIndexoutofBoundException

Throwable:

Throwable is a supper class for all type of error and Exceptions in java. This class is a member of java.lang package. If you want create your own customized Exceptions then your class must be extend to this class.

Example:

Bellow example show create custom exception by extending java.lang.Throwable

class  MyException extends Throwable
{
// customized exception 
}
class ThrowandThrows
{
void method() throws MyException 
{
MyException e = new MyException();
throw e;
}
}

Explain the user defined Exceptions?

Ans:

Sometimes we need to create custom exception in java, i.e exception which is not defined in JDK or any third party library your application using. We often feel a need to create and thrown our own exceptions these exceptions are known as user defined or custom exceptions.

Example

public class UserDefinedException {
  
    public static void main(String args[]) {
        Account acct = new Account();
        System.out.println("Current balance : " + acct.balance());
        System.out.println("Withdrawing $200");
        acct.withdraw(200);
        System.out.println("Current balance : " + acct.balance());
        acct.withdraw(1000);
 
    }
 
}

/**
  * Java class to represent a Bank account which holds your balance and provide wi
  */  
  class Account {
 
    private int balance = 1000;
 
    public int balance() {
        return balance;
    }
 
    public void withdraw(int amount) throws NotSufficientFundException {
        if (amount > balance) {
            throw new NotSufficientFundException(String.format("Current balance %d is less than requested amount %d", balance, amount));
        }
        balance = balance - amount;
    }
 
    public void deposit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException(String.format("Invalid deposit amount %s", amount));
        }
    }
 
}


/**
   * User defined Exception class in Java
   */ 
  class NotSufficientFundException extends RuntimeException {
 
    private String message;
 
    public NotSufficientFundException(String message) {
        this.message = message;
    }
 
    public NotSufficientFundException(Throwable cause, String message) {
        super(cause);
        this.message = message;
    }
 
    public String getMessage() {
        return message;
    }

}

Out put:

Current balance : 1000
Withdrawing $200
Current balance : 800
Exception in thread "main" excptiohandleing.NotSufficientFundException: Current balance 800 is less than requested amount 1000
 at excptiohandleing.Account.withdraw(UserDefinedException.java:30)
 at excptiohandleing.UserDefinedException.main(UserDefinedException.java:11)