Tuesday, March 31, 2009

JDBC-ODBC-tutorial

JDBC versus ODBC and other APIs :
At this point, Microsoft's ODBC (Open DataBase Connectivity) API is probably the most widely used programming interface for accessing relational databases. It offers the ability to connect to almost all databases on almost all platforms. So

why not just use ODBC from Java ?

The answer is that you can use ODBC from Java, but this is best done with the help of JDBC in the form of the JDBC-ODBC Bridge, which we will cover shortly. The question now becomes, "Why do you need JDBC?" There are several answers to this question:

  1. ODBC is not appropriate for direct use from Java because it uses a C interface. Calls from Java to native C code have a number of drawbacks in the security, implementation, robustness, and automatic portability of applications.
  2. A literal translation of the ODBC C API into a Java API would not be desirable. For example, Java has no pointers, and ODBC makes copious use of them, including the notoriously error-prone generic pointer "void *". You can think of JDBC as ODBC translated into an object-oriented interface that is natural for Java programmers.
  3. ODBC is hard to learn. It mixes simple and advanced features together, and it has complex options even for simple queries. JDBC, on the other hand, was designed to keep simple things simple while allowing more advanced capabilities where required.
  4. A Java API like JDBC is needed in order to enable a "pure Java" solution. When ODBC is used, the ODBC driver manager and drivers must be manually installed on every client machine. When the JDBC driver is written completely in Java, however, JDBC code is automatically installable, portable, and secure on all Java platforms from network computers to mainframes.
In summary, the JDBC API is a natural Java interface to the basic SQL abstractions and concepts. It builds on ODBC rather than starting from scratch, so programmers familiar with ODBC will find it very easy to learn JDBC. JDBC retains the basic design features of ODBC; in fact, both interfaces are based on the X/Open SQL CLI (Call Level Interface). The big difference is that JDBC builds on and reinforces the style and virtues of Java, and, of course, it is easy to use.

More recently, Microsoft has introduced new APIs beyond ODBC: RDO, ADO, and OLE DB. These designs move in the same direction as JDBC in many ways, that is, in being an object-oriented database interface based on classes that can be implemented on ODBC. However, we did not see compelling functionality in any of these interfaces to make them an alternative basis to ODBC, especially with the ODBC driver market well-established. Mostly they represent a thin veneer on ODBC. This is not to say that JDBC does not need to evolve from the initial release; however, we feel that most new functionality belongs in higher- level APIs such as the object/relational mappings and embedded SQL mentioned in the previous section.

Monday, March 30, 2009

comparison Data types



/* This Program is a simple java Application which
shows how to compare two integer data types (this shows
some typical casses . Same rules applies to all the other
comparision operators in java*/
package datatypes;

public class IntCompare {

public static void main(String[] args) {
int i=22,j=33;
byte k=22,l=33;
short a=99,b=98;
char c='A',d='B';
float f=22.22F;
System.out.println(" int comp i < j " + (i<j));
//i <j returns boolean values true or false
// C language the same operator returns 0 or 1
// all the variables are converted to integer before
//comparision
System.out.println(" char comp " + (c<d));
System.out.println(" byte comp " + (k<l));
System.out.println(" short comp " + (a<b));
//int will be converted to float before comparisson
System.out.println(" float and int comp " + (f>i));

}

}


output:
int comp i < j true
char comp true
byte comp true
short comp false
float and int comp true


what is JDBC.

JDBC : ( Connecting Java and Databases )
Java Database Connectivity is a standard SQL database access interface, providing uniform access to a wide range of relational databases. It also provides a common base on which higher-level tools and interfaces can be built. This comes with an "ODBC Bridge". The Bridge is a library which implements JDBC in terms of the ODBC standard C API.
What Is JDBC ?
JDBC is a Java API for executing SQL statements. As a point of interest, JDBC is a trademarked name and is not an acronym; nevertheless, JDBC is often thought of as standing for "Java Database Connectivity". It consists of a set of classes and interfaces written in the Java programming language. JDBC provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API.

