HashMap vs TreeMap vs HashTable vs concurrentHashMap values and keys

import java.util.*;
import java.util.concurrent.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
//Multiple null values allowed
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2”,null);
hashMap.put(“null3″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

//No nulls as keys as well as values too
//thread safe
Map<String,String> conMap= new ConcurrentHashMap<String,String>();
conMap.put(“null1″,”null”);
conMap.put(“null”,”nuller”);
System.out.println(conMap);
}
}

 

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
{null=null-1, null1=nuller}
{null=nuller, null1=null}

If we put null as key in treemap or hashtable or concurrentHastable then it won’t  throws any  error at Compile Time.but it will throw below error at runtime

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
Exception in thread “main” java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:464)
at StaticVsNormalVsNo_Imports.main(StaticVsNormalVsNo_Imports.java:44)

Static vs Normal vs No imports in JAVA

Why imports are useful:

An import declaration allows a static member or a named type to be referred to by a simple name that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name.

A single-type-import declaration imports a single named type, by mentioning its canonical name.

A type-import-on-demand declaration imports all the accessible types of a named type or package as needed. It is a compile time error to import a type from the unnamed package.

A single static import declaration imports all accessible static members with a given name from a type, by giving its canonical name.

A static-import-on-demand declaration imports all accessible static members of a named type as needed.

http://stackoverflow.com/questions/2903166/meaning-of-the-import-statement-in-a-java-file

What happen if we don’t declare imports in JAVA file:

The below program I am trying to call one of the method add of Arraylist i.e java.util.Arraylist i.e https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(E) .As i didn’t declared any imports in my .java file it throws error like below.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
Arraylist arraylist=new Arraylist();
System.out.println(arraylist.add());
}
}

o/p:
D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java
StaticVsNormalVsNo_Imports.java:4: error: cannot find symbol
System.out.println(arraylist.add());
^
symbol: method add()
location: variable arraylist of type Arraylist
1 error

If we try to  get rid of the error by doing some changes like creating my own Arraylist class as below.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
Arraylist arraylist=new Arraylist();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

class Arraylist{
public String add(int a){
return “Mehtod message……..”+a;
}
}

o/p:
D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
Mehtod message……..10
Arraylist@15db9742

But it is not the functionality what i intended to do  so I move one step forward and I am giving here the fully qualified name i.e java.util.Arraylist<E>.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
java.util.ArrayList<Integer> arraylist=new java.util.ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

class Arraylist{
public String add(int a){
return “Mehtod message……..”+a;
}
}

o/p:
D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]

Now functionality is working as expected ,but what if i want’s to use 100 or 10 arraylists.In this case writing of java.util.ArrayList<Integer> arraylist=new java.util.ArrayList<Integer>(); 100 times or 10 times doesn’t make sense.So here java people import statement to rescue.

import java.util.ArrayList;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new .ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

o/p:

true [10]

What import java.util.ArrayList saying is whenever compiler sees the word ArrayList in the class it will use the java.util.ArrayList i.e in the JAVA API document there is a package called util and in that package there is class called ArrayList.

Here A package may contains many number of classes if i want to use one or more classes in a perticular package ,We are having an option wildcard character(*).If compiler sees the * symobol in import declaration it will search for all the classes in the entire package.

import java.util.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

}
}

o/p:

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null1=null, null2=null}
{null=null-1, null1=nuller}

static imports in JAVA:

If we want to access the static members and methods of a class with out using the classname evrytime i.e Classname.XXXXX etc.Here is the example

System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.toHexString(123));

instead of putting class name every time we will go for static import.

import java.util.*;
import java.util.concurrent.*;

import static java.lang.System.out;
import static java.lang.Integer.*;
//static import won’t work
public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
out.println(MAX_VALUE);
out.println(MIN_VALUE);
out.println(toHexString(123));

o/p:

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b

