Difference between throw and throws in java


Throw:

 

  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined) 




  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public boolean isValidForVote(int age){
  4.  try{
  5.    if(age<18){
  6.   throw new InvalidAgeException ("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.   return false;
  12.  }
  13.   public static void main(String agrs[]){
  14.  ThrowDemo obj= new ThrowDemo();
  15.    obj.isValidForVote(17);
  16.   }
  17. }
We can throw predefined exceptions also

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public void method(){
  4.  try{
  5.   
  6.   throw new NullPointerException("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.  }
  12.   public static void main(String agrs[]){
  13.  ThrowDemo obj= new ThrowDemo();
  14.    obj.method();
  15.   }
  16. }
Like this we can throw checked exceptions and unchecked exceptions also. But throw keyword is mainly used to throw used defined exceptions / custom exceptions.

Throws:

  • The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un  handled exceptions to the calling place.

  1. package com.instanceofjavaforus;
  2. public class ThrowSDemo {
  3. public void method(int a,int b) Throws ArithmeticException{
  4.  
  5. inc c= a/b;
  6.  }
  7.   public static void main(String agrs[]){
  8.  ThrowDemo obj= new ThrowDemo();
  9.    try{
  10. obj.method(1,0);
  11. }catch(Exception e){
  12.  System.out.println(e);
  13. }
  14.   }
  15. }

 Uses of throws keyword:

  • Using throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, JVM.
  • Using throws keyword we can avoid try-catch with respect to the statements which are proven to generate checked exceptions.
  • It us highly recommended not to avoid try-catch with respect to the statements which are proven to generate exceptions in main method using throws keyword to the main() method.



JDBC

JDBC:

  • The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. 
  • Using JDBC you can connect to the database and execute any type of statements related relational database. 
  • JDBC is a Java API for executing SQL statements and supports basic SQL functionality. 

JDBC Architecture:

http://instanceofjavaforus.blogspot.in/

  • Java application calls the JDBC API. JDBC loads a driver which connects to the database.

Connectivity Steps to JDBC:

5 Steps to connect java Application with the database using JDBC.They are:
  • Register the driver class
  • Creating Connection
  • Creating Statement
  • Execting Queries
  • Closing Connection

Register the driver class:

  • The forName() of class is used to register the driver class.Using this class is used load the class dynamically.
try {

Class.forName(com.mysql.jdbc.Driver”); //Or any other driver

}

catch(Exception x){

System.out.println( “Unable to load the driver class!” );

}

Creating the Connection:


  • DriverManager is the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. 
  • Its getConnection() method of Driver Manager class is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to 
  • the database and returns a connection object.

try{
 Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}

Creating Statement:


  • Once a connection is established we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. Statement 
  • A statement object is used to send and execute SQL statements to a database.
       statement = dbConnection.createStatement();

Three kinds of Statements:

  • Statement
  • Prepared Statement
  • Callable Statement

Statement:

  • Execute simple sql queries without parameters.
         Statement createStatement().

Prepared Statement: 

  • Execute precompiled sql queries with or without parameters.
        PreparedStatement prepareStatement(String sql).

Callable Statement: 

  • Execute a call to a database stored procedure.
       CallableStatement prepareCall(String sql)

Executing Queries:


  • Statement interface defines methods that are used to interact with database and execution of SQL statements.
  • The Statement class has three methods:
  • executeQuery()
  • executeUpdate()
  • execute(). 

executeQuery():


  • For a SELECT statement, the method to use is executeQuery . 

executeUpdate():

  • For statements that create or modify tables, the method to use is executeUpdate. 
  • statements and are executed with the method executeUpdate. 

execute():

  • execute() executes an SQL statement that is written as String object.

Connection Close():

  • This method is used to close the connection.
          con.close();

Syntax:

public void close() throws SQLException.


Difference between enumeration and iterator and listiterator?

Enumeration:

  • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
  • Enumeration uses elements() method.
  • Enumeration can traverse in forward direction only.
  • Enumeration having methods like hasMoreElement(),nextElement().

Program:

package com.instanceofjavaforus;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector vector=new Vector();
vector.add("indhu");
vector.add("sindhu");
vector.add("swathi");
vector.add("swathi");
vector.add(null);
vector.add(null);
Enumeration en = vector.elements();  
    while(en.hasMoreElements()){  
         System.out.println(en.nextElement());  
    }  
}
}

Output:

indhu
sindhu
swathi
swathi
null
null

Iterator:

  • Iterator is implemented on all Java collection classes.
  • Iterator uses iterator() method.
  • Iterator can traverse in forward direction only.
  • Iterator having methods like hasNext(), next(), remove().

Program:

package com.instanceofjavaforus;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class IteratorDemo{
public static void main(String[] args) {
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}

}


Output:

swathi
sindhu
indhu

ListIterator:

  • ListIterator is implemented only for List type classes
  • ListIterator uses listIterator() method.
  • ListIterator can traverse in forward and backward directions.
  • ListIterator having methods like 
  • hasNext()
  • next()
  • previous()
  • hasPrevious()
  • remove()
  • nextIndex()
  • previousIndex().

Program:

package com.instanceofjavaforus;
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo{
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList.add("indhu");
arrayList.add("sindhu");
arrayList.add("saidesh");
arrayList.add(null);
arrayList.add(null);
ListIterator it=arrayList.listIterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

}

Output:
indhu
sindhu
saidesh
null
null


Why Java does not supports multiple inheritance?

Inheritance:

  • The concept of getting properties of one class object to another class object is known as inheritance.
  • Here properties means variable and methods.

Types of Inheritance:

  1. Multiple inheritance.
  2. Multilevel inheritance.

 Multiple inheritance:


  • The concept of Getting the properties from multiple class objects to sub class object with same priorities is known as multiple inheritance.
  • Java Doesn't Support multiple Inheritance.

Diamond problem:

  • In multiple inheritance there is every chance of multiple properties of multiple objects with  the same name available to the sub class object with same priorities leads for the ambiguity.

  1. //Multiple inheritance program
  2. Class A{
  3. }
  4. Class B extends A{
  5. public void show(){
  6. }
  7. }
  8. Class C extends A{
  9. public void show(){
  10. }
  11. }
  12. Class D extends B,C{  // not supported by java leads to syntax error.
  13. }


Why multiple inheritanc eis not possible in java




  •  We have two classes B and c which are inheriting A class properties.
  • Here Class D inheriting B class and C class So properties present in those classes will be available in java.
  • But both classes are in same level with same priority.
  • If we want to use show() method that leads to ambiguity
  • This is called diamond problem.
  • Because of multiple inheritance there is chance of the root object getting created more than once.
  • Always the root object i.e object of object class hast to be created only once.
  • Because of above mentioned reasons multiple inheritance would not be supported by java.
  • Thus in java a class can not extend more than one class simultaneously. At most a class can extend only one class.
So these are the reasons that java does not supports multiple inheritance.Even though having this much reasons some people say and we also gets some doubts when we are using interfaces. lets me clear this one also. our immediate question should be.

Is Java supports multiple inheritance using interfaces?

  • Before that we need to know about interfaces.
  • Interfaces having fully abstract functionality.
  • Means methods in interfaces by default public abstract methods so we need to implement these methods in classes which are extending this interface.
   
  1. /Multiple inheritance program
  2. interface A{
  3. public void  show();
  4. }
  5. interface B{
  6. public void  display();
  7. }
  8. Class C Implements A,B{
  9. }



  • Here it seems we are achieving multiple inheritance by using interfaces. but we are not.
  • Syntactically it seems to multiple inheritance but the actual implementation of multiple inheritance is not there. how can i say that? let me clear

Difference between interfaces and inheritance: in multiple inheritance

  • Inheritance means getting the properties from one class object to another class object.
  • Means if any class extending another class then the super class methods can be used in sub classes happily.
  • But in interfaces the methods in interfaces are fully abstract so we need to provide functionality in our extended class and use it .seems both are opposite right? yes.
  • That is the reason we can say interfaces are only supports syntactical multiple inheritance which is not implementation of multiple inheritance.
So finally java supports only syntax of multiple inheritance does not supports implementation of multiple inheritance.
Inheritance is like debit and interface is like credit but interface has its own importance in other concepts like server side programming

What is the major change in JAVA 8 regarding interfaces:

5 different places to define Object of a class in java

different places to define object of a class


  • Object of a class can be defined at 5 different places.
  1. Defining object of a class as local to a method or local variable.
  2. Defining object of a class as an instance variable of another class.
  3. Defining object of a class as the parameter of the method.
  4. Defining  object of a class as the return data type of the method.
  5. Defining object of a class as the static variable or class variable of another class.

1.Defining object of a class as local to a method or local variable:


  1. package com.instanceofjava;
  2.  
  3.  public class ObjectInsideMethod { 
  4.  
  5.    int val;  
  6.  
  7. public int getVal()
  8.  {     
  9.   
  10.   return val;   
  11.  
  12.   }
  13.  
  14. public void setVal(int val) {  
  15.  
  16.        this.val = val;
  17.  
  18.  }
  19.  
  20. public void createObject(){ 
  21.   
  22.        ObjectInsideMethod obj=new ObjectInsideMethod();        
  23.         obj.setVal(10);    
  24.  
  25.       System.out.println(obj.getVal());
  26.  
  27.   }
  28.  
  29.    public static void main(String[] args) {
  30.  
  31.         ObjectInsideMethod obj=new ObjectInsideMethod();
  32.         obj.createObject();
  33.  
  34.  }
  35. }





2.Defining object of a class as an instance variable of another class:


  1. package instanceofjava;
  2.  
  3. class sample{
  4.  
  5.   int num;
  6.  
  7. public void setNum(int num) {
  8.         this.num= num;
  9. }
  10.  
  11. public String getNum() {
  12.         return num;
  13.     }
  14. }



  1. package com.instanceofjava; 
  2.  
  3. public class ObjectAsInstanceVariable { 
  4.  
  5.  Sample sample= new Sample ();   
  6.  
  7. public static void maina(String args[]){  
  8.  
  9.      ObjectAsInstanceVariable obj=new ObjectAsInstanceVariable();    
  10.      obj.sample.setNun(10);    
  11.  
  12.     }
  13.   }  



3.Defining object of a class as the parameter of the method.


  1. package com.instanceofjava; 
  2.  
  3.  public class Employee 
  4. {  
  5.  
  6.    String name;  
  7.    int id;   
  8.    String address;    
  9.  
  10. Employee(String name, int id, String address){ 
  11.  
  12.         this.name=name; 
  13.         this.id=id; 
  14.         this.address=address; 
  15.  }   
  16.  
  17.  public boolean comapreEmpids(Employee e){
  18.  
  19. if(this.id==e.id){ 
  20.  
  21. return true;  
  22.  
  23. }
  24. return false;
  25. }   
  26.  
  27.  public static void main(String args[]){
  28.  
  29.      Employee empone= new Employee("sai", 1, "hyderabad");
  30.      Employee emptwo= new Employee("sai", 2, "Khammam");
  31.  
  32.      boolean check=empone.comapreEmpids(emptwo);
  33.      System.out.println(check); //returns false
  34.  
  35.     } 
  36. }

 

 4.Defining  object of a class as the return data type of the method.


  1. package com.instanceofjava;  
  2.  
  3. public class Singleton
  4. {

  5. static Singleton obj;
  6.  
  7.  private  Singleton(){
  8.  } 
  9.  
  10. public static Singleton getInstance(){
  11.  
  12. if(obj!=null){ 
  13. return  obj; 
  14. }
  15. else{
  16. obj=new Singleton();
  17. return obj;
  18. }
  19.  
  20. }
  21.  
  22. public static void main(String[] args) {
  23.  
  24.  Singleton obj=Singleton.getInstance();
  25.  Singleton obj1=Singleton.getInstance();
  26.  
  27. }
  28.  }


5.Defining object of a class as the static variable or class variable of another class


  1. package com.instanceofjavaforus; 
  2. public class Sample {
  3.  
  4.      public void diplsyString(String str){
  5.          System.out.println(str);
  6. }
  7.  
  8.  
  9.  
  10. package com.instanceofjavaforus;
  11.  
  12. public class TestDemo {
  13.  
  14.   public static Sample sample= new Sample();
  15.  
  16.   public static void main(String args[]){
  17.  
  18. TestDemo.sample.diplsyString("Hello Hyderabd");
  19.  
  20.  }
  21. }


This scenario used in System.out.println();

Five different ways to create objects in java?


    There are four different ways to create objects in java:

  1.     Using new keyword
  2.     Using Class.forName():
  3.     Using clone():
  4.     Using Object Deserialization:  
  5.     Using newIntance() method

Using new keyword:


    This is the most common way to create an object in java. Almost 99% of objects are created in this way.

MyObject object=new Object();

Using Class.forName():

  • If we know the name of the class & if it has a public default constructor we can create an object in this way.
  • Syntax:
  • Myobject obj=(MyObject) class.forName("object").newInstance();




Using clone():


  • The clone() can be used to create a copy of an existing object.
  • Syntax:
  • MyObject obj=new MyObject();
  • MyObject object=(MyObject )obj.clone();

Using Object Deserialization:

  • Object deserialization is nothing but creating an object from its serialized form.
  • Syntax:
  • objectInputStream istream=new objectInputStream(some data);
  • MyObject object=(MyObject) instream.readObject();

Using newInstance() method

Object obj = DemoClass.class.getClassLoader().loadClass("DemoClass").newInstance();

Java Program on creating object using new keyword:


    package com.instanceofjava;
    
    public class Employee
    {
    
    private int id;
    private String name;
    
    Employee(int id,String name){
    this.id=id;
    this.name=name;
    }
    
    public void display(){
    
    System.out.println(id+" "+name);
    
    }
    
    public static void  main (String args[]){

    Emploee e=new Employee(1,"Indhu");
    Employee e1=new Employee(2,"Sindhu");
    
    e.display();
    e1.display();
    
    }
    }

 Output:

    Indhu
    Sindhu

Java Program on creating object using clone() method:


    package com.instanceofjava;
    
    public class Empcloneable implements Cloneable {
    
      int a;
      String name;
    
    Empcloneable(int a,String name){
    
     this.a=a;
     this.name=name;
    
    }
    
     public Empcloneable clone() throws CloneNotSupportedException{
    
      return (Empcloneable) super.clone();
    
     }
    
    public static void main(String[] args) {

    Empcloneable e=new Empcloneable(2,"Indhu");
    System.out.println(e.name);
    
    try {

    Empcloneable b=e.clone();
    System.out.println(b.name);
    
    } catch (CloneNotSupportedException e1) {
    
     e1.printStackTrace();
    }
    
    }
    }


 Output:

    Indhu
    Indhu

Java Program on creating object using Deserialization


    package com.instanceofjava;
    import java.io.*;
    public class Files
    {
    
    public static void main(String [] args)
    {
    
     Employee e = null;
    
    try
    {
    
    FileInputStream fileIn = new FileInputStream("/E/employee.txt");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    
    e = (Employee) in.readObject();
    in.close();
    fileIn.close();
    
    }catch(IOException i)
    {
    i.printStackTrace();
    return;
    
    }catch(ClassNotFoundException c)
    {
    System.out.println("Employee class not found");
    c.printStackTrace();
    return;
    }
    
    System.out.println("Deserialized Employee...");
    System.out.println("Name: " + e.name);
    
    }
    
    }


 Output:

    Name:Indhu





Java Program on creating object using class.forName();


    package com.instanceofjava;
    public class Sample{
    
    public static void main(String args[]){
    
    try {
    
     Class s= Class.forName("com.instanceofjava.Sample");
     Sample obj=(Sample) s.newInstance(); 
     System.out.println(obj.hashcode());
    
     } catch (Exception e) {
    
      e.printStackTrace();
    
    }
    
    }
    
    }

 Output:

    2007759836

You Might Like:

1.What are all the Five different places to create object in java



3.Six different ways to iterate list in java

Collections Map

Map:
  • Map is key-value pair.
  • Map Interface represents a mapping between key and value.
  • Map having:
  1. HashMap
  2. LinkedHashMap
  3. HashaTable
  4. TreeMap

HashMap:
  • HashMap is not synchronized.
  • Hashmap allows one key null and multiple null values.
  • HashMap default capacity is :
static final int DEFAULT_INITIAL_CAPACITY =16 static final float DEFAULT_LOAD_FACTOR = 0.75f;
Program for HashMap:

package com.instanceofjava;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Hashmap2 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap map=new HashMap();
map.put(1, "indhu");
map.put("d", "sindhu");
map.put("3", "swathi");
map.put(null, "indhira");
map.put(null, "indhira");
map.put(4, "sindhu");
if(!map.isEmpty()){
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}


Output:
indhira
swathi
indhu
sindhu
sindhu

HashTable:
  • HashTable is synchronized.
  • HashTable doesn't allow any null key or any null values.
  • HasTable Default capacity:
static final int DEFAULT_INITIAL_CAPACITY = 11;static final float DEFAULT_LOAD_FACTOR = 0.75f;
Program for HashTable:

package com.instanceofjava;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Hashtable3{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Hashtable hashTable=new Hashtable();
hashTable.put(1, "indhu");
hashTable.put("d", "sindhu");
hashTable.put("3", "swathi");
hashTable.put("d", "sindhu");
if(!hashTable.isEmpty()){
Iterator it=hashTable.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}


}
}

}


Output:
swathi
sindhu
indhu

TreeMap:

  • TreeMap is sorted order.
  • TreeMap doesn't allow null key or null values.



Program for TreeMap:

package com.instanceofjava;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Employee{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}


}
}

}

Output:

swathi
sindhu
indhu



Select Menu