Using JDBC, it is easy to send SQL statements to virtually any relational database. In other words, with the JDBC API, it isn't necessary to write one program to access a Sybase database, another program to access an Oracle database, another program to access an Informix database, and so on. One can write a single program using the JDBC API, and the program will be able to send SQL statements to the appropriate database. And, with an application written in the Java programming language, one also doesn't have to worry about writing different applications to run on different platforms. The combination of Java and JDBC lets a programmer write it once and run it anywhere.

Java, being robust, secure, easy to use, easy to understand, and automatically downloadable
on a network, is an excellent language basis for database applications. What is needed is a way for Java applications to talk to a variety of different databases. JDBC is the mechanism for doing this.

JDBC extends what can be done in Java. For example, with Java and the JDBC API, it is possible to publish a web page containing an applet that uses information obtained from a remote database. Or an enterprise can use JDBC to connect all its employees (even if they are using a conglomeration of Windows, Macintosh, and UNIX machines) to one or more internal databases via an intranet. With more and more programmers using the Java programming language, the need for easy database access from Java is continuing to grow.

What Does JDBC Do?
Simply put, JDBC makes it possible to do three things:

  • establish a connection with a database
  • send SQL statements
  • process the results.

The following code fragment gives a basic example of these three steps:
Connection con = DriverManager.getConnection(
"jdbc:odbc:wombat", "login", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = getInt("a");
String s = getString("b");
float f = getFloat("c");
}
JDBC Is a Low-level API and a Base for Higher-level APIs :
JDBC is a "low-level" interface, which means that it is used to invoke (or "call") SQL commands directly. It works very well in this capacity and is easier to use than other database connectivity APIs, but it was designed also to be a base upon which to build higher-level interfaces and tools. A higher-level interface is "user-friendly," using a more understandable or more convenient API that is translated behind the scenes into a low-level interface such as JDBC. At the time of this writing, two kinds of higher-level APIs are under development on top of JDBC:

An embedded SQL for Java. At least one vendor plans to build this. DBMSs implement SQL, a language designed specifically for use with databases. JDBC requires that the SQL statements be passed as Strings to Java methods. An embedded SQL preprocessor allows a programmer to instead mix SQL statements directly with Java: for example, a Java variable can be used in a SQL statement to receive or provide SQL values. The embedded SQL preprocessor then translates this Java/SQL mix into Java with JDBC calls.

A direct mapping of relational database tables to Java classes. JavaSoft and others have announced plans to implement this. In this "object/relational" mapping, each row of the table becomes an instance of that class, and each column value corresponds to an attribute of that instance. Programmers can then operate directly on Java objects; the required SQL calls to fetch and store data are automatically generated "beneath the covers." More sophisticated mappings are also provided, for example, where rows of multiple tables are combined in a Java class.

As interest in JDBC has grown, more developers have been working on JDBC-based tools to make building programs easier, as well. Programmers have also been writing applications that make accessing a database easier for the end user. For example, an application might present a menu of database tasks from which to choose. After a task is selected, the application presents prompts and blanks for filling in information needed to carry out the selected task. With the requested input typed in, the application then automatically invokes the necessary SQL commands. With the help of such an application, users can perform database tasks even when they have little or no knowledge of SQL syntax.

Saturday, March 28, 2009

jdbc-example-Stored procedure



In this example we will see how to call the Stored procedure
have some in parameters,out parameter.


create Stored procedure :

create or replace procedure procthree(pone IN number,ptwo
IN number,pthree OUT number)
as
BEGIN
pthree:=pone+ptwo;
end procthree;
/

jdbc code using above Stored procedure example:

import java.sql.*;
class SP3
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println(" Connected 2 DB.....");
CallableStatement cstmt=con.prepareCall("{call procthree(?,?,?)}");
cstmt.setInt(1,12);
cstmt.setInt(2,22);
// Register out parameter
cstmt.registerOutParameter(3,Types.INTEGER);
// Execute the call.
cstmt.execute();
System.out.println(cstmt.getInt(3)); //34


}
}


Friday, March 27, 2009

jdbc-code-storedprocedure


In this example we will see how to call the Stored procedure have some
in parameters,
Store those values in the data base.

create Stored procedure :