but it is having dis advantage like

  • readability
  • both Long and Integer having MAX_VALUE etc similar properties in this case if we put wild card import(*)  it leads us to Compile Time Error.

Creating object(s) for class,interface,Abstract class,final class and enum in JAVA.

In java every communication among the classes merely done by the methods with the help of objects.The below link shows the various advantages with object in java.

Advantages with Object:

  • Define the structure and behavior of a class.
  • Independence-i.e One object values doesn’t affects the other object values.
  • Modularity- Once it got created ,We can move the object over methods or any where in the program.

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

WHY WE NEED OBJECT IN JAVA….? 

Creating a object for Class:

  • There are numerous ways to create an object for a particular class in java.But here i am showing only the most generalized way i.e using new keyword.

class Demo{
public String string;
//Definfing the structure of class
public Demo(String str){
this.string=str;
System.out.println(“In construcor”+string);
}
//Here we are changing the behabiour of class through method
public String getName(){
return “Brad Pitt”;
}
}
public class Demo_Object{
public static void main(String[] args)throws Exception{
//creating the object with new() operator
Demo demoObject=new Demo(” Mr..”);
String str=demoObject.getName();
System.out.println(str);
}
}

o/p:
D:\OCJP>javac Demo_Object.java

D:\OCJP>java Demo_Object
In construcor Mr..
Brad Pitt

 

Creating Object for an interface:

As all of us knew that interface is a kind of class but the only difference we see is abstraction i.e interface is 100% abstract.Directly we can’t create object for interface.Why so,Here are nice explanations

https://www.quora.com/Why-cant-we-create-an-object-to-interface-in-Java

http://softwareengineering.stackexchange.com/questions/263301/i-want-to-understand-clearly-why-cant-we-instantiate-an-object-of-an-abstract-c

But through Anonymous classes we can create the objects.Example programs are below.

interface TestInterface{
String toString();
}

public class Object_Creation3{
public static void main(String[] args)throws Exception{
System.out.println(new TestInterface(){
public String toString(){
return “HAAAAAAAAAAAhhhaaaaaaa”+this.getClass();
}
});
}
}

o/p:

D:\OCJP>javac Object_Creation3.java

D:\OCJP>java Object_Creation3
HAAAAAAAAAAAhhhaaaaaaaclass Object_Creation3$1

 

With that syntax, you create an anonymous class, which is perfectly legal.

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class’ name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

 

Object Creation for Abstract class:

We can’t create for object for an Abstract class because if we do also the implementation must happen i.e through extends otherwise it will left remains as an empty template.

Because it’s abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

Take for example an “Animal” abstract class. There’s no such thing as a “pure” animal – there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn’t be able to instantiate plain Animal – that’s just a basic template. And there’s certain functionality that all animals share, such as “makeSound()", but that can’t be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

 

abstract class AbstractClassSample{
public String name;
//public AbstractClassSample(String name){
//this.name=name;
//}
public abstract void getName();
public String getCompany(){
return “OpenText”;
}
}

public class Abstract_ObjectCreation{
public static void main(String[] args)throws Exception{
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar pichai”);
System.out.println(abstractClassSample.getCompany());
}
}

o/p:

D:\OCJP>javac Abstract_ObjectCreation.java
Abstract_ObjectCreation.java:14: error: AbstractClassSample is abstract; cannot
be instantiated
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar picha
i”);
^
1 error

But we can get benefit with inheritance in the case of Abstract class by extending the abstract class to sub class and creating object for sub class as below.

abstract class AbstractClassSample{
public String designation=”Software Engineer”;
public AbstractClassSample(String d){
this.designation=d;
}
public abstract String getName();
public String getCompany(){
return “OpenText”;
}
}

class Abstract_Inheritence extends AbstractClassSample{
public int employeeId;
public Abstract_Inheritence(int no,String d){
super(d);
this.employeeId=no;
}
public String getName(){
return “Madhu”;
}
//public String getCompany(){
// return “PegaSystems”;
// }
}

