Saturday 27 September 2014

Overriding of static method in Java.

So in my previous post which is on overriding in java I mentioned that static methods can’t be overridden .Yes, its true that we cannot override static methods .But hold on when I tried the following program it worked :
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
 Public static void disp(){
  System.out.println("in parent");
 }
}


public class child extends Parent{
 public  static void disp(){
  System.out.println("in child");
 }

 public static void main(String[] args) {
  child c= new child();
  p.disp();
 
 
 }
}
And there is output also as :
In child

Without any compilation error .
Ok, so I will explain you this thing that overriding happens at runtime not at compilation time .Its actually dynamic binding .This thing which is happening in the above example is method hiding means If you declare,  another static method with same signature in derived class than static method of super class will be hidden, and any call to that static method in sub class will go to static method declared in that class itself. This is known as method hiding in Java.


I will explain you this with an example . Suppose we have 2 classes one parent and other child and we have a static method disp() in both classes which is actually overridden in child class then by rule of overriding method of that class should be resolved with the object of class used to call that method but instead of that in case of static method its being resolved by reference . eg. In the example given below if I am using parent reference and object of child then method of parent class will be called instead of parent class because static methods are dealt or resolved at compile time .
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
 Public static void disp(){
  System.out.println("in parent");
 }
}


public class child extends Parent{
 public  static void disp(){
  System.out.println("in child");
 }

 public static void main(String[] args) {
Parent p= new child();
  p.disp();
 
 
 }
}

Then output will be :
In parent
In the case below with child class reference  
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
 Public static void disp(){
  System.out.println("in parent");
 }
}


public class child extends Parent{
 public  static void disp(){
  System.out.println("in child");
 }

 public static void main(String[] args) {
  child c= new child();
  p.disp();
 
 
 }
}

Output will be :
In child

See also :





Read More »

Friday 26 September 2014

Overriding in java

Meaning of overriding :


Overriding concept is associated with Inheritance . If we have 2 classes ,one extending the other then child class can override methods of parent class . But there are some rules which needs to be followed :

So we will see which are all these rules :

Rule 1 : The signature of method in the child class should be exactly same as that in Parent class which includes return type, method parameters and name.

Rule 2:Argument list should be exactly same as that of overridden method.

Rule 3: Constructors cannot be overridden .

Rule 4: Static methods cannot be overridden but can be re declared which is actually method hiding .This can be read in detail from

Overriding of static method in Java.


Rule 5 : Final methods cannot be overridden.

Imp things :

1. Overridden methods are bound at run time only.



This i will explain u with an example:


package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
public void disp(){
System.out.println("in parent");
}
}


public class child extends Parent{
public void disp(){
System.out.println("in child");
}
public static void main(String[] args) {
child c= new child();
p.disp();
}
}

Output : in child 


method disp is being overridden in the above example 

Imp Thing : If you dont provide same arguments in method name of return type then there will be a compilation error.

Now as you can see we have made an object of child class with child class reference only . But what happens if we have child class reference and parent class object .


 Child class reference and parent class object in Overriding:

This thing can be understood with the help of an example :

package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
public void disp(){
System.out.println("in parent");
}
}


public class child extends Parent{
public void disp(){
System.out.println("in child");
}
public static void main(String[] args) {
child c= new Parent();
c.disp();
//testing tst= new Parent();
}
}

In this case there will be a compilation error on the error which is shown as bold in the above example . But there is a solution that you can add casting of object to child  but that also lead to an exception that parent class object cannot be cast to child class.


Exception in thread "main" java.lang.ClassCastException: test.Parent cannot be cast to test.child
at test.child.main(child.java:20)

Now one more case where we have parent class reference and child class object .So what you thick in this case ?
Compilation error ?
No error?
or something else ?

ok let me tell you this case in detail also 

Parent class reference and child class object in Overriding:

Well this case can also seen with an example :
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
public void disp(){
System.out.println("in parent");
}
}


public class child extends Parent{
public void disp(){
System.out.println("in child");
}
public static void main(String[] args) {
Parent p= new child();
p.disp();
//testing tst= new Parent();
}
}

In case of  Parent class reference and child class object in Overriding there will be no compilation error and the program will execute with out put as :

in child .

Imp Notes :
Read More »

Thursday 25 September 2014

How to sort and reverse an array list without using sort method

package test;

import java.util.ArrayList;
import java.util.List;

public class testing {

public static void main(String[] args) {
List<Integer> l= new ArrayList<Integer>();

l.add(1);
l.add(7);
l.add(90);
l.add(67);
int temp;
for (int i = 0; i < l.size(); i++) {
for (int j =0 ; j < l.size(); j++) {

if(l.get(i)>l.get(j)){
temp = l.get(i);
l.set(i,l.get(j));
l.set(j,temp) ;

}
}

}
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
}
}

 See :
How to reverse a string in java
Difference between Arrays.sort() and collections.sort() 
How to add instance of a class to list and then reterieve it
Constructor,Constructor Interview Questions
Overriding/method Overriding In java