create or replace procedure proctwo(pone IN number,ptwo IN number)as
begin
insert into temp values(pone,ptwo);
end proctwo;
/

jdbc using above Stored procedure example:

import java.sql.*;
class SP2
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" Connected 2 DB.....");
CallableStatement cstmt=con.prepareCall("{call proctwo(?,?)}");
cstmt.setInt(1,12);
cstmt.setInt(2,22);
cstmt.execute();
System.out.println("Executed");


}
}



Tuesday, March 24, 2009

callablestatement



creation of oracle Stored Procedure:
Here text is the table with one column.Use Sp to insert the value in the DB

create or replace procedure procone
as
i number;
BEGIN
i:=443;
insert into test values(i);
end procone;
/

jdbc example use above stored procedure:

import java.sql.*;
class CStmtDemo1
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" nected 2 DB.....");

CallableStatement cstmt=con.prepareCall("{call procone()}");
cstmt.execute();
}
}


Saturday, March 21, 2009

jdbc batch update



import java.sql.*;
class BatchUpdateDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" Connected 2 DB.....");

con.setAutoCommit(false);
Statement stmt=con.createStatement();
String vsql1="insert into emp2 values(1231,'chandu',100)";
String vsql2="insert into emp2 values(1224,'chandu',100)";
String vsql3="insert into emp2 values(1233,'chandu',100)";

try
{
stmt.clearBatch();
stmt.addBatch(vsql1);
stmt.addBatch(vsql2);
stmt.addBatch(vsql3);
stmt.executeBatch();
con.commit();//without commit the data won't be effected in DB.
}
// any of the above addBatch fail whole transaction rooBack
catch(Exception e)
{
con.rollBack();
}
System.out.println("Data has been entered successfully. ....");

}
}



Thursday, March 19, 2009

jdbc-connection-example





import java.sql.*;
class TransDemo
{
public static void main(String[] args)throws Exception
{
// Register the driver,In this case oracle thin driver

Class.forName("oracle.jdbc.driver.OracleDriver");

// getting connection object by passing URL, username,password

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

System.out.println(" Connected 2 DB.....");


}
}





jdbc-AutoCommit-example



import java.sql.*;
class TransDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println(" Connected 2 DB.....");
// By default setAutoCommit true,In this case after execute
every transaction ,automatically commit transaction.

con.setAutoCommit(false);
Statement stmt=con.createStatement();
String vsql="insert into emp2 values(123,'chandu',100)";

stmt.executeUpdate(vsql);
con.commit(); //with out commit the data won't be effected
in Database in case of setAutoCommit (false).

System.out.println("Table has been created.....");

}
}



Wednesday, March 18, 2009

jdbc example insert data database



import java.sql.*;
class InsertData
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" Connected 2 DB.....");

Statement stmt=con.createStatement();
String vsql="insert into emp2 values(12,'chandu',100)";

stmt.executeUpdate(vsql);
System.out.println("Table has been created.....");

}
}



TYPE-SCROLL-INSENSITIVE-Example



import java.sql.*;
class ScrollRS
{
public static void main(String[] args) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
("jdbc:odbc:ds","system","chandru");


System.out.println(" Connected 2 DB.....");
/* In case of scroll insensitive the changes made by another
application can't be pickup after opening the Resultset.
*/
Statement stmt=con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String vsql="select * from emp2";
ResultSet rs=stmt.executeQuery(vsql);
while(rs.next())
{
System.out.println("ENO:"+rs.getInt(1));
System.out.println("ENAME:"+rs.getString(2));
System.out.println("SAL:"+rs.getInt(3));
}

rs.absolute(1);
System.out.println("ENO:"+rs.getInt(1));
System.in.read();
System.out.println(" After change DB.....");
System.out.println("ENO:"+rs.getInt(1));




}
}


Tuesday, March 17, 2009

ResultSet.TYPE_SCROLL_SENSITIVE example



