Tuesday 23 June 2015

Difference between JDK, JRE and JVM


JVM:-
The Java Virtual machine (JVM) is the virtual machine that runs the Java bytecodes. The JVM doesn't understand Java typo, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM.
Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.

JRE:-
Java Runtime Environment contains JVM, class libraries, and other supporting files. It contains set of libraries plus other files that JVM uses at runtime.
Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system.
It does not contain any development tools such as compiler, debugger, etc.
The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

JDK:-Java Development Kit (JDK) The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.


                                    JDK is a superset of the JRE






                                             Relations between JVM ,JRE, JDK



Tuesday 30 July 2013

Abstract class and Interface in Java

                                                   Abstraction in Java

Abstraction(Hide certain details and show only essential details):- Abstraction is a process of hiding the implementation details and showing only functionality to the user.Another way, it shows only important things to the user and hides the internal details.

How to achieve Abstraction in java
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)

2. Interface (100%)


1.Abstract class:-
A class that is declared as abstract is known as abstract class.It needs to be extended and its method
implemented. It cannot be instantiated.

An abstract class is something which is incomplete and you can not create instance of abstract class. Java has concept of abstract classes, abstract method but a variable can not be abstract in Java.


Example of abstract class

abstract class Shape{
abstract void draw();            //here we hide implementation  
}

class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
 }

class Test{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
 }

 }
------------------------------------------------------------------------------------------------------------
*1.If there is any abstract method in a class, that class must be abstract.
*2.An abstract method in Java doesn't have body , its just a declaration. In order to use abstract method you need to override that method in SubClass.
------------------------------------------------------------------------------------------------------------

2. Interface:-An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

An interface is similar to a class in the following ways:

1.An interface can contain any number of methods.
2.An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
3.The bytecode of an interface appears in a .class file.
4.Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

1.You cannot instantiate an interface.
2.An interface does not contain any constructors.
3.All of the methods in an interface are abstract.
4.An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
5.An interface is not extended by a class; it is implemented by a class.
6.An interface can extend multiple interfaces.

Example of interface 

interface Vehicle {
    void showMaxSpeed();//must be implemented in all classes which implement this interface
   }
    
   class Bus implements Vehicle {
    
    public void showMaxSpeed() {
        System.out.println("Bus max speed: 100 km/h");
    }
   }
    
   class Truck implements Vehicle {
    
    public void showMaxSpeed() {
        System.out.println("Truck max speed: 80 km/h");
    }
   }

public class InterfaceExample {
    
   public static void main(String[] args) {
    Vehicle bus = new Bus();
    Vehicle truck = new Truck();
    bus.showMaxSpeed();
    truck.showMaxSpeed();
   }
}


------------------------------------------------------------------------------------------------------------
Java Abstract class and interface Interview Questions

**Difference Between Interface and Abstract Class

(i)Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
(ii)Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.
(iii)Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
(iv)Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
(v)An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
(vi)A Java class can implement multiple interfaces but it can extend only one abstract class.
(vii)Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.

(viii)In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

1.Can abstract class have constructors in Java?

Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class,  constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Now some interviewer, ask what is the purpose of constructor, if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation. Also even if you don’t provide any constructor, compiler will add default no argument constructor in abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.

2.Can you create instance of abstract class?

No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract,  you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.

3.What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

4.Is it necessary for abstract class to have abstract method?

No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class, e.g. now allowing to create any instance. By the way, it’s debatable whether you should have abstract method inside abstract class or interface. In my opinion, abstract class should have abstract methods, because that’s the first thing programmer assumes, when he see that class. That would also go nicely along principle of least surprise.

5.Can abstract class implements interface in Java? does they require to implement all methods?

Yes, abstract class can implement interface by using implements keyword. Since they are abstract, they don’t need to implement all methods. It’s good practice to provide an abstract base class, along with an interface to declare Type. One example of this is java.util.List interface and corresponding java.util.AbstractList abstract class. Since AbstractList implements all common methods,  concrete implementations like LinkedList and ArrayList are free from burden of implementing all methods, had they implemented List interface directly. It’s best of both world, you can get advantage of interface for declaring type, and flexibility of abstract class to implement common behavior at one place. Effective Java has a nice chapter on how to use interface and abstract class in Java, which is worth reading.

6.Can abstract class be final in Java?
No, abstract class can not be final in Java. Making them final will stop abstract class from being extended, which is the only way to use abstract class. They are also opposite of each other, abstract keyword enforces to extend a class, for using it, on the other hand, final keyword prevents a class from being extended. In real world also, abstract signifies incompleteness, while final is used to demonstrate completeness. Bottom line is, you can not make your class abstract and final in Java, at same time, it’s a compile time error.

