Programming in Java All
Programming in Java All
CSE2006
Course Type LP
Credits 3
Text Book(s):
1. Herbert Schildt, “Java The complete reference”, 11th edition, Oracle press , 2018
Reference Book(s):
1. Oracle University Reference E-Kit
2. Deitel and Deitel, “Java How to Program (Early objects)”,10thedition,Pearson, 2015
3. Cay S.Horstmann and Gary Cornell, “Core Java Vol I–
Fundamentals”,8thedition,Pearson,2011
4. Steven Holzner et al., “Java 2 Black Book”, Dreamtech press, Reprint edition 2010
Unit I –
Unit Description
• Java Introduction
• Java Hello World, Java JVM, JRE, and JDK, Difference between C
& C++, Java Variables, Java Data Types, Java Operators, Java
Input and Output, Java Expressions & Blocks, Java Comment
• Java Flow Control
• Java if...else, Java switch Statement, Java for Loop, Java for-each
Loop, Java while Loop, Java break Statement, Java continue
Statement
What is Java?
• Enterprise solutions
• Game development
• Secured web development
• Embedded systems
• Mobile application development
• Big Data Applications, and many more.
Why to Learn Java?
• int myNum = 5;
• float myFloatNum = 5.99f;
• char myLetter = 'D';
• boolean myBool = true;
• String myText = "Hello";
Anatomy of a class
Java Control Statements
• If Statement:
• In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of
the If statement gives a Boolean value, either true or false. In Java, there are
four types of if-statements given below.
1.Simple if statement
2.if-else statement
3.if-else-if ladder
4.Nested if-statement
Switch Statement:
• In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
• Points to be noted about the switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7
of Java
• Cases cannot be duplicated
• Default statement is executed when any of the case doesn't match the value of the expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, the next case is executed.
• While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
Loop Statements
switch (expression){
case value1:
statement1;
break; .
. case valueN:
statementN;
break;
default:
default statement;
}
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
2
Java for loop
• while(condition){
• //looping statements
•}
• public class Calculation {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• while(i<=10) {
• System.out.println(i);
• i = i + 2;
• }
• }
• }
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java do-while loop
• do
•{
• //statements
• } while (condition);
• public class Calculation {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• do {
• System.out.println(i);
• i = i + 2;
• }while(i<=10);
• }
• }
• Printing the list of first 10 even numbers
•0
•2
•4
•6
•8
• 10
Java break statement
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) { 0 1 2 3 4 5 6
System.out.println(i); 0
if(i>6) {
break;
}
}
}
}
0
1
2
3
4
5
6
Java continue statement
• public class ContinueExample {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• for(int i = 0; i<= 3; i++) {
• for (int j = i; j<=5; j++) {
• if(j == 6) {
• continue; 0 1 2 3 4 5 1 2 3 4 5 2 3 4 5 3 4 5
• }
• System.out.println(j);
• }
• }
• }
•
• }
0
1
2
3
5
---------
1
2
3
5
---------
2
3
5
Java Object-Oriented Programming
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Object
• Example 1:
• Object: car.
• State: color, brand, weight, model.
• Behavior: break, accelerate, turn, change gears.
• Example 2:
• Object: house.
• State: address, color, location.
• Behavior: open door, close door, open blinds.
Class
• Runtime errors can be handled in Java using try-catch blocks with the
following steps:
• Surround the statements that can throw a runtime error in try-catch
blocks.
• Catch the error.
• Depending on the requirements of the application, take necessary
action. For example, log the exception with an appropriate message.
Top 10 common Java compile errors and how to fix them
It includes syntax errors such as missing of semicolon(;), It includes errors such as dividing a number by zero,
misspelling of keywords and identifiers etc. finding square root of a negative number etc.
Major reasons why an exception Occurs
try {
statement(s)
} catch (ExceptiontType name) {
statement(s)
} finally {
statement(s)
}
class JavaException {
public static void main(String args[]){
try{
int d = 0;
int n =20;
int fraction = n/d;
}
catch(ArithmeticException e){
System.out.println("In the catch block due to Exception = "+e);
}
finally{
System.out.println("Inside the finally block");
}
}
}
List of Runtime Exception examples
1. ArithmeticException
2. NullPointerException
3. ClassCastException
4. DateTimeException
5. ArrayIndexOutOfBoundsException
6. NegativeArraySizeException
7. ArrayStoreException
8. UnsupportedOperationException
9. NoSuchElementException
10.ConcurrentModificationException
Constructors in Java
• The name of the constructors must be the same as the class name.
• Java constructors do not have a return type. Even do not use void as a
return type.
• There can be multiple constructors in the same class, this concept is
known as constructor overloading.
• The access modifiers can be used with the constructors, use if you
want to change the visibility/accessibility of constructors.
• Java provides a default constructor that is invoked during the time of
object creation. If you create any type of constructor, the default
constructor (provided by Java) is not invoked
Types of Java constructors
•Default Constructor
•No-Args Constructor
•Parameterized Constructor
Default Constructor
• If you do not create any constructor in the class, Java provides a
default constructor that initializes the object.
public class Main {
int num1;
int num2;
System.out.println("obj_y");
System.out.println("num1 : " + obj_y.num1);
System.out.println("num2 : " + obj_y.num2);
}
• obj_x
• num1 : 10
• num2 : 20
• obj_y
• num1 : 100
• num2 : 200
Constructor types:
Parameterized constructor Accepts arguments to initialize object properties public Car(String make, String model, int year)
with specific values.
Private constructor Restricts object creation from outside the class. private Employee()
Copy constructor Creates a new object by copying the state of public Person(Person other)
another object.
What is Inheritance?
• Single Inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance
•
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Multi-level Inheritance
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual Machine
(JVM), and other components that are required to run Java applications.JRE is the superset of JVM.
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in Java. When you
download JDK, JRE is also downloaded with it.
In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc, Java Debugger, etc).
Relationship between JVM, JRE, and JDK.
Interfaces in Java
• A class can extend another class similar to this an interface can extend another
interface. But only a class can extend to another interface, and vice-versa is not
allowed.
Difference Between Class and Interface
Class Interface
A class can contain concrete (with implementation) methods The interface cannot contain concrete (with implementation) methods.
The access specifiers used with classes are private, protected, and public. In Interface only one specifier is used- Public.
EXAMPLE 1: SWAP TWO NUMBERS IN JAVA USING A TEMPORARY VARIABLE
public class swap {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// Swapping logic using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
EXAMPLE 2: SWAP TWO NUMBERS IN JAVA WITHOUT USING A TEMPORARY VARIABLE
public class swap {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
class Sem1 class Sem2 extends Sem1
{ {
int m11,m12,m13,m14,avg1;
int m21,m22,m23,m24,avg2;
Sem1() Sem2()
{ {
m11=95; m21=89;
m12=93; m22=98;
m13=88; m23=97;
m14=90; m24=79;
avg1=(m11+m12+m13+m14)/4; avg2=(m21+m22+m23+m24)/4;
} }
} }
class Sem4 extends Sem3
class Sem3 extends Sem2 {
{
int m41,m42,m43,m44,avg4;
int m31,m32,m33,m34,avg3; Sem4()
Sem3() {
{ m41=79;
m31=87; m42=90;
m32=78; m43=77;
m33=88; m44=96;avg4=(m41+m42+m43+m44)/4;
m34=96; }
int totatavg()
avg3=(m31+m32+m33+m34)/4; {
return (avg1+avg2+avg3+avg4)/4;
} }
} }
class MultipleInheritanceExample2
{
public static void main(String args[])
{
semester 1 avg 91
semester 2 avg 90
semester 3 avg 87
semester 4 avg 85
total average 88
• Multithreading
• Introduction, Thread Creations, Thread Life Cycle, Life
Cycle Methods, Java Synchronization methods, User-defined
packages
What is a Thread in Java?
• String classes, methods, operations on Strings and 1-D Arrays, 2-D and Jagged Arrays and its operations
• Java Collections Framework, Java Collection Interface, Java List Interface, Java Array List, Java Vector, Java
Stack Introduction to Byte-oriented and Character-oriented streams, Java I/O Streams, and Java Reader/Writer
Java I/O Streams
• An input stream is used to read data from the source. And, an output
stream is used to write data to the destination.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
• For example, in our first Hello World example, we have used System.out to print a
string. Here, the System.out is a type of output stream.
Types of Streams
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
}
}
search() Method
To search for an element in the stack, we use the search() method. It returns the position of the element from the
top of the stack.
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Stack: [Dog, Horse, Cat]
// Add elements to Stack [1 to n] rest of list
animals.push("Dog"); Array [0 to n ]
animals.push("Horse"); Position of 1: dog
animals.push("Cat");
System.out.println("Stack: " + animals);
// Search an element
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
}
}
empty() Method
To check whether a stack is empty or not, we use the empty() method.
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Suitable for processing non-textual data such as Suitable for processing textual data such as
images, videos, etc. documents, HTML, etc.
Input and Output operations are performed using Input and Output operations are performed using
InputStream and OutputStream classes Reader and Writer classes
• Array will be -
• 10 0 37 0 0
Initialize while declaring
• We can also initialize the whole array while declaring it just by using
curly brackets {}. The string must be in quotes, whereas int, float, etc.,
do not require that.
• int[] myArray = {1, 2, 3, 4, 5}; // For integer type
• String[] myArray1 = {"A", "B", "C", "D"}; // For string type
How to Change an Array Element?
}
}
• Advantages
• Can access an array element value randomly just by using the index indicated
by the array.
• At a time, we can store lots of values in arrays.
• It becomes easier to create and work with the multi-dimensional arrays.
• Disadvantages
• Arrays in Java do not have in-built remove or add methods.
• In Java arrays, we need to specify the size of the array. So there might be a change
of memory wastage. So, it is recommended to use ArrayList.
• Arrays in Java are strongly typed.
UNIT 5
• Database Applications with JDBC
• Database Applications with JDBC: Defining the layout of the JDBC
API - Connecting to a database by using a JDBC driver – Submitting
queries and getting results from the database - Specifying JDBC driver
information externally.
Java Database Connectivity
• JDBC stands for Java Database Connectivity is a Java API(Application
Programming Interface) used to interact with databases.
• JDBC is a specification from Sun Microsystems and it is used by Java
applications to communicate with relational databases.
• We can use JDBC to execute queries on various databases and perform operations
like SELECT, INSERT, UPDATE and DELETE.
• JDBC API helps Java applications interact with different databases like
MSSQL, ORACLE, MYSQL, etc.
• It consists of classes and interfaces of JDBC that allow the applications to access
databases and send requests made by users to the specified database.
Purpose of JDBC
• JDBC has four main components that are used to connect with a
database as follows:
1.JDBC API
2.JDBC Driver Manager
3.JDBC Test Suite
4.JDBC-ODBC Bridge Drivers
JDBC API
• As the name suggests JDBC-ODBC Bridge Drivers are used to translate JDBC
methods to ODBC function calls.
• JDBC-ODBC Bridge Drivers are used to connect database drivers to the database.
Even after using JDBC for Java Enterprise Applications, we need an ODBC
connection for connecting with databases.
• JDBC-ODBC Bridge Drivers are used to bridge the same gap between JDBC and
ODBC drivers.
• The bridge translates the object-oriented JDBC method call to the procedural
ODBC function call.
• It makes use of the sun.jdbc.odbc package. This package includes a native library
to access ODBC characteristics.
Architecture of JDBC
The major components of JDBC architecture
1.Application
2.The JDBC API
3.DriverManager
4.JDBC Drivers
5.Data Sources
• Application
• Applications in JDBC architecture are java applications like applets or
servlet that communicates with databases.
• JDBC API
• The JDBC API is an Application Programming Interface used
to create Databases. JDBC API uses classes and interfaces to connect
with databases. Some of the important classes and interfaces defined
in JDBC architecture in java are the DriverManager class, Connection
Interface, etc.
• DriverManager
• DriverManager class in the JDBC architecture is used to establish a
connection between Java applications and databases.
• Using the getConnection method of this class a connection is established between
the Java application and data sources.
• JDBC Drivers
• JDBC drivers are used to connecting with data sources.
• All databases like Oracle, MSSQL, MYSQL, etc. have their drivers, to connect
with these databases we need to load their specific drivers.
• Class is a java class used to load drivers. Class.forName() method is used to load
drivers in JDBC architecture.
Data Sources
• Data Sources in the JDBC architecture are the databases that we can
connect using this API.
• These are the sources where data is stored and used by Java
applications.
• JDBC API helps to connect various databases like Oracle, MYSQL,
MSSQL, PostgreSQL, etc.
Types of JDBC Architecture
• 3-tier model is a complex and more secure model of JDBC architecture in java.
• In this model the user queries are sent to the middle tier and then they are executed
on the data source.
• Here, the java application is considered as one tier connected to the data
source(3rd tier) using middle-tier services.
• In this model user queries are sent to the data source using middle-tier services,
from where the commands are again sent to databases for execution.
• The results obtained on the database are again sent to the middle-tier and then to
the user/application.
Interfaces of JDBC API
• Steps to connect a Java program using JDBC API. 1. Load Driver: Load JDBC
Driver for specific databases using forName() method of class Class.
Syntax: Class.forName("com.mysql.jdbc.Driver")
• 2. Create Connection: Create a connection with a database using DriverManager
class. Database credentials are to be passed while establishing the connection.
Syntax: DriverManager.getConnection()
• 3. Create Query: To manipulate the database we need to create a query using
commands like INSERT, UPDATE, DELETE, etc. These queries are created and
stored in string format. Syntax: String sql_query = "INSERT INTO
Student(name, roll_no) values('ABC','XYZ')"
• 4. Create Statement: The query we have created is in form of a
string. To perform the operations in the string on a database we need to
fire that query on the database. To achieve this we need to convert a
string object into SQL statements. This can be done
using createStatement() and prepareStatement() interfaces.
Syntax: Statement St = con.createStatement();
• 5. Execute Statement: To execute SQL statements on the database we can use
two methods depending on which type of query we are executing.
• Execute Update: Execute update method is used to execute queries like insert,
update, delete, etc. Return type of executeUpdate() method is int. Syntax: int
check = st.executeUpdate(sql);
• Execute Query: Execute query method is used to execute queries used to display
data from the database, such as select. Return type of executeQuery() method is
result set. Syntax: Resultset = st.executeUpdate(sql);
• 6. Closing Statement: After performing operations on the database, it is better to
close every interface object to avoid further conflicts. Synatx: con.close();
Java Persistence API
• The Java Persistence API (JPA) is the Java API specification that
bridges the gap between relational databases and object-oriented
programming by handling the mapping of the Java objects to the
database tables and vice-versa.
• This process is known as the Object Relational Mapping (ORM). JPA
can define the way Java classes (entities) are mapped to the database
tables and how they can interact with the database through the
EntityManager, the Persistence context, and transactions.
Key Terminologies in JPA
• Entity
• EntityManager
• Persistence Context
• Criteria API
• JPQL (Java Persistence Query Language)
• Persistence Unit
Where to use JPA?
• JPA in Java can be called Java Persistence API (JPA) which can
simplify the process of working with the database by providing object
relationship mapping structure CRUD operations (Create, Read,
Update, Delete) are actions especially if it contains database abuse.
JPA CRUD operation
• The Create operation involves inserting new records into the database.
In JPA, this is achieved by the persisting new entity instances.
• Steps to implement the create operation:
• Create a new instance of the entity class
• Set the values for its attributes.
• Use the EntityManagers persist() method to make entity managed and
persistent.
Example:
• EntityManager em = entityManagerFactory.createEntityManager();
• EntityTransaction transaction = em.getTransaction();
• transaction.begin();
• //create the instance of the entity
• Employee employee = new Employee();
• //set the attributes
• employee.setName("John");
• employee.setSalary(50000);
• em.persist(employee);
• transaction.commit();
Read Operation
• The read operation involves the retrieving the existing records from
the database. In JPA, this is the typically done using primary keys of
the entity.
• Steps to implement :
• Use the EntityManagers find() method to the retrieve the entity by its
primary key.
• Example:
• Employee employee = em.find(Employee.class, 1L);
Update Operation
• The update operation involves modifying the existing records in the database. In
JPA, this is the accomplished by the updating managed by the entity instances.
• Steps to implement:
• Retrieve the entity using Entitymanagers find() method or the query.
• Modify the arrtibutes of the entity.
• Use the EntityManagers merge() method to the update the entity in database.
• Example:
• Employee employee = em.find(Employee.class, 1L);
• employee.setSalary(55000);
• em.merge(employee);
Delete Operation
• The delete operation involves removing records from the database. In JPA, this
can be done by removing the managed entity instances.
• Steps to implement:
• Retrieve the entity using the EntityManagers find() method or the query.
• Use the EntityManagers remove() method to the delete entity from the database.
• Example:
• Employee employee = em.find(Employee.class, 1L);
• em.remove(employee);
What Is an ORM Tool?
Difference Different
Same package Same package
Access Modifier Same class Package package non-
subclass non-subclass
subclass subclass
Private Yes No No No No
Output:
VIT
Public Access Modifier
// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java I am an animal.
public class Main { I have 4 legs.
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
// Step 2: Construct a 'Statement' object called 'stmt' inside the Connection created
Statement stmt = conn.createStatement();
){
// Step 3: Write a SQL query string. Execute the SQL query via the 'Statement'.
// The query result is returned in a 'ResultSet' object called 'rset'.
String strSelect = "select title, price, qty from books";
System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo For debugging
} catch(SQLException ex) {
ex.printStackTrace();
} // Step 5: Close conn and stmt - Done automatically by try-with-resources (JDK 7)
}
}
Synchronization in Java