import java.sql.*;
class GetDataScrollable
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" nected 2 DB.....");
/*In case of scroll sensitive result set can use refreshRow method ,
to get the changes that are made by some other application after
the ResultSet is opened.*/
Statement stmt=con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String vsql="select * from emp3";
ResultSet rs=stmt.executeQuery(vsql);
System.out.println("RS has been opened.....");
rs.absolute(2);
System.out.println(rs.getString(1));
//System.in.read();
rs.updateString("ename","lax");
rs.updateRow();
}
}



Jdbc get the data from database example



import java.sql.*;
class GetData
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" Connected 2 DB.....");
//FARWARD_ONLY resultset is the default resultset
Statement stmt=con.createStatement();
String vsql="select * from emp4";
ResultSet rs=stmt.executeQuery(vsql);
while(rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}



}
}



Monday, March 16, 2009

jdbc code create table



import java.sql.*;
class CreateTable
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","chandru");
System.out.println(" Connected 2 DB.....");

Statement stmt=con.createStatement();
String vsql="create table em3(eno number(5)
primary key,ename varchar2(12),sal number(8))";

stmt.executeUpdate(vsql);
System.out.println("Table has been created.....");
}
}



JDBC code connect DataBase



import java.sql.*;
class DBCon
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Driver drv=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(drv);
Connection con=DriverManager.
getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott",
"tiger");

System.out.println("Connected to DB...");
}
}



Saturday, March 14, 2009

java operator precedence example



class EvolutionOrder
{
public static void main(String arg[])
{
System.out.println(m1(1) +m1(2)*m1(3)/m1(4)-m1(5)* m1(6));
}
public static int m1(int i)
{
System.out.println(i);
return i;
}
}

output:
1
2
3
4
5
6
-28


Friday, March 13, 2009

main-method-valid-declarations



class DiffMain
{
//static public void main(String[] args)

//final static public void main(String[] args)

//public static synchronized void main(String arg[])

public static final synchronized void main(String arg[])
{


System.out.println("hello world");

}
}



command-line-arguments-integer



class Cargint
{
public static void main(String[] args)
{
int sum=0;

for(String s:args)
{
int i=Integer.parseInt(s);

sum=sum+i;

}
System.out.println(sum);

}
}


run: java Cargint 10 20 30

output:
60


command-line-arguments-foreach



class Cargforeach
{
public static void main(String[] args)
{


for(String s:args)
{
System.out.println(s);
}

}
}

run: java Cargforeach java from sun

output:
java
from
sun



command line args example code



class Carg
{
public static void main(String[] args)
{

System.out.println("Hello World!");
System.out.println(args[0]);

}
}


run: java Carg 200

output:
Hello World!
200 ----> it consider as string



package example code



//javac -d . P2.java <-

package pack1;

class P2
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

compile: javac -d . P2.java
It will create one folder pack1 under it will put the . class file
run: java pack1.P2



Wednesday, March 11, 2009

Example code assertion




Demo 1:
public class Aser1 {

public static void main(String arg[])
{
int x=10;
assert (x==10); // valid
System.out.println(x);
}
}

For Run

java -ea Ase1
output: 10

If we write like this assert (x>10);
java -ea Ase1
output:
Assertion error

Demo 2:
public class Aser2 {

public static void main(String sr[])
{
int x=10;
assert(x>10):m1();
System.out.println(x);
}
public static int m1()
{
return 1000;
}
}

For Run

java -ea Aser2
output:
Assertion error:1000



Customized Serialization



package myio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;



class Dog2 implements Serializable
{
transient Cat1 c=new Cat1();
private void writeObject(ObjectOutputStream os)throws Exception
{
os.defaultWriteObject();
int i=c.j;
os.writeInt(i);
}
private void readObject(ObjectInputStream is)throws Exception
{
is.defaultReadObject();
int i=is.readInt();
c=new Cat1();
c.j=i;
}
}
class Cat1
{
int j=20;
}
public class SerDemo3
{
public static void main(String arg[])throws Exception
{
Dog2 d=new Dog2();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog2 d1=(Dog2)ois.readObject();
System.out.println(d1.c.j);
}
}

output:
20





Serialization object graph



package myio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog1 implements Serializable
{
Cat c=new Cat();
}
class Cat implements Serializable
{
int i=10;
Rat r=new Rat();
}
class Rat implements Serializable
{
int j=20;
}