7.Can abstract class have static methods in Java?
Yes, abstract class can declare and define static methods, nothing prevents from doing that. But, you must follow guidelines for making a method static in Java, as it’s not welcomed in a object oriented design, because static methods can not be overridden in Java. It’s very rare, you see static methods inside abstract class, but as I said, if you have very good reason of doing it, then nothing stops you.

8.Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class, e.g. now allowing to create any instance.

9.What is abstract method in Java?
An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration.  All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java

                public void abstract printVersion();
Now, In order to implement this method, you need to extend abstract class and override this method.

10.Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.























Saturday 27 July 2013

Java Database Connectivity (JDBC)

                                                  Java Database Connectivity (JDBC)



The Java Database Connectivity (JDBC) API enable Java application to interact with a database.
It’s a java API for communicating to relational database,API has java classes and interfaces using that developer can easily interact with database.

What are the main steps in java to make JDBC connectivity?
1.Load a Driver
2.Establish a connection
      (i) driver name
      (ii) port no.
      (iii) ip address
      (iv) user name
      (v) passward
3.Statement object
4.Execute the Query(ResultSet)
     (i)Process the Results
5.Close the connection


1.Load a Driver:- Before you can connect to a database, you need to load the driver. Use Class.forName(String) method. This method takes a string representing a fully qualified class name and loads the corresponding class.your code implicitly loads the driver using the Class.forName() method.Here is an example:

try {
    Class.forName("connect.microsoft.MicrosoftDriver");
    //Class.forName("oracle.jdbc.driver.OracleDriver"); for Oracle driver
    //Class.forName("com.sybase.jdbc.SybDriver"); for sybase driver
} catch(ClassNotFoundException e) {
    System.err.println("Error loading driver: " + e);
}

Note:-The forName() method can throw a ClassNotFoundException if the driver is not available.


2.Establish a connection:- To make the actual network connection, pass the URL, the database username, and the password to the getConnection method of the DriverManager class,as illustrated in the following example.

Connection con=DriverManager.getConnection
                                               ("jdbc:oracle:thin:@localhost:1521:xe","system","password");

3.Statement object:- A Statement object is used to send queries and commands to the database and is created from the Connection as follows:

Statement stmt = connection.createStatement();


4.Execute the Query(ResultSet):- Once you have a Statement object, you can use it to send SQL queries by using the executeQuery method, which returns an object of type ResultSet. Here is an example:

String query = "SELECT col1, col2, col3 FROM sometable";

ResultSet rs = statement.executeQuery(query);

(i)Process the Results:- The simplest way to handle the results is to process them one row at a time, using the ResultSet’s next method to move through the table a row at a time. Within a row, ResultSet provides various getXxx methods that take a column index or column name as an argument and return the result as a variety of different Java types. For instance, use getInt if the value should be an integer, getString for a String, and so on for most other data types. If you just want to display the results, you can use getString regardless of the actual column type. However, if you use the version that takes a column index, note that columns are indexed starting at 1 (following the SQL convention), not at 0 as with arrays, vectors, and most other data structures in the Java programming language.

Note that the first column in a ResultSet row has index 1, not 0. Here is an example that prints the values of the first three columns in all rows of a ResultSet.

while(resultSet.next()) {
       System.out.println(results.getString(1) + " " +
       results.getString(2) + " " +
       results.getString(3));
}



5.Close the connection:- To close the connection explicitly, you should do

connection.close();


_________________________________________________________________________________
                                        Java Database Connectivity (JDBC) Driver

JDBC Driver is a software component that enables java application to interact with the database.There are  4 types of JDBC drivers:

1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1. JDBC-ODBC bridge driver:- The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC methods into ODBC function calls.

Sun provides a JDBC-ODBC Bridge driver by “sun.jdbc.odbc.JdbcOdbcDriver”.

The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example, ODBC must be installed on the computer and the database must support ODBC driver.

The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a particular database.

Process:-
Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 1 Driver   →   ODBC Driver   → Database library APIs → Database

Advantages:-
1.easy to use.
2.can be easily connected to any database.
Disadvantages:-
1.Performance degraded because JDBC method call is converted into the ODBC funcion calls.
2.The ODBC driver needs to be installed on the client machine.


2. Native-API driver (partially java driver):- The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver converts the JDBC method calls into native calls of the database  so this driver is also known as a Native-API driver.