Read More »

Serialization in Java

Meaning of serilization in java



Serialization means converting an object data into byte stream so that it can be easily transfer through network.
It means its mechanism of translating objects values/state to bytes to send it over the network and same ay deseriablzation is coverting those bytes back into object data.
You might interseted in : String,String Buffer and String Builder
How to add instance of a class to list and then reterieve it
Read More »

Can a class be static in java?

Static class in java :

Static class in java :



YES, we can  have static classes in java like we've got static variables and static method and static things are related to the complete class not with an object of a class.

Similarly ,static classes can even be related to another class. therefore we are able to have solely static nested classes. Static variables and methods
Static variables and methods


Static variables and methods :
Static Variable :Static variables belongs to the complete class instead of one object .
They have only one copy of memory
They can be access with simply name of class ,we don't need an object to initialize or access them
For eg . we've got a class Student as below :
public class Student{
private static String studentId;
public Static void studenttest()
{
}
So we are able to access each static method and variable as
Student.studentId
Student.studenttest()





You may like :
Custom Exception in Java -Tutorial

Read More »

Wednesday 24 September 2014

If we are using both constructor and Setter method of a bean to set property of a bean class then with which value it will be set , with value given in constructor or setter method ?


Ans :  With value given by setter method.
Reason : Because constructor will be invoked at the time of object creation but setter method will be invoked after that ,so due to which value of setter method ll override value given by constructor .
Eg. We have bean class Student

Class Student
{
Private int studentID;
Private String studentName;

Public Student(int stuid,String stuName)
{
this.studentID=stuid;
this.studentName=stuName;
}

//getter and setter methods for both
}

Class test
{
Main
{
Student obj=new Student(1,”Manish”);//Constructor will be invoked here
obj.setStudentID(2);//setter method will be invoked here which will override the value given //by Constructor
System.out.println(obj.getStudentID()) ; //will print 2
}

}

Read More »

Monday 22 September 2014

Internal Working of Array List

ArrayList works on the principle of creating a array and adding elements to it.

ArrayList class has a member variable elementData which is a Object array;


Object[] elementData;





When we do List l = new ArrayList(); the array elementData is initalized with a size of 10


if you use List l = new ArrayList(5) then an array elementData is initalized with a size of 5

add(E element)

Inside .add() method there is this check. Before adding element into the array it will check what is the current size of filled elements and what is the maximum size of the array. If size of filled elements is greater than maximum size of the array(or will be after adding current element) then size of the array must be increased .

 if it is completely filled that is all element 10 are filled a new array is created with a new capacity which is 1.5 of original array  using Arrays.copyOf. If the elementData array is not exhausted the new element is added in the array.
So adding a element in a array may take more time as a completely new array needs to be created with greater capacity and the data in the old array is transferred into the new array.

add(index i, E element)
On adding a element at a particular index in ArrayList, ArrayList checks if a element is already present at that index. If no than the element passed in add() is added at that index, otherwise a new array is created with the index kept vacant and the remaining element shifted to right.
For Eg:


List<Integer> l= new ArrayList<String>();
l.add(1);
l.add(2);
l.add(3);
for (int i: l)
system.out.println(l.get(i));

See also :
Difference between equals() and = =
Difference between Arrays.sort() and collections.sort() 
Static varibale,static class,Static method
How to add instance of a class to list and then reterieve it
Difference between Array and ArrayList
Custom Exception in Java -Tutorial
Read More »

Saturday 20 September 2014

Difference between JSP include directive and JSP include action


              JSP include directive                        

 

                  JSP action directive

<%@ include file=”filename” %> is the JSP include directive.
<jsp:include page=”relativeURL” /> is the JSP include action element.

At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page


The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters.



You may like:
Difference between LinkedList and ArrayList
Difference between equals() and = =
Read More »

Tuesday 16 September 2014

JDBC Basics – Java Database Connectivity Steps

Before you can create a java Jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.



1. Loading a database driver


In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. 

Once loaded, the Driver class creates an instance of itself. 

A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.

The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in java.lang package.

For full JDBC Tutorial : JDBC tutorial

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}

With JDBC we need to handle exception . As in the above example we are handling exception if its unable to load the driver class.For more Information on Exception read Exception Handling in JAVA


2.Creating a oracle jdbc Connection




The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. 

DriverManager is considered the backbone of JDBC architecture.

DriverManager class manages the JDBC drivers that are installed on the system.

Its getConnection() method 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.

A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned.

An application can have one or more connections with a single database, or it can have many connections with different databases.

A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.

JDBC URL Syntax::    jdbc: <subprotocol>: <subname>
JDBC URL Example:: jdbc: <subprotocol>: <subname>


Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.



try{
 Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}

catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}


3. Creating a jdbc Statement object

Once a connection is obtained we can interact with the database.
Connection interface defines methods for interacting with the database via the established connection.
To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements:

1. Simple Statement 
2. Prepared Statement
3. PreparedStatement


For more information on Statements see :JDBC statements


4. Executing a SQL statement 