class SerDemo2
{
public static void main(String arg[])throws Exception
{
Dog1 d=new Dog1();
FileOutputStream fos=new FileOutputStream("abc1.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc1.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog1 d1=(Dog1)ois.readObject();
System.out.println(d1.c.i);
System.out.println(d1. c.r.j);
}
}

output:
10
20


source code Serializable





import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;



class Dog implements Serializable
{
int i=10;
int j=20;
transient int k=30; // here k value serialize with default value.

}
public class Myser1 {
public static void main(String arg[])throws Exception

{
Dog d1=new Dog();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);

FileInputStream fis=new FileInputStream("abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"......"+d2.j+"...."+d2.k);
}
}


output:
10.....20.....0


core java Faqs

JRE vs JVM vs JDK

Java Runtime Environment (JRE)
A subset of the Java Development Kit (JDK) for end-users and developers who want to redistribute the runtime environment alone.The Java runtime environment consists of the Java virtual machine1, the Java core classes, and supporting files.
JDK
Java Development Kit. A software development environment for writing
applets and application in Java .
JVM
A software "execution engine" that safely and compatibly executes the
byte codes in Java class files on a microprocessor
Bite code:
Is a optimized set of instructions designed to be executed by Java-run time system, which is called the Java Virtual machine (JVM), i.e. in its standard form, the JVM is an Interpreter for byte code.
JIT- is a compiler for Byte code, The JIT-Complier is part of the JVM, it complies byte code into executable code in real time, piece-by-piece on demand basis.

variable:An item of data named by an identifier.Each variable has a type,such as int or Object,and a scope
class variable :A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions. Also called a static field. See also instance variable.
Instance variable :Any item of data that is associated with a particular object. Each instance of a class has its own copy of the instance variables defined in the class. Also called a field. See also class variable.
local variable :A data item known within a block, but inaccessible to code outside the block. For example, any variable defined within a method is a local variable and can't be used outside the method.
class method :A method that is invoked without reference to a particular object. Class methods affect the class as a whole, not a particular instance of the class. Also called a static method. also instance method.

instance method :Any method that is invoked with respect to an instance of a class. Also called simply a method. See also class method.


Interface: Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy. Using Interface, you can specify what a class must do but not how it does.