Process:-
Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 2 Driver   →  Vendor Client Database library APIs → Database

Advantage:-
1.There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver; hence the performance is better as compare the type 1 driver (JDBC-ODBC Bridge).
2.Performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:-
1.The Native driver needs to be installed on the each client machine.
2.The Vendor client library needs to be installed on client machine.

3. Network Protocol driver (fully java driver):- Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database.

Process:-
Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 3 Driver   →  Middleware (Server)→ any Database

Advantage:-

1.There is no need for the vendor database library on the client machine because the middleware is database independent and it communicates with client.
2.Type 3 driver can be used in any web application as well as on internet also because there is no any software require at client side.
3.A single driver can handle any database at client side so there is no need a separate driver for each database.
4.The middleware server can also provide the typical services such as connections, auditing, load balancing, logging etc.

Disadvantage:-

1.An Extra layer added, may be time consuming.
2.At the middleware develop the database specific coding, may be increase complexity.
3.Network support is required on client machine.


4. Thin driver (fully java driver):- The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in between do not need to be converted any other formatted system so this is the fastest way to communicate quires to DBMS and it is completely written in JAVA because of that this is also known as the “direct to database Pure JAVA driver”.

Process:-
Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 4 Driver (Pure JAVA Driver)   → Database Server

Advantage:-

1.It’s a 100% pure JAVA Driver so it’s a platform independence.
2.No translation or middleware layers are used so consider as a faster than other drivers.
3.The all process of the application-to-database connection can manage by JVM so the debugging is also managed easily.

Disadvantage:-

1.There is a separate driver needed for each database at the client side.
2.Drivers are Database dependent, as different database vendors use different network protocols.

























Wednesday 24 July 2013

What is the difference between access specifiers and access modifiers in java?

                   What is the difference between access specifiers and access modifiers in java?


Access specifiers:- By using access specifier we define that who one can access our class/method and variable(or whatever with that we use access specifier ).
Basically java access specifier are four types -

1.public,
2.private,
3.protected, and
4.default


public access specifier :-(Any where)
If you declare any method/function as the public access specifier than that variable/method
can be used anywhere.



private access specifier :-(only till class)
If you declare any method/variable as private than it will only accessed in the same class which declare that method/variable as private.The private members cannot access in the outside world.If any class declared as private than that class will not be inherited.




protected access specifier :-(within a class,within a package and outside package in derived class)
It has same properties as that of private access specifier but it can access the methods/variables in the child class of parent class in which they are declared as protected.When we want to use the private members of parent class in the child class then we declare those variables as protected.



default access specifier :-(Any where in same package)
If you define any method/variable as default or not give any access specifier than the method or variable will be accessed in only that package in which they are defined.They cannot be accessed outside the package.



Access modifiers:- But access modifier are properties of a class/method/variable while access modifier are five types.

1.final
2.static
3.abstract
4.Synchronization and
5.transient











variable in java


  variable in java


     

Instance Variable:- Variable which are associated with a single instance of class.
e.g studentid,name,sal etc.

Static Variable:-  Variable  which are not associated withsingle instance of class  acommen value will be persist between all the object.Static variable are known as class variable.

Local Variable:- Which are arguments of method/function declared local in method/function or in some scope.

                                           

Tuesday 23 July 2013

What is Class and Object in Java

                                               
                                                        What is Class and Object in Java

Java is an object-oriented programming language.As a language that has the Object Oriented feature Java supports the following fundamental concepts:

Classes
Objects
Encapsulation
Inheritance
Polymorphism
Abstraction


Class:- A class is a template, blueprint(of Object) means you can create different object based on one class which varies in there property.

Object:-An object is an instance of a class. You can create many instances of a class.
e.g. if Car is a class than Hyundai,Nissan,Maruti Suzuki or Tata Motors can be considered as object because they are essentially a car but have different size, shape, color and feature.

Objects have states and behaviors:- State is represented by field in class 
e.g. numberOfGears, whether car is automatic or manual, car is running or stopped etc. 
On the other hand behavior is controlled by functions, also known as methods in Java 
e.g. start() will change state of car from stopped to started or running and stop() will do opposite.





For example, a car is an object. 

Its state includes current:

Speed
RPM
Gear
Direction
Fuel level
Engine temperature

Its behaviors include:

Change Gear
Go faster/slower
Go in reverse
Stop
Shut-off

Its identity is:

VIN
License Plate


*1. A class describes the data and the methods of its objects. Every object belongs to some class.
*2. An object contains data (instance variables) representing its state, and instance methods, which are the things it can do.