public class Test_Inhiritence{
public static void main(String[] args)throws Exception{
Abstract_Inheritence abstract_Inheritence=new Abstract_Inheritence(123,”Associate”);
String s1=abstract_Inheritence.getName();
String s2=abstract_Inheritence.getCompany();
System.out.println(s1);
System.out.println(s2);
}
}

o/p:

D:\OCJP>javac Test_Inhiritence.java

D:\OCJP>java Test_Inhiritence
Madhu
OpenText

 

 

Object Creation for final class:

We can create object for a final class as normal i.e first use case.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
}
}

o/p:
D:\OCJP>javac FinalClassObject.java

D:\OCJP>java FinalClassObject
In ConstructorMr.Ramanjan

But final class cannot be extended .It will throgh the error as below.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject extends Final_Demo{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
System.out.println(“errorr……”);
}
}

o/p:

D:\OCJP>javac FinalClassObject.java
FinalClassObject.java:7: error: cannot inherit from final Final_Demo
public class FinalClassObject extends Final_Demo{
^
FinalClassObject.java:7: error: constructor Final_Demo in class Final_Demo canno
t be applied to given types;
public class FinalClassObject extends Final_Demo{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
2 errors

Creating Object for enum:

Enums cannot be intialized as they only a private constructor.

public enum Sample{
   READ,WRITE
}   


//Will get convetred the above code into below internally.


class Sample extends Enum {
    public static final Sample READ = new Sample("READ", 0);
    public static final Sample WRITE = new Sample("WRITE", 1);

    private Sample(String s, int i)
    {
        super(s, i);
    }