This we will demonstrate with the Statement object, and returning a jdbc resultSet. 

Statement interface defines methods that are used to interact with database via the execution of SQL statements. 

The Statement class has three methods for executing statements:
executeQuery(), 
executeUpdate(),
 and execute(). 

For a SELECT statement, the method to use is executeQuery
For statements that create or modify tables, the method to use is executeUpdate
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.

Before going further we need to know about ResultSet .


ResultSet in JDBC


ResultSet provides access to a table of data generated by executing a Statement. 

The table rows are retrieved in sequence.

 A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. 

It is constructed from the Connection object.

See :How to sort an Array List without using Comparator or sort method
5. Test JDBC Driver Installation

import javax.swing.JOptionPane;

public class TestJDBCDriverInstallation_Oracle {

  public static void main(String[] args) {
 StringBuffer output  = new StringBuffer();
 output.append(”Testing oracle driver installation \n”);
 try {
 String className = “sun.jdbc.odbc.JdbcOdbcDriver”;
 Class driverObject = Class.forName(className);
 output.append(”Driver : “+driverObject+”\n”);
 output.append(”Driver Installation Successful”);
 JOptionPane.showMessageDialog(null, output);
   } catch (Exception e) {
    output  = new StringBuffer();
    output.append(”Driver Installation FAILED\n”);
    JOptionPane.showMessageDialog(null, output);
  System.out.println(”Failed: Driver Error: ” + e.getMessage());
 }
   }
}





Read More »

JDBC Tutorial



JDBC -An introduction


The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections.
 Using JDBC you can send SQL, PL/SQL statements to almost any relational database.
 JDBC is a Java API for executing SQL statements and supports basic SQL functionality.
 It provides RDBMS access with which you can embed SQL inside Java code. 


With JDBC you can do many operations such as :

create a table
insert values into it
query the table
retrieve results

update the table

So for this we will start from basics and will also help in JDBC interview Questions also.

Quick Start :

1.JDBC Basics – Java Database Connectivity Steps
     Helps you to get familiar with JDBC





Read More »

Monday 15 September 2014

Throw Keyword , Throws Keyword and Difference between Throw and Throws

Throw keyword:


Throw keyword is used to throw an exception explicitly.

An exception, either a newly instantiated one or an exception that you just caught. by using the throw keyword.

Throw Example in Java :


import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}

Throws Keyword in java :



If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.

Like if a method does not want or capable to handle the exception with throws keyword itself , it can use throws keyword in its signature so what will happen that the method which is calling that method will have code handle that exception .
This can be understand with the help of an example below:



Throws Example in Java :


class DemoThrowsException {
    public void readFile(String file) throws FileNotFoundException {
        //..code
    }
    void useReadFile (String name) {              
        try {                                      
            readFile(name);                        
        }                                          
        catch (FileNotFoundException e) {          
            //code                                 
        }                                          
    }
}

 This is a simple example of using throws keyword .
In this example readFile method is not handling the FileNotFoundException ,so it throws the exception 
which will be handled by useReadFile method with try catch block which is internally calling readFile method .

Difference between throw and throws in Java :


Throws
Throw
Throws clause in used to declare an exception throw keyword is used to throw an exception explicitly.

Throws is followed by exception class names throw is followed by an instance variable
Throws clause is used in method declaration (signature).

throw is used inside method body to invoke an exception
Using throws you can declare multiple exceptions Using Throw keyword in java you cannot throw more than one exception

User Defined Exception in Java:


User defined exceptions in java are also known as Custom exceptions. Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions.

  • User defined exception needs to inherit (extends) Exception class in order to act as an exception.
  • throw keyword is used to throw such exceptions.

Read More »

Exception Handling in Java

Exception Handling in Java

Read More »

Saturday 13 September 2014

Exception ,Types of Exception , Its Handling


Exception Handling

What is Exception

Exception is an abnormal condition. In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at run time.

Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling.

Types of Exception

1.Checked Exception
2. Unchecked Exception
3. Error

How to reverse a string in java


1. Checked Exception

A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer.

2. Unchecked Exception/ RunTime Exception

A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.


How to Catch an Exception


A method catches an exception using a combination of the 
try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}

-------------------------------------------------------------------------------------------------------------------------
Exception Handling Example

public class MyExceptionHandle {
    public static void main(String a[]){
        try{
            for(int i=5;i>=0;i--){
                System.out.println(10/i);
            }
        } catch(Exception ex){
            System.out.println("Exception Message: "+ex.getMessage());
            ex.printStackTrace();
        }
        System.out.println("After for loop...");
    }
}



Output:

2
2
3
5
10
Exception Message: / by zero
java.lang.ArithmeticException: / by zero
        at com.myjava.exceptions.MyExceptionHandle.main(MyExceptionHandle.java:12)
After for loop...



Explanation :
As in the above example.... we handled the exception caused by 10/i which is arithematic exception ....because of that after exception occurs the program does not terminate and After the loop...statement also run. 

---------------------------------------------------------------------------------------------------------------------


Read More »