  • A class can implement more than one Interface.
  • An Interface can extend one or more interfaces, by using the keyword extends.
  • All the data members in the interface are public, static and Final by default.
  • An Interface method can have only Public, default and Abstract modifiers.
  • An Interface is loaded in memory only when it is needed for the first time.
  • A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface.
  • If the Implementation for all the methods declared in the Interface are not provided , the class itself has to declare abstract, other wise the Class will not compile.
  • If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid.
  • If a class implements tow interfaces both have identical method name and argument list, but different return types, the code will not compile.
An Interface can’t be instantiated. Interfaces Are designed to support dynamic method resolution at run time.
  • An interface can not be native, static, synchronize, final, protected or private.
  • The Interface fields can’t be Private or Protected.
  • A Transient variables and Volatile variables can not be members of Interface.
  • The extends keyword should not used after the Implements keyword, the Extends must always come before the Implements keyword.
  • A top level Interface can not be declared as static or final.
  • If an Interface species an exception list for a method, then the class implementing the interface need not declare the method with the exception list.
  • If an Interface can’t specify an exception list for a method, the class can’t throw an exception.
  • If an Interface does not specify the exception list for a method, he class can not throw any exception list.
The general form of Interface is
Access interface name {
return-type method-name1(parameter-list);
type final-varname1=value;
}

Marker Interfaces : Serializable, Clonable, Remote, EventListener,

Java.lang is the Package of all classes and is automatically imported into all Java Program
Interfaces: Clonable , Comparable, Runnable

Abstract Class: Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy.
  • Classes and methods can be declared as abstract.
  • Abstract class can extend only one Class.
  • If a Class is declared as abstract , no instance of that class can be created.
  • If a method is declared as abstract, the sub class gives the implementation of that class.
  • Even if a single method is declared as abstract in a Class , the class itself can be declared as abstract.
  • In abstract Class the keyword abstract must be used for method.
  • Abstract classes have sub classes.
Combination of modifiers Final and Abstract is illegal in java.

Abstract Class means - Which has more than one abstract method which doesn’t have method body but at least one of its methods need to be implemented in derived Class.

The general form of abstract class is :
abstract type name (parameter list);

The Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object.

Difference Between Interfaces And Abstract class ?
  • All the methods declared in the Interface are Abstract, where as abstract class must have atleast one abstract method and others may be concrete.
  • In abstract class keyword abstract must be used for method, where as in Interface we need not use the keyword for methods.
  • Abstract class must have Sub class, where as Interface can’t have sub classes.
  • An abstract class can extend only one class, where as an Interface can extend more than one.

What are access specifiers and access modifiers ?

Accesss specifiers
Public
Protected
Private
Access modifiers
Public
Abstract
Final
Static
Volatile
Synchronized
Transient
Native

• Public : The Variables and methods can be access any where and any package.
• Protected : The Variables and methods can be access same Class, same Package & sub class.
• Private : The variable and methods can be access in same class only.

Same class --------------------------- Public, Protected, and Private
Same-package & subclass ----------- Public, Protected
Same Package & non-sub classes ---- Public, Protected
Different package & Sub classes ------ Public, Protected
Different package & non- sub classes -- Public

Identifiers : are the Variables that are declared under particular Datatype.

Literals: are the values assigned to the Identifiers.

Static : access modifier.
Signature: Variable-Static int b; Method- static void meth(int x)
  • When a member is declared as Static, it can be accessed before any objects of its class are created and without reference to any object. Eg : main(),it must call before any object exit.
  • Static can be applied to Inner classes, Variables and Methods.
  • Local variables can’t be declared as static.
  • A static method can access only static Variables. and they can’t refer to this or super in any way.
  • Static methods can’t be abstract.
  • A static method may be called without creating any instance of the class.
  • Only one instance of static variable will exit any amount of class instances.
  • Final : access modifier
  • All the Variables, methods and classes can be declared as Final.
  • Classes declared as final class can’t be sub classed.
  • Method ‘s declared as final can’t be over ridden.
  • If a Variable is declared as final, the value contained in the Variable can’t be changed.
  • Static final variable must be assigned in to a value in static initialized block.
Transient : access modifier
Transient can be applied only to class level variables.
Local variables can’t be declared as transient.
During serialization, Object’s transient variables are not serialized.
Transient variables may not be final or static. But the complies allows the declaration and no compile time error is generated.

Volatile: access modifier
Volatile applies to only variables.
Volatile can applied to static variables.
Volatile can not be applied to final variables.
Transient and volatile can not come together.
Volatile is used in multi-processor environments.

Native : access modifier
Native applies to only to methods.
Native can be applied to static methods also.
Native methods can not be abstract.
Native methods can throw exceptions.
Native method is like an abstract method. The implementation of the abstract class and native method exist some where else, other than the class in which the method is declared.
Synchronized : access modifier
Synchronized keyword can be applied to methods or parts of the methods only.
Synchronize keyword is used to control the access to critical code in multi-threaded programming.


Declaration of access specifier and access modifiers :

Class ------------- Public, Abstract, Final
Inner Class ------- Public, Protected, Private, Final, Static,
Anonymous ------- Public, Protected, Private, Static
Variable ---------- Public, Protected, Private, Final, Static, Transient, Volatile, Native
Method ----------- Public, Protected, Private, Final, Abstract, Static, Native, Synchronized
Constructor -------- Public, Protected, Private
Free-floating code block ----- Static, Synchronized

Package : A Package is a collection of Classes Interfaces that provides a high-level layer of access protection and name space management.
Finalize( ) method:
  • All the objects have Finalize() method, this method is inherited from the Object class.
  • Finalize() is used to release the system resources other than memory(such as file handles& network connec’s.
  • Finalize( ) is used just before an object is destroyed and can be called prior to garbage collection.
  • Finalize() is called only once for an Object. If any exception is thrown in the finalize() the object is still eligible for garbage collection.
  • Finalize() can be called explicitly. And can be overloaded, but only original method will be called by Ga-collect.
  • Finalize( ) may only be invoked once by the Garbage Collector when the Object is unreachable.
The signature finalize( ) : protected void finalize() throws Throwable { }

Constructor( ) :A constructor method is special kind of method that determines how an object is initialized when created.
  • Constructor has the same name as class name.
  • Constructor does not have return type.
  • Constructor cannot be over ridden and can be over loaded.
  • Default constructor is automatically generated by compiler if class does not have once.
  • If explicit constructor is there in the class the default constructor is not generated.
  • If a sub class has a default constructor and super class has explicit constructor the code will not compile.

Object : Object is a Super class for all the classes. The methods in Object class as follows.
Object clone( )
final void notify( )
Int hashCode( )
Boolean equals( )
final void notify( )
Void finalize( )
String toString( )
Final Class getClass( )
final void wait( )

Class : The Class class is used to represent the classes and interfaces that are loaded by the JAVA Program.

String: String is Immutable and String Is a final class. The String class provides for strings whose value will not change.
One accessor method that you can use with both strings and string buffers is the length() method, which returns the number of characters contained in the string or the string buffer. The methods in String Class:-
toString( )
equals( )
indexOff( )
LowerCase( )
charAt( )
compareTo( )
lastIndexOff( )
UpperCase( )
getChars( )
subString( )
trim( )
getBytes( )
concat( )
valueOf( )
toCharArray( )
replace( )
ValueOf( ) : converts data from its internal formate into human readable formate.
String Buffer : Is Mutable , The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change.
In addition to length, the StringBuffer class has a method called capacity, which returns the amount of space allocated for the string buffer rather than the amount of space used.
The methods in StringBuffer Class:-
length( )
append( )
replace( )
charAt( )
setCharAt( )
capacity( )
insert( )
substring( )
getChars( )
ensureCapacity( )
reverse( )
setLength( )
delete( )

Wraper Classes : are the classes that allow primitive types to be accessed as Objects.
These classes are similar to primitive data types but starting with capital letter.
Number
Byte
Boolean
Double
Short
Character
Float
Integer
Long
primitive Datatypes in Java :
According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double, int.

Float class : The Float and Double provides the methods isInfinite( ) and isNaN( ).
isInfinite( ) : returns true if the value being tested is infinetly large or small.
isNaN( ) : returns true if the value being tested is not a number.

Character class : defines forDigit( ) digit( ) .
ForDigit( ) : returns the digit character associated with the value of num.
digit( ) : returns the integer value associated with the specified character (which is presumably) according to the specified radix.

String Tokenizer : provide parsing process in which it identifies the delimiters provided by the user, by default delimiters are spaces, tab, new line etc., and separates them from the tokens. Tokens are those which are separated by delimiters.

Observable Class: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update( ) method of each of its observers to notify the observers that it has changed state.
Observer interface : is implemented by objects that observe Observable objects.

Instanceof( ) :is used to check to see if an object can be cast into a specified type with out throwing a cast class exception.

IsInstanceof( ) : determines if the specified Object is assignment-compatible with the object represented by this class. This method is dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

Garbage Collection : When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection.
System.gc() method may be used to call it explicitly and does not force the garbage collection but only suggests that the JVM may make an effort to do the Garbage Collection.

this() : can be used to invoke a constructor of the same class.
super() :can be used to invoke a super class constructor.

Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.

Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
What is reflection API? How are they implemented
Reflection package is used mainlyfor the purpose of getting the class name. by useing the getName method we can get name of the class for particular application. Reflection is a feature of the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program.

What is heap in Java
JAVA is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpratation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than Intepratation phase interorate the class file line by line and give the proper result.

main( ) : is the method where Java application Begins.
String args[ ] : receives any command line argument during runtime.
System : is a predefined Class that provides access to the System.
Out : is output stream connected to console.
Println :displays the output.

Downcasting : is the casting from a general to a more specific type, i.e casting down the hierarchy. Doing a cast from a base class to more specific Class, the cast does;t convert the Object, just asserts it actually is a more specific extended Object.

Upcasting : byte can take Integer values.