    // More methods, e.g. getter
}

Is Java is case-sensitive language?

YES…yes

Look at below snippet.

public class Main_Demo{
public static void main(String[] args)throws Exception{
System.out.println(“Keep Challenging………….”);
System.out.println(“Building tomorrow’s enterprise………….”);
String name=”cognizant”;
String NAME=”Infosys”;
System.out.println(name);
System.out.println(NAME);
}
}

 

D:\OCJP>javac Main_Demo.java

D:\OCJP>java Main_Demo
Keep Challenging………….
Building tomorrow’s enterprise………….
cognizant
Infosys

D:\OCJP>

Though both having same name as name because of the feature of case sensitiveness. It takes as two different strings.

Even if i compile with case it won’t work.

D:\OCJP>javac Main_Demo.java

D:\OCJP>java MAIN_DEMO
Error: Could not find or load main class MAIN_DEMO

D:\OCJP>java main_demo
Error: Could not find or load main class main_demo

D:\OCJP>Main_Demo
‘Main_Demo’ is not recognized as an internal or external command,
operable program or batch file.

D:\OCJP>java Main_Demo
Keep Challenging………….

Case sensitive  and case- insensitive Languages:

https://en.wikipedia.org/wiki/Case_sensitivity

Some computer languages are case-sensitive for their identifiers (C, C++, Java, C#, Verilog,[1] Ruby[2] and XML). Others are case-insensitive (i.e., not case-sensitive), such as Ada, most BASICs (an exception being BBC BASIC), Fortran, SQL[3] and Pascal.

 

 

Identifiers in JAVA

  • All the java components like  classes,interfaces,methods,variables,packages etc needs names in order to make benefit from them in our program .These names are called “identifiers”.
  • They are used to refer the actual reference value assigned to any variable etc.
  • Example:

 If i declare
String name=”India”;
int value=10;

Here name is a identifier of a class called java.lang.String;
Here value is an identifier which represents a primitive data type of int .It is having 10 as it’s value.

  • In the HelloWorld program, HelloWorld,String- HelloWorld, args, main and println are respresents methods. 

 

Legal Identifiers:

The set of rules of the compiler to determine whether a name is legal or not.Legal identifiers are must be composed of following combinations.They are

  • Numbers(0-9)
  • Currency Symbols($ as JAVA supports)
  • Connecting Characters(_)
  • Unicode characters(A_Z ,a-z,$,_)

Example:

public class Identifiers{
public static void main(String[] args)throws Exception{
int _a=10;
int _________abc_bc=10;
int abc_____455_dfj=10;
int a#=10;
int a$=10;
int $res=10;
int &iop=10;
int 34_u=10;
int char=10;
System.out.println(_a);
System.out.println(_________abc_bc);
System.out.println(abc_____455_dfj);
System.out.println(a#);
System.out.println(a$);
System.out.println($res);
System.out.println(&iop);
System.out.println(34_u);
System.out.println(char);
}

output:

D:\OCJP>javac Identifiers_Test.java
Identifiers_Test.java:6: error: illegal character: ‘#’
int a#=10;
^
Identifiers_Test.java:9: error: not a statement
int &iop=10;
^
Identifiers_Test.java:9: error: ‘;’ expected
int &iop=10;
^
Identifiers_Test.java:10: error: illegal underscore
int 34_u=10;
^
Identifiers_Test.java:10: error: not a statement
int 34_u=10;
^
Identifiers_Test.java:11: error: not a statement
int char=10;
^
Identifiers_Test.java:11: error: ‘;’ expected
int char=10;
^
Identifiers_Test.java:11: error: not a statement
int char=10;
^
Identifiers_Test.java:11: error: ‘;’ expected
int char=10;
^
Identifiers_Test.java:15: error: illegal character: ‘#’
System.out.println(a#);
^
Identifiers_Test.java:15: error: illegal start of expression
System.out.println(a#);
^
Identifiers_Test.java:18: error: illegal start of expression
System.out.println(&iop);
^
Identifiers_Test.java:19: error: illegal underscore
System.out.println(34_u);
^
Identifiers_Test.java:19: error: ‘)’ expected
System.out.println(34_u);
^
Identifiers_Test.java:19: error: illegal start of expression
System.out.println(34_u);
^
Identifiers_Test.java:20: error: ‘.class’ expected
System.out.println(char);
^
Identifiers_Test.java:21: error: reached end of file while parsing
}
^
17 errors

so by above program we came to know that we should fallow some rules in order to make it as an identifier.

Rules of Legal Identifiers:

  • It shouldn’t start with digit(0-9).
  • It shouldn’t  start with special charactes like (@ # %^&*()!)
  • It shouldn’t contain the keyword i.e “char” “int”
  • It can have prefered length. “ppppppp______dfds_dsgfdg”.
  •  It shouldn’t contain white spaces.
  • _ can be first letter.$ can be used in midddle.Apart from no special charactes are allowd.

Now i have removed all the invalid identifier declarations .It is working fine as expected.

public class Identifiers_Test{
public static void main(String[] args)throws Exception{
int _a=10;
int _________abc_bc=10;
int abc_____455_dfj=10;
int a_=10;
int a$=10;
//int a#=10;
//int $res=10;
//int &iop=10;
//int 34_u=10;
//int char=10;
System.out.println(_a);
System.out.println(_________abc_bc);
System.out.println(abc_____455_dfj);
//System.out.println(a#);
System.out.println(a$);
System.out.println(a_);
//System.out.println(a#);
//System.out.println($res);
//System.out.println(&iop);
//System.out.println(34_u);
//System.out.println(char);
}
}

output:

D:\OCJP>javac Identifiers_Test.java

D:\OCJP>java Identifiers_Test
10
10
10
10
10

D:\OCJP>

 

Why we should follow identifier rules:

  • Conflicts like int a-=10; If we declare like this compile got confused to choose whether it is a short hand operator or identifier.

Could usage:

Could can be used in several situations.Some of them are 

Possibility : 

  • Heavy rains could cause the road damage.
  • Heavy consumption of cigarette could cause  cancer.
  • Why did you do that? It could have broken your legs.
  • You could have called me first.
  • Due to hectic schedule,I couldn’t make it happen.

Ability:

  • I could play football when I was 18 years old.
  • Yesterday,I couldn’t eat full meal .

Suggestions:

  • You could have spent your time in new York.
  • We could take a auto because it’s too far.
  • We could go to a movie if all are interested.
  • You could have taken Cappuccino .

Request:

  • Could I have something to drink?
  • Couldn’t you help me with this for just  a minute?
  • Couldn’t he thinks about you?
  • Could you please help me out?

Permission:

  • Could I take this Friday off?
  • Could I take your pencil?
  • Could I use your laptop for sometime?
  • Could I take advantage over her?

It also used to tell something that has no possibility .

Janvir couldn’t have seen him .

Statement(I) in JDBC

public interface Statement
extends Wrapper, AutoCloseable

The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statementobjects. All execution methods in the Statement interface implicitly close a statment’s current ResultSet object if an open one exists.

Example:

package practice;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CheckInsertTable {
public static void main(String[] args) throws SQLException {
String url = “jdbc:oracle:thin:@localhost:1521:xe”;
String uname = “system”;
String pwd = “madhu”;
String Tablename = “Tagnames_companies”;
Check_Insert_Commit_Connection_Interface object = new Check_Insert_Commit_Connection_Interface();
Connection connection = object.makeConnection(url, uname, pwd);
connection.setAutoCommit(true);
Statement statement = connection.createStatement();
boolean b = object.checTableExists(connection, Tablename);
System.out.println(b);
if (!b) {
object.createNewTable(Tablename, statement);
boolean b2 = object.checTableExists(connection, Tablename);
System.out.println(b2);
if (b2) {
object.insetTheRecords(statement, Tablename);
object.readTheTable(Tablename, statement);
statement.close();
connection.close();
} else {
System.out.println(“Some problem…………!”);
}
} else {
System.out.println(“Table already exists…..!”);
}
}
}

class Check_Insert_Commit_Connection_Interface {
public boolean checTableExists(Connection connection, String tablename) throws SQLException {
Boolean boolean1 = false;
DatabaseMetaData md = connection.getMetaData();
String[] strings = { “TABLE” };
ResultSet rs = md.getTables(null, null, “%”, strings);
while (rs.next()) {
if (rs.getString(3).equalsIgnoreCase(tablename)) {
boolean1 = true;
}
}
return boolean1;
}

public void readTheTable(String tablename, Statement statement) throws SQLException {
ResultSet resultSet = statement.executeQuery(“select * from ” + tablename);
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
System.out.println(“————————————“);
}
}

public void insetTheRecords(Statement statement, String tablename) {
try {
statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
+ “VALUES (1,’Tcs’,’Experience The Certainity’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
+ “VALUES (2,’Infosys’,’Powered by Intellect,Driven by values’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
+ “VALUES (3,’Pega Sysytems’,’Build for the change’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createNewTable(String tablename, Statement statement) {
String createTableSQL = “CREATE TABLE ” + tablename + “(” + “COMPANY_ID NUMBER(5) NOT NULL, ”
+ “COMPANYNAME VARCHAR(20) NOT NULL, ” + “COMPANYTAGNAME VARCHAR(40) NOT NULL, ”
+ “CREATED_DATE DATE NOT NULL, ” + “PRIMARY KEY (COMPANY_ID) ” + “)”;
try {
int no = statement.executeUpdate(createTableSQL);
System.out.println(no);
} catch (SQLException e) {
e.printStackTrace();
}
}

public Connection makeConnection(String url, String uname, String pwd) {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, uname, pwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;

}
}

output:

false
0
true
1
Tcs
Experience The Certainity
————————————
2
Infosys
Powered by Intellect,Driven by values
————————————
3
Pega Sysytems
Build for the change
————————————

db_comapanies_statement

Dis-advantages of Statement(I):

  • Only Static queries are available i.e no run time submission of arguments to a sql query.
  • SQL injection problem.

Advanatges:

  • In the long run, yes. If you are only running it once, no – but then it doesn’t matter because you are only running it once.
  • Best for DDL COMMANDS: CREATE,ALTER,DROP AND TRUNCATE.

    In practice you should always start with a PreparedStatement and only downgrade to a Statement if you have proven a performance problem.

Reference:

Statement Versus PreparedStatement

There’s a popular belief that using a PreparedStatement object is faster than using a Statement object. After all, a prepared statement has to verify its metadata against the database only once, while a statement has to do it every time. So how could it be any other way? Well, the truth of the matter is that it takes about 65 iterations of a prepared statement before its total time for execution catches up with a statement. This has performance implications for your application, and exploring these issues is what this section is all about.

When it comes to which SQL statement object performs better under typical use, a Statement or a PreparedStatement, the truth is that the Statement object yields the best performance. When you consider how SQL statements are typically used in an application–1 or 2 here, maybe 10-20 (rarely more) per transaction–you realize that a Statement object will perform them in less time than a PreparedStatement object. In the next two sections, we’ll look at this performance issue with respect to both the OCI driver and the Thin driver.

 

References:

 

 

Connection(I) in JDBC

public interface Connection
extends Wrapper, AutoCloseable

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object’s database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection’s configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection’s type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection’s type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);

 

The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData.

Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
Statement statement=connection.createStatement();

With the Connection(I) object help we are creating the statement .Similarlry,we can create for prepared and callable statements.

 

 

  • A sample program that checks if table is exists or not and it will create a new table and displays the contents of the table.Here we are using two  methods executeUpdate() and execute() etc.
  • executeUpdate

    int executeUpdate(String sql)
                      throws SQLException
    Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.Note:This method cannot be called on a PreparedStatement or CallableStatement.

    Parameters:
    sql – an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
    Returns:
    either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
    Throws:
    SQLException – if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces a ResultSet object, the method is called on a PreparedStatement or CallableStatement
    SQLTimeoutException – when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement

     

  • execute

    boolean execute(String sql)
                    throws SQLException
    Executes the given SQL statement, which may return multiple results. In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple results or (2) you are dynamically executing an unknown SQL string.The execute method executes an SQL statement and indicates the form of the first result. You must then use the methods getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s).

    Note:This method cannot be called on a PreparedStatement or CallableStatement.

    Parameters:
    sql – any SQL statement
    Returns:
    true if the first result is a ResultSet object; false if it is an update count or there are no results
    Throws:
    SQLException – if a database access error occurs, this method is called on a closed Statement, the method is called on a PreparedStatement or CallableStatement
    SQLTimeoutException – when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement
    See Also:
    getResultSet(), getUpdateCount(), getMoreResults()

     

  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.Date;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class CheckInsertTable {
    public static void main(String[] args) throws SQLException {
    String url = “jdbc:oracle:thin:@localhost:1521:xe”;
    String uname = “system”;
    String pwd = “madhu”;
    String Tablename = “Tagnames_companies”;
    Check_Insert_Commit_Connection_Interface object = new Check_Insert_Commit_Connection_Interface();
    Connection connection = object.makeConnection(url, uname, pwd);
    connection.setAutoCommit(true);
    Statement statement = connection.createStatement();
    boolean b = object.checTableExists(connection, Tablename);
    System.out.println(b);
    if (!b) {
    object.createNewTable(Tablename, statement);
    boolean b2 = object.checTableExists(connection, Tablename);
    System.out.println(b2);
    if (b2) {
    object.insetTheRecords(statement, Tablename);
    object.readTheTable(Tablename, statement);
    statement.close();
    connection.close();
    } else {
    System.out.println(“Some problem…………!”);
    }
    } else {
    System.out.println(“Table already exists…..!”);
    }
    }
    }

    class Check_Insert_Commit_Connection_Interface {
    public boolean checTableExists(Connection connection, String tablename) throws SQLException {
    Boolean boolean1 = false;
    DatabaseMetaData md = connection.getMetaData();
    String[] strings = { “TABLE” };
    ResultSet rs = md.getTables(null, null, “%”, strings);
    while (rs.next()) {
    if (rs.getString(3).equalsIgnoreCase(tablename)) {
    boolean1 = true;
    }
    }
    return boolean1;
    }

    public void readTheTable(String tablename, Statement statement) throws SQLException {
    ResultSet resultSet = statement.executeQuery(“select * from ” + tablename);
    while (resultSet.next()) {
    System.out.println(resultSet.getString(1));
    System.out.println(resultSet.getString(2));
    System.out.println(resultSet.getString(3));
    System.out.println(“————————————“);
    }
    }

    public void insetTheRecords(Statement statement, String tablename) {
    try {
    statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
    + “VALUES (1,’Tcs’,’Experience The Certainity’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
    statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
    + “VALUES (2,’Infosys’,’Powered by Intellect,Driven by values’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
    statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
    + “VALUES (3,’Pega Sysytems’,’Build for the change’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    public void createNewTable(String tablename, Statement statement) {
    String createTableSQL = “CREATE TABLE ” + tablename + “(” + “COMPANY_ID NUMBER(5) NOT NULL, ”
    + “COMPANYNAME VARCHAR(20) NOT NULL, ” + “COMPANYTAGNAME VARCHAR(40) NOT NULL, ”
    + “CREATED_DATE DATE NOT NULL, ” + “PRIMARY KEY (COMPANY_ID) ” + “)”;
    try {
    int no = statement.executeUpdate(createTableSQL);
    System.out.println(no);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    public Connection makeConnection(String url, String uname, String pwd) {
    Connection connection = null;
    try {
    connection = DriverManager.getConnection(url, uname, pwd);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return connection;

    }
    }

    output:

    false
    0
    true
    1
    Tcs
    Experience The Certainity
    ————————————
    2
    Infosys
    Powered by Intellect,Driven by values
    ————————————
    3
    Pega Sysytems
    Build for the change
    ————————————

     

DatabaseMetadata(I) in JDBC

  • public interface DatabaseMetaData
    extends Wrapper
  • omprehensive information about the database as a whole.This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBCTM technology (“JDBC driver”) that is used with it. Different relational DBMSs often support different features, implement features in different ways, and use different data types. In addition, a driver may implement a feature on top of what the DBMS offers. Information returned by methods in this interface applies to the capabilities of a particular driver and a particular DBMS working together. Note that as used in this documentation, the term “database” is used generically to refer to both the driver and DBMS.

    A user for this interface is commonly a tool that needs to discover how to deal with the underlying DBMS. This is especially true for applications that are intended to be used with more than one DBMS. For example, a tool might use the methodgetTypeInfo to find out what data types can be used in a CREATE TABLE statement. Or a user might call the method supportsCorrelatedSubqueries to see if it is possible to use a correlated subquery or supportsBatchUpdates to see if it is possible to use batch updates.

    Some DatabaseMetaData methods return lists of information in the form of ResultSet objects. Regular ResultSet methods, such as getString and getInt, can be used to retrieve the data from these ResultSet objects. If a given form of metadata is not available, an empty ResultSet will be returned. Additional columns beyond the columns defined to be returned by the ResultSet object for a given method can be defined by the JDBC driver vendor and must be accessed by their column label.

    Some DatabaseMetaData methods take arguments that are String patterns. These arguments all have names such as fooPattern. Within a pattern String, “%” means match any substring of 0 or more characters, and “_” means match any one character. Only metadata entries matching the search pattern are returned. If a search pattern argument is set to null, that argument’s criterion will be dropped from the search.

     

  • https://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
  • A simple example on databasemaetadata(I)
  • ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)

    Retrieves a description of the tables available in the given catalog.
  • package practice;

    import java.sql.*;
    import oracle.jdbc.driver.*;

    class getVersion
    {
    public static void main (String args[])
    throws SQLException
    {
    // Load the Oracle JDBC driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    //Creates the Connection object
    Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
    // Create Oracle DatabaseMetaData object
    DatabaseMetaData meta = conn.getMetaData();
    // gets driver info:
    System.out.println(“JDBC driver version is ” + meta.getJDBCMajorVersion());
    System.out.println(“JDBC driver name is”+meta.getDriverName());

    DatabaseMetaData md = conn.getMetaData();
    String[] strings={“TABLE”};
    ResultSet rs = md.getTables(null, null, “%”,strings);
    while (rs.next()) {
    System.out.println(rs.getString(3));
    }
    }
    }

    output:

    JDBC driver version is 11
    JDBC driver name isOracle JDBC driver
    APEX$_ACL
    APEX$_WS_FILES
    APEX$_WS_HISTORY
    APEX$_WS_LINKS
    APEX$_WS_NOTES
    APEX$_WS_ROWS
    APEX$_WS_TAGS
    APEX$_WS_WEBPG_SECTIONS
    APEX$_WS_WEBPG_SECTION_HISTORY
    SYS_IOT_OVER_16977
    WWV_COLUMN_EXCEPTIONS
    WWV_DEMO_DEPT
    WWV_DEMO_EMP
    WWV_FLOWS
    WWV_FLOWS_RESERVED
    WWV_FLOW_ACTIVITY_LOG1$
    WWV_FLOW_ACTIVITY_LOG2$
    WWV_FLOW_ACTIVITY_LOG_NUMBER$
    etc…………………………………………………………………..

Driver Manger Class in JDBC

  • public class DriverManager
    extends Object
  • It is the satatic class in java SDK.
  • First, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. Typically, a JDBC application connects to a target data source using one of two classes:

    DriverManager: This fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path. Note that your application must manually load any JDBC drivers prior to version 4.0.

    DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object’s properties are set so that it represents a particular data source. See Connecting with DataSource Objects for more information. For more information about developing applications with the DataSource class, see the latest The Java EE Tutorial.

  • //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  • Class.forName() is not directly related to JDBC at all. It simply loads a class.

    Most JDBC Driver classes register themselves in their static initializers by calling registerDriver().

    registerDriver() is the real call that you hardly ever need to call yourself (unless you write your own JDBC driver).

    Note that in JDBC 4 you should not need either of those if your JDBC driver is up-to-date, as drivers can be found using the service location mechanisms instead (i.e. simply leave out that call and open your connection as usual). See the documentaton of DriverManager for details:

    The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

    my.sql.Driver

    Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

     

  • Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path.

    DriverManager.registerDriver() manually is potentially dangerous since it actually causes the Driver to be registered twice. If your code requires you to deregister a Driver to prevent a memory leak then you would only end up deregistering it once and leave a second instance registered.

https://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html

http://www.ibm.com/support/knowledgecenter/ssw_i5_54/rzaha/db2drivr.htm

  • Example:
  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class SimpleConnection {
    public static void main(String[] args) throws SQLException {
    String url=”jdbc:oracle:thin:@localhost:1521:xe”;
    String uname=”system”;
    String pwd=”madhu”;

    //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    try {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    //Class.forName(“oracle.jdbc.driver.OracleDriver”).newInstance();
    //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
    Statement statement=connection.createStatement();

    ResultSet resultSet=statement.executeQuery(“select * from contact”);
    while(resultSet.next()){
    System.out.println(resultSet.getString(1));
    }
    connection.close();
    }
    }

    output:

    madhu
    charan
    surbhi
    ammu
    indra

     

wordpress_db_statement

oracle ojdbc6.jar location: C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib