Is the stack empty or not? false
The stack size is: 5
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack using
three different methods are as follows:
Using iterator() Method
Using forEach() Method
Using listIterator() Method
Using the iterator() Method
It is the method of the Iterator interface. It returns an iterator over the elements in the stack.
Before using the iterator() method import the java.util.Iterator package.
Syntax
Iterator<T> iterator()
Let's perform an iteration over the stack.
StackIterationExample1.java
import java.util.Iterator;
import java.util.Stack;
public class StackIterationExample1
{
public static void main (String[] args)
{
//creating an object of Stack class
Stack stk = new Stack();
//pushing elements into stack
stk.push("BMW");
stk.push("Audi");
stk.push("Ferrari");
stk.push("Bugatti");
stk.push("Jaguar");
//iteration over the stack
Iterator iterator = stk.iterator();
while(iterator.hasNext())
{
Object values = iterator.next();
System.out.println(values);
}
}
}
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Using the forEach() Method
Java provides a forEach() method to iterate over the elements. The method is defined in the
Iterable and Stream interface.
Syntax
default void forEach(Consumer<super T>action)
Let's iterate over the stack using the forEach() method.
StackIterationExample2.java
import java.util.*;
public class StackIterationExample2
{
public static void main (String[] args)
{
//creating an instance of Stack class
Stack <Integer> stk = new Stack<>();
//pushing elements into stack
stk.push(119);
stk.push(203);
stk.push(988);
System.out.println("Iteration over the stack using forEach() Method:");
//invoking forEach() method for iteration over the stack
stk.forEach(n ->
{
System.out.println(n);
});
}
}
Output:
Iteration over the stack using forEach() Method:
119
203
988
Using listIterator() Method
This method returns a list iterator over the elements in the mentioned list (in sequence),
starting at the specified position in the list. It iterates the stack from top to bottom.
Syntax
ListIterator listIterator(int index)
Parameter: The method parses a parameter named index.
Returns: This method returns a list iterator over the elements, in sequence.
Exception: It throws IndexOutOfBoundsException if the index is out of range.
Let's iterate over the stack using the listIterator() method.
StackIterationExample3.java
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;
public class StackIterationExample3
{
public static void main (String[] args)
{
Stack <Integer> stk = new Stack<>();
stk.push(119);
stk.push(203);
stk.push(988);
ListIterator<Integer> ListIterator = stk.listIterator(stk.size());
System.out.println("Iteration over the Stack from top to bottom:");
while (ListIterator.hasPrevious())
{
Integer avg = ListIterator.previous();
System.out.println(avg);
}
}
}
Output:
Iteration over the Stack from top to bottom:
988
203
119
17 JDBC
17.1 Introduction to JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses
JDBC drivers to connect with the database. There are four types of JDBC drivers:
JDBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
A list of popular classes of JDBC API are given below:
DriverManager class
Blob class
Clob class
Types class
Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the
following activities:
Connect to the database
Execute queries and update statements to the database
Retrieve the result received from the database.
17.2 JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.
Advantages:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function
calls.
The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
17.3Steps to connect Database
There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put
vender's Jar in the classpath, and then JDBC driver manager can detect and load the driver
automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the records
of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
17.5 Driver Manager
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and
the appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Useful methods of DriverManager class
Method Description
1) public static void registerDriver(Driver driver): is used to register the given driver with
DriverManager.
2) public static void deregisterDriver(Driver driver):
is used to deregister the given driver (drop the
3) public static Connection getConnection(String url): driver from the list) with DriverManager.
4) public static Connection getConnection(String is used to establish the connection with the
url,String userName,String password): specified url.
is used to establish the connection with the
specified url, username and password.
17.6 Connection Interface
A Connection is the session between java application and database. 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. The
Connection interface provide many methods for transaction management like commit(),
rollback() etc.
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it
is true.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
17.6 Statement
The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object
of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns
the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.
Example of Statement interface
Let’s see the simple example of Statement interface to insert, update and delete the record.
import java.sql.*;
class FetchRecord{
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","oracle");
Statement stmt=con.createStatement();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where
id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}
17.7 ResultSet
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next from the current p
2) public boolean previous(): is used to move the cursor to the one row previous from the curr
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row number in the Re
6) public boolean relative(int row): is used to move the cursor to the relative row number in the Res
positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column index of the curren
8) public int getInt(String columnName): is used to return the data of specified column name of the curren
9) public String getString(int is used to return the data of specified column index of the curren
columnIndex):
10) public String getString(String is used to return the data of specified column name of the c
columnName):
import java.sql.*;
class FetchRecord{
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","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UP
DATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}}
17.8Prerpared Statement
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop, insert, u
public ResultSet executeQuery() executes the select query. It returns an instance of Re
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
download this example
Example of PreparedStatement interface that updates the record
PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
download this example
Example of PreparedStatement interface that deletes the record
PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
stmt.setInt(1,101);
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
download this example
Example of PreparedStatement interface that retrieve the records of a table
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
download this example
Example of PreparedStatement to insert records until user press n
import java.sql.*;
import java.io.*;
class RS{
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","oracle");
PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
System.out.println("Do you want to continue: y/n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);
con.close();
}}
17.8 Resultset Meta data
he metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column
type etc. , ResultSetMetaData interface is useful because it provides methods to get
metadata from the ResultSet object.
Commonly used methods of ResultSetMetaData interface
Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in
public String getColumnName(int index)throws SQLException it returns the column name of the specifi
public String getColumnTypeName(int index)throws SQLException it returns the column type name for the s
public String getTableName(int index)throws SQLException it returns the table name for the specified
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.
Syntax:
public ResultSetMetaData getMetaData()throws SQLException
Example of ResultSetMetaData interface :
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
17.9 Database Meta Data
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.
Commonly used methods of DatabaseMetaData interface
public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the version number of the
JDBC driver.
public String getUserName()throws SQLException: it returns the username of the database.
public String getDatabaseProductName()throws SQLException: it returns the product name
of the database.
public String getDatabaseProductVersion()throws SQLException: it returns the product
version of the database.
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified
catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
How to get the object of DatabaseMetaData:
The getMetaData() method of Connection interface returns the object of DatabaseMetaData.
Syntax:
public DatabaseMetaData getMetaData()throws SQLException
Simple Example of DatabaseMetaData interface :
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("Driver Name: "+dbmd.getDriverName());
System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
download this example
Example of DatabaseMetaData interface that prints total number of tables :
import java.sql.*;
class Dbmd2{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
download this example
Example of DatabaseMetaData interface that prints total number of views :
import java.sql.*;
class Dbmd3{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"VIEW"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
17.10Callable Statement
CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.
The differences between stored procedures and functions are given below:
Stored Procedure Function
is used to perform business logic. is used to perform calculation.
must not have the return type. must have the return type.
may return 0 or more values. may return only one values.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be used in stored Exception handling using try/catch can't be
procedures. functions.
CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output. call sum4(?,?)}");
stmt.setInt(2,10);
stmt.setInt(3,43);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();
System.out.println(stmt.getInt(1));
}
}
Output: 53
17.12 Transaction Management
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent
state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event
of errors, power loss etc.
Advantage of Transaction Mangaement
fast performance It makes the performance fast because database is hit at the time of
commit.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydef
void commit() commits the transaction.
void rollback() cancels the transaction.
Simple example of transaction management in jdbc using Statement
Let's see the simple example of transaction management using Statement.
import java.sql.*;
class FetchRecords{
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","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
If you see the table emp400, you will see that 2 records has been added.
Example of transaction management in jdbc using PreparedStatement
Let's see the simple example of transaction management using PreparedStatement.
import java.sql.*;
import java.io.*;
class TM{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
}
if(answer.equals("rollback")){
con.rollback();
}
System.out.println("Want to add more records y/n");
String ans=br.readLine();
if(ans.equals("n")){
break;
}
}
con.commit();
System.out.println("record successfully saved");
con.close();//before closing connection commit() is called
}catch(Exception e){System.out.println(e);}
}}
18 Programs
Java Program to Print an Integer (Entered by the User)
Java Program to Add Two Integers
Java Program to Multiply two Floating Point Numbers
Java Program to Find ASCII Value of a character
Java Program to Compute Quotient and Remainder
Java Program to Swap Two Numbers
Java Program to Check Whether a Number is Even or Odd
Java Program to Check Whether an Alphabet is Vowel or Consonant
Java Program to Find the Largest Among Three Numbers
Java Program to Find all Roots of a Quadratic Equation
Java Program to Check Leap Year
Java Program to Check Whether a Number is Positive or Negative
Java Program to Check Whether a Character is Alphabet or Not
Java Program to Calculate the Sum of Natural Numbers
Java Program to Find Factorial of a Number
Java Program to Generate Multiplication Table
Java Program to Display Fibonacci Series
Java Program to Find GCD of two Numbers
Java Program to Find LCM of two Numbers
Java Program to Display Characters from A to Z using loop
Java Program to Count Number of Digits in an Integer
Java Program to Reverse a Number
Java Program to Calculate the Power of a Number
Java Program to Check Whether a Number is Palindrome or Not
Java Program to Check Whether a Number is Prime or Not
Java Program to Display Prime Numbers Between Two Intervals
Java Program to Check Armstrong Number
Java Program to Display Armstrong Number Between Two Intervals
Java Program to Display Prime Numbers Between Intervals Using Function
Java Program to Display Armstrong Numbers Between Intervals Using Function
Java Program to Display Factors of a Number
Java Program to Make a Simple Calculator Using switch...case
Java Program to Check Whether a Number can be Expressed as Sum of Two Prime
Numbers
Java Program to Find the Sum of Natural Numbers using Recursion
Java Program to Find Factorial of a Number Using Recursion
Java Program to Find G.C.D Using Recursion
Java Program to Convert Binary Number to Decimal and vice-versa
Java Program to Convert Octal Number to Decimal and vice-versa
Java Program to Convert Binary Number to Octal and vice-versa
Java Program to Reverse a Sentence Using Recursion
Java Program to calculate the power using recursion
Java Program to Calculate Average Using Arrays
Java Program to Find Largest Element of an Array
Java Program to Calculate Standard Deviation
Java Program to Add Two Matrix Using Multi-dimensional Arrays
Java Program to Multiply to Matrix Using Multi-dimensional Arrays
Java Program to Multiply two Matrices by Passing Matrix to a Function
Java Program to Find Transpose of a Matrix
Java Program to Find the Frequency of Character in a String
Java Program to Count the Number of Vowels and Consonants in a Sentence
Java Program to Sort Elements in Lexicographical Order (Dictionary Order)
Java Program to Add Two Complex Numbers by Passing Class to a Function
Java Program to Calculate Difference Between Two Time Periods
Java Code To Create Pyramid and Pattern
Java Program to Remove All Whitespaces from a String
Java Program to Print an Array
Java Program to Convert String to Date
Java Program to Round a Number to n Decimal Places
Java Program to Concatenate Two Arrays
Java Program to Convert Character to String and Vice-Versa
Java Program to Check if An Array Contains a Given Value
Java Program to Check if a String is Empty or Null
Java Program to Get Current Date/TIme
Java Program to Convert Milliseconds to Minutes and Seconds
Java Program to Add Two Dates
Java Program to Join Two Lists
Java Program to Convert List (ArrayList) to Array and Vice-Versa
Java Program to Get Current Working Directory
Java Program to Convert Map (HashMap) to List
Java Program to Convert Array to Set (HashSet) and Vice-Versa
Java Program to Convert Byte Array to Hexadecimal
Java Program to Create String from Contents of a File
Java Program to Append Text to an Existing File
Java Program to Convert a Stack Trace to a String
Java Program to Convert File to byte array and Vice-Versa
Java Program to Convert InputStream to String
Java Program to Convert OutputStream to String
Java Program to Lookup enum by String value
Java Program to Compare Strings
Java Program to Sort a Map By Values
Java Program to Sort ArrayList of Custom Objects By Property
Java Program to Check if a String is Numeric
Java Program to Create Directories
Java Program to Rename File
Java Program to List Files in a Directory
Java Program to Copy File
19 Interview Q and A
https://www.javatpoint.com/corejava-interview-questions
20 Find Output of following programs:
https://www.indiabix.com/java-programming/java-lang-class/026001
21 Ouick tips and tricks
1) There is no better way to do well in Coding interviews than practicing as many
coding problems as possible. This will not only train your mind to recognize
algorithmic patterns in problems but also give you the much-needed confidence
to solve the problem you have never seen before.
2) My second tips are to learn about as many data structure and algorithms as
possible. This is an extension of the previous tip but it also involves reading and
not just practicing. For example, If you know about the hash table you can also
many array and counter-based problems easily. Same is true for tree and graph.
3) Choosing the right data structure is a very important part of software
development and coding interview and unless and until you know them, you won’t
be able to choose.
4) Time yourself — candidates who solve interview problems within the time limit
and quickly are more likely to do well in the interview so you should also time
yourself.
5) Think of edge cases and run your code through them. Some good edge cases
might be the empty input, some weird input or some really large input to test the
boundary conditions and limits.
6) After solving the problem, try explaining it to a friend or colleagues how is also
interested in coding problems. This will tell you whether you have really
understood the problem or not. If you can explain easily means you understood.
Also, the discussion makes your mind work and you could come up with an
alternative solution and able to find some flaws in your existing algorithms.
Another useful tip to excel Coding interviews is to appear in the coding interview and
lots of them. You will find yourself getting better after every interview and this also
helps you to get multiple offers which further allows you to better negotiate and get
those extra 30K to 50K which you generally leave on a table if you just have one offer
in hand.