What is the difference between equals() method and == operator


== operator:

  •  == operator used to compare objects references.
  • used to compare data of primitive data types
  • if  we are comparing two objects using "==" operator if reference of both are same then it will returns true otherwise returns false.
  • obj1==obj2;
  • If we are comparing primitive data type variables then it compares data of those two variables
  • Ex: int a=12; int b=12; if(a==b) returns true

Comparing primitive values: 


  1. package com.instanceofjava;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {

  6. int a=12;
  7. int b=13;
  8. int c=12;
  9.  
  10. if(a==b){
  11. System.out.println("a and b are equal");
  12.  
  13. if(b==c){
  14. System.out.println("a and b are equal");
  15.  
  16. }
  17. }
     

Comparing Objects:

  1. package com.instanceofjavaforus;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  Demo obj1= new Demo();
  8. Demo obj2=new Demo();
  9.  
  10. if(obj1==obj2){ // here both are two different objects(memory allocation wise);
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1==s2){ // here it returns false
  11. System.out.println("obj1 and obj2 are referring to same address");
  12. }else{
  13.  System.out.println("obj1 and obj2 are referring to different address");
  14.  
  15. }
  16. }

Comparing String Literals:

  •  If we declared two string literals with same data then those will refer same reference.
  • means if we create any object using string literal then it will be created in string pool 
  • then if we are created another literal with same data then it wont create another object rather refers same object in pool.
  • so if compare two string literals with same data using "==" operator then it returns true.
  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringLiteralDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1="abc";
  8. String s2="abc";
  9.  
  10. if(s1==s2){ // here it returns true
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

equals() method:

  • equals() method defined in "object" class.
  • By default equals methods behaves like "==" operator when comparing objects.
  • By default equals() method compares references of objects.
  • But All wrapper classes and String class overriding this equals method and comparing data .
  • Means in String class and in All wrapper classes this equals() methods is overridden so that to compare data of those class objects. 

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1.equals(s2)){ // here it returns true
  11.  
  12. System.out.println(" data present in obj1 and obj2 is same");
  13.  
  14. }else{
  15.  
  16.  System.out.println(" data present in obj1 and obj2 is different");
  17.  
  18. }
  19. }
  20. }


 Comparing custom objects:

  • If we want to compare custom objects means our own objects data.
  • Then we need to override equals method and in that we need to compare data.

  1. package com.instanceofjavaforus;

    public class Patient {
       String name;
       Patient(String name){
           this.name=name;
       }
          public boolean equals(Patient obj){
          
           if(this.name.equals(obj)){
               return true;
           }else{
               return false;
           }
       }
           public static void main(){
            Patient obj1= new Patient("sam");
           
            Patient obj2= new Patient("sam");
           
            System.out.println(obj1.equals(obj2)); //returns true
        }
           
    }

Important points to note about equals() and "==":

  • "==" used to compare data for primitive data type variables .
  • "==" operator compares objects references
  • By default equals() method behaves like "==" operator for objects means compares objects references.
  • All wrapper classes and String class overriding this equals() method and compares data of two objects. if same returns true.(when ever we overrides equals() method we need to override hashcode() method too and if two objects on equal method same then both should have same hashcode).
  • And in equals() method in string class logic includes "==" operator too.

  1. package com.instanceofjava;
  2.  
  3. public boolean equals(Object anObject) {
  4.    if (this == anObject) {
  5.       return true;
  6.      }
  7.  if (anObject instanceof String) {
  8.      String anotherString = (String) anObject;
  9.      int n = value.length;
  10.     if (n == anotherString.value.length) {
  11.     char v1[] = value;
  12.      char v2[] = anotherString.value;
  13.   int i = 0;
  14. while (n-- != 0) {
  15.    if (v1[i] != v2[i])
  16.            return false;
  17.            i++;
  18.        }
  19.          return true;
  20.         }
  21.     }
  22.        return false;
  23.   }

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();
Select Menu