0% found this document useful (0 votes)
17 views

Java Basics Notes 1

Uploaded by

srinivasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java Basics Notes 1

Uploaded by

srinivasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Java

www.axessupskill.in
Agenda
▪ Java Introduction

▪ Download and install Java

▪ Download and install Eclipse IDE

▪ Java Variables

▪ Java Data Types

▪ Java Operators

www.axessupskill.in
What is Java?
▪ Java is a popular programming language, created in 1995.

▪ It is owned by Oracle, and more than 3 billion devices run Java.

▪ It is used for:
– Mobile applications (specially Android apps)
– Desktop applications
– Web applications
– Web servers and application servers
– Games
– Database connection
– And much, much more!

www.axessupskill.in
Why Use Java?
▪ Java works on different platforms (Windows, Mac, Linux etc.)

▪ It is one of the most popular programming language in the world

▪ It is easy to learn and simple to use

▪ It is open-source and free

▪ It is secure, fast and powerful

www.axessupskill.in
JDK, JRE and JVM
▪ JDK (Java Development Kit)

▪ JDK contains everything that will be required to develop and run Java application.

▪ JRE (Java Runtime Environment)

▪ JRE contains everything required to run Java application which has already been compiled. It
doesn’t contain the code library required to develop Java application.

▪ JVM (Java Virtual Machine)

▪ JVM is a virtual machine which works on top of your operating system to provide a recommended
environment for your compiled Java code. JVM only works with bytecode. Hence you need to
compile your Java application(.java) so that it can be converted to bytecode format (also known as
the .class file).

▪ Which then will be used by JVM to run an application. JVM only provide the environment needed
to executed Java Bytecode.

www.axessupskill.in
JDK, JRE and JVM

www.axessupskill.in
Download & Install Java
1) Download Link
▪ http://download.oracle.com/otn-
pub/java/jdk/9.0.4+11/c2514751926b4512b076cc82f959763f/jdk-9.0.4_windows-x64_bin.exe

www.axessupskill.in
2) Once the download is complete, run the exe for install JDK. Click Next

www.axessupskill.in
Java Environment Setup

www.axessupskill.in
Eclipse IDE
▪ https://www.eclipse.org/downloads/download.php?file=/oomph/epp/photon/R/eclipse-inst-
win64.exe

www.axessupskill.in
Download and Start Eclipse IDE

1
2
3

www.axessupskill.in
5

www.axessupskill.in
www.axessupskill.in
Create a Java Project
▪ To create a new Java project in Eclipse

Go to File  New  Java Project  Specify Project Name  Finish

www.axessupskill.in
IntelliJ IDE

www.axessupskill.in
Java
Variables
▪ What is a Variable?

▪ A variable is a container which holds value.

▪ Every variable is assigned a data type which designates the type and quantity of value it
can hold.

▪ In order to use a variable in a program you to need to perform 2 steps


– Variable Declaration
– Variable Initialization

www.axessupskill.in
Java Variables(Cont..)

www.axessupskill.in
Java Data Types

www.axessupskill.in
Java Operators

www.axessupskill.in
Agenda
▪ Control Statements

▪ Conditional/Statements(Selection Statements)

▪ Loops /Iterative Statements

▪ Jump Statements

www.axessupskill.in
Control Statements

www.axessupskill.in
If..else
▪ In this flowchart, the code will respond in the following way:
1. First of all, it will enter the loop where it checks the condition.
2. If the condition is true, the set of statements in ‘if’ part will be executed.
3. If the condition is false, the set of statements in the ‘else’ part will be executed.

www.axessupskill.in
Switch..case

▪ The switch statement defines multiple paths for execution of a set of statements. It is a
better alternative than using a large set of if-else statements as it is a multi-way branch
statement.

▪ In this Switch case flowchart, the code will respond in the following steps:
1. First of all it will enter the switch case which has an expression.
2. Next it will go to Case 1 condition, checks the value passed to the condition. If it is true, Statement
block will execute. After that, it will break from that switch case.
3. In case it is false, then it will switch to the next case. If Case 2 condition is true, it will execute the
statement and break from that case, else it will again jump to the next case.
4. Now let’s say you have not specified any case or there is some wrong input from the user, then it will
go to the default case where it will print your default statement.

www.axessupskill.in
Switch..case (Cont..)

www.axessupskill.in
While loop
▪ While statement: Repeat a group of
statements while a given condition is
true. It tests the condition before
executing the loop body.

▪ In this flowchart, the code will


respond in the following steps:
1. First of all, it will enter the loop
where it checks the condition.
2. If it’s true, it will execute the set of
code and repeat the process.
3. If it’s False, it will directly exit the
loop.

www.axessupskill.in
Do..while loop
▪ Do-while statement: It is like a while
statement, but it tests the condition at
the end of the loop body. Also, it will
executes the program at least once.

▪ In this do-while flowchart, the code will


respond in the following steps:
1. First of all, it will execute a set of
statements that is mentioned in your
‘do’ block.
2. After that, it will come to ‘while’ part
where it checks the condition.
3. If the condition is true, it will go back
and execute the statements.
4. If the condition is false, it will directly
exit the loop.

www.axessupskill.in
For loop
▪ For statement: For statement execute
a sequence of statements multiple
time where you can manage the loop
variable. You basically have 3
operations here: initialization,
condition and iteration.

▪ In this flowchart, the code will


respond in the following steps:
1. First of all, it will enter the loop
where it checks the condition.
2. Next, if the condition is true, the
statements will be executed.
3. If the condition is false, it directly
exits the loop.

www.axessupskill.in
When we use while, do..while &
for loops
▪ Scenario 1: If u want to travel by your own vehicle(two wheeler or four wheeler),You should know
how much petrol available in your vehicle and you know how much distance to travel.

▪ For loop --- Know the initial condition and no of iterations.

▪ Scenario 2: If u want to travel in a FLIGHT, You should buy a ticket then only you are eligible to
enter into the Flight.

▪ While loop ---- First satisfy the condition then Proceed.

▪ Scenario 3: If u want to travel in BUS, You can board the bus then buy the ticket.

▪ Do..while ---- Proceed first then checking.

www.axessupskill.in
Jump Statements
▪ Jump statement: Jump statement are used to transfer the control to another part of your
program. These are further classified into – break and continue.

www.axessupskill.in
Break statement
▪ Break statement: Whenever a break
statement is used, the loop is
terminated and the program control is
resumed to the next statement following the
loop

▪ In this flowchart, the code will respond in


the following steps:
1. First of all, it will enter the loop where it
checks the condition.
2. If the loop condition is false, it directly exits the
loop.
3. If the condition is true, it will then check the
break condition.
4. If break condition is true, it exists from the
loop.
5. If the break condition is false, then it will
execute the statements that are remaining in
the loop and then repeat the same steps.

www.axessupskill.in
Continue statement
▪ Continue statement: Continue statement is
another type of control statements. The
continue keyword causes the loop to
immediately jump to the next iteration of
the loop.

▪ In this flowchart, the code will respond in


the following steps:
1. First of all, it will enter the loop where it
checks the condition.
If the loop condition is false, it directly exits
the loop.
2. If the loop condition is true, it will execute
block 1 statements.
3. After that it will check for ‘continue’
statement. If it is present, then the
statements after that will not be executed in
the same iteration of the loop.
4. If ‘continue’ statement is not present, then
all the statements after that will be executed.

www.axessupskill.in
Input From the User
▪ Scanner class is to take the input from user which is imported from java.util.Scanner package.
Scanner input = new Scanner(System.in);

▪ Get Integer Input From the User


int number = input.nextInt();

▪ Get float, double and String Input


float myFloat = input.nextFloat();
double myDouble = input.nextDouble();
String myString = input.next();

www.axessupskill.in
Agenda
▪ Arrays

▪ Single Dimensional Array

▪ Multi Dimensional Array

▪ Strings

www.axessupskill.in
What are Java Arrays?
▪ An array is a container object that holds a fixed number of values of a single type.
▪ The length of an array is established when the array is created. After creation, its
length is fixed.
▪ There are 2 types of arrays
1. Single Dimensional
2. Two Dimensional(Double Dimensional)

www.axessupskill.in
Single Dimensional Array
▪ Declare array

▪ Insert values into array

▪ Find the size of array

▪ How to read/access values from array

www.axessupskill.in
Multi Dimensional Array
• Declare array

• Insert values into array

• Find the size of array

• How to read/access values from array

www.axessupskill.in
Strings
▪ length(): It returns count of total number of characters present in the String.

String s=“Welcome” s.length() 7

▪ concat() : Combines a specific string at the end of another string and ultimately returns a
combined string. It is like appending another string.

String s=“Welcome”
s.concat(s1) Welcome To Java
String s1=“ To Java”

▪ trim() : The java string trim() method removes the leading and trailing spaces.

String s=“ Welcome ” s.trim() Welcome

www.axessupskill.in
Strings
▪ charAt(): Returns a char value at the given index number. The index number starts from 0.

String s=“Welcome” s.charAt(3) c

▪ contains() : Searches the sequence of characters in this string. It returns true if sequence of char values are
found in this string otherwise returns false.

String s= “Welcome” s.contains(“Wel”) True

▪ equals() : Compares the two given strings based on the content of the string. If any character is not matched, it
returns false. If all characters are matched, it returns true.

String s=“Welcome” s.equals(“Welcome”) True

String s=“Welcome” s.equals(“welcome”) False

www.axessupskill.in
Strings
▪ equalsIgnoreCase() : Compares two string on the basis of content but it does not check the case
like equals() method. In this method, if the characters match, it returns true else false.

String s=“Welcome” s.equalsIgnoreCase(“Welcome”) True

String s=“Welcome” s.equalsIgnoreCase(“welcome”) True

▪ replace(): Returns a string, replacing all the old characters or CharSequence to new characters.
There are 2 ways to replace methods.

String s=“Welcome” s.replace(’e’, ’a’) Walcoma


String s=“Welcome To Java” s.replace(“Java”, ”Selenium”) Welcome To Selenium

www.axessupskill.in
Strings
▪ Substring() : Returns substring of a string based on starting index and ending index.

Starting Index
0 1 2 3 4 5 6
W E L C O M E
Ending Index
1 2 3 4 5 6 7

String s=“Welcome” s.substring(1,3) el

String s=“Welcome” s.substring(0,4) Welc

String s=“Welcome” s.substring(2,4) lc

www.axessupskill.in
Strings
▪ toLowerCase(): returns the string in lowercase letter.

String s=“WELCOME” s.toLowerCase() welcome

▪ toUpperCase(): returns the string in Uppercase letter.

String s=“welcome” s.toUpperCase() WELCOME

www.axessupskill.in
Agenda
▪ Class & Object

▪ Java Methods

▪ Java Constructor

www.axessupskill.in
Java Class & Object
Object1
class Employee
{ Employee emp1=new Employee();
int eid; emp1.eid=1020;
String ename; emp1.ename="John";
double sal; Variables emp1.sal=80000;
String job; emp1.job="Manager";
void display()
emp1.display();
{ Object2
System.out.println(eid);
Class

System.out.println(ename);
System.out.println(sal);
Employee emp2=new Employee();
System.out.println(job); emp2.eid=1021;
emp2.ename="David";
} Methods emp2.sal=50000;
void bonus()
{ emp2.job="Tech Assistant";
System.out.println((sal *10) /100);
} emp2.display();
}

www.axessupskill.in
Class & Object
▪ main() within class

www.axessupskill.in
Class & Object
▪ main() outside class
▪ In real time development, we create classes and use it from another class. It is a better approach
than previous one.

▪ We can have multiple classes in different java files or single java file.

Student.java Student1.java

www.axessupskill.in
Class & Object
▪ 3 ways to initialize object variables in java.
– By reference variable
– By method
– By constructor

www.axessupskill.in
Class & Object
▪ Initialization through reference variable

Student.java Student2.java

www.axessupskill.in
Class & Object
▪ Initialization through method

Student.java Student3.java

www.axessupskill.in
Class & Object
▪ Initialization through constructor

Student.java Student4.java

www.axessupskill.in
Java Methods
▪ A method is a set of code which is referred to by name and can be called (invoked) at any point in
a program simply by utilizing the method's name.

▪ A method as a subprogram that acts on data and often returns a value.

▪ Each method has its own name.

Parameter/s Returned Value


Case1  

Case2  

Case3  

Case4  

www.axessupskill.in
Java Constructor
▪ Constructor in java is a special type of method that is used to initialize the object.

▪ Java constructor is invoked at the time of object creation.

▪ Rules for creating java constructor:


1. Constructor name must be same as its class name.
2. Constructor must have no explicit return type.

▪ There are 2 Types of Constructors.

Constructor

Default Parameterized

www.axessupskill.in
Method V/s Constructor
• Method name can be anything.
• Method can return a value.
Method

• Need to call method explicitly.

• Constructor name must be same as class name.


• Constructor doesn't return a value.
Constructor

• Automatically invoked at the time of object creation.

www.axessupskill.in
Assignment
1. Create a Student class contains the following variables and methods.
– Class Name: Student
– Variables : SID , Sname, Sub1,Sub2,Sub3
– Methods:
▪ getStuData() Takes student details SID and Sname as parameters and assign them to variables.
▪ getStuMarks() Takes student marks as parameters and assign them to Sub1, Sub2, Sub3.
▪ totalMarks() Calculate total marks and print the student details with total marks.
– Now, create objects from Student class stu1, stu2 etc. Then call Student class methods.
2. Write a program to demonstrate constructor.
– Create a class ‘Calculation’ with 3 integer variable.
– Create a constructor for assign the values into variables.
– Then create another method ‘sum’ to calculate sum of 3 numbers.
– Now, create object and call constructor by passing 3 integer values then call sum method.

www.axessupskill.in
Agenda
▪ Overloading

▪ this keyword

▪ Static variables & static methods

www.axessupskill.in
Method Overloading
▪ Method Overloading in Java is a concept related to Object Oriented Programming (OOP). Java
supports overloading of methods and can distinguish between different methods with method
signatures. A situation, wherein, in the same class there are two or more methods with same
name, having different functions or different parameters, it is called Method Overloading.

▪ Why Method Overloading?


– Using Method Overloading in Java is very common among Java programmers, because it:
– Provides flexibility to call similar method for different data types
– Saves memory
– Saves time

▪ Method Overloading can be done in two ways:


 By changing Arguments’ data types
 By changing number of Arguments

www.axessupskill.in
Overloading
10, 20 add(int x, int y)
10, 20, 30 add(int x, int y, int z)

10.5, 20.0 add(double x, double y)

10.5, 20.0, 30.5 add(double x, double y, double z)


10, 20.5 add (int x, double y)
20.5, 10 add (double y, int x)

www.axessupskill.in
62

Can we overload java main()


method?
▪ Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only.

www.axessupskill.in
this keyword
er s wor esolv

Output: Output:
0 10
0 20

www.axessupskill.in
static
▪ The static keyword in java is used for memory management mainly.

▪ We can apply java static keyword with variables and methods

▪ The static can be:


– variable (also known as class variable)
– method (also known as class method)

static

variable method

www.axessupskill.in
static
Employee

int empno;
String ename;
int deptno;
void bonus()

emp1 emp2 emp3

int empno=101; int empno=102; int empno=103;


String ename=“John”; String ename=“David”; String ename=“Scott”;
int deptno=10; int deptno=10; int deptno=10;
void bonus() void bonus() void bonus()

• Every object occupy certain amount of space in memory.


• Objects are independent. So if modify a variable value in obj1 , that will not reflect other objects
variable values.

www.axessupskill.in
static
Employee

int empno;
String ename;
static int deptno=10; deptno=10
void bonus()

emp1 emp2 emp3

int empno=101; int empno=102; int empno=103;


String ename=“John”; String ename=“David”; String ename=“Scott”;
void bonus() void bonus() void bonus()

www.axessupskill.in
static variables and methods
static Non-static

Variables Methods Variables Methods

static methods    

Non-static methods    

Direct Access

Through Object

www.axessupskill.in
System.out.println()

class Test class System


{ {
static String s="Welcome"; static PrintStream out;
} }

Test.s.length(); System.out.println();

www.axessupskill.in
Assignment
▪ 1) Create a class Calculation with the following methods.

▪ Class Name: Calculation

 int sum(int x, int y) : Should accept two integer parameters and returns sum of two numbers.

 int sum(int x, int y, int z) : Should accept three integer parameters and returns sum of three
numbers.

 double sum(double x, double y) : Should accept two double type parameters and returns sum
of two numbers.

 double sum(double x, double y, double z) : Should accept three double type parameters and
returns sum of three numbers.

▪ Now, create object for Calculations class ‘cal’ then call different methods by passing different
inputs.

www.axessupskill.in
Agenda
▪ Java Inheritance

▪ Method Overriding

▪ super Keyword

▪ final Keyword

www.axessupskill.in
Inheritance
▪ In OOP, computer programs are designed in such a way where everything is an object that interact with one
another. Inheritance is one such concept where the properties of one class can be inherited by the other.

▪ It helps to reuse the code and establish a relationship between different classes.

▪ In Java, there are two classes:


1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )

▪ A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is
known as Parent class.

www.axessupskill.in
Types of Inheritance
▪ Inheritance is further classified into 4 types.

www.axessupskill.in
Single Inheritance
▪ In single inheritance, one class inherits the properties of another. It enables a derived class to
inherit the properties and behavior from a single parent class.

▪ This will in turn enable code reusability as well as add new features to the existing code.

▪ Here, Class A is your parent class and Class B is your child class which inherits the properties and
behavior of the parent class.

www.axessupskill.in
Multilevel Inheritance

▪ When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.

▪ If we talk about the flowchart, class B inherits the properties and behavior of class A and class
C inherits the properties of class B. Here A is the parent class for B and class B is the parent
class for
 C. So in this case class C implicitly inherits the properties and methods of class A along with
Class
 B. That’s what is multilevel inheritance.

www.axessupskill.in
Hierarchical Inheritance
▪ When a class has more than one child classes (sub classes) or in other words, more than one child
classes have the same parent class, then such kind of inheritance is known as hierarchical.

▪ If we talk about the flowchart, Class B and C are the child classes which are inheriting from the
parent class i.e Class A.

www.axessupskill.in
Hybrid Inheritance
▪ Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, so this type
of inheritance can only be achieved through the use of the interfaces.
▪ If we talk about the flowchart, class A is a parent class for class B and C, whereas Class B
and C are the parent class of D which is the only child class of B and C.

www.axessupskill.in
Method Overriding
▪ If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

▪ Rules for Java Method Overriding


– method must have same name as in the parent class
– method must have same parameter as in the parent class.

www.axessupskill.in
super keyword
▪ The super keyword in java is a reference variable which is used to refer
immediate parent class object.
▪ Usage of java super Keyword
 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

www.axessupskill.in
Super
▪Keyword
super is used to refer immediate parent class instance variable.

www.axessupskill.in
Super Keyword
▪ super can be used to invoke parent class method.

www.axessupskill.in
Super Keyword
▪ super is used to invoke parent class constructor

www.axessupskill.in
final
Keyword
▪ The final keyword in java is used to restrict the user. The java final keyword can
be used for variables, methods and classes.
– variable
– method
– class

www.axessupskill.in
Java final variable
▪ If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Output:Compile Time Error

www.axessupskill.in
Java final method
▪ If you make any method as final, you cannot override it.

Output:Compile Time Error

www.axessupskill.in
Java final class
▪ If you make any class as final, you cannot extend it.

Output:Compile Time Error

www.axessupskill.in
Assignment

▪ Assignment-1
▪ Create a class ‘Teacher’ which contains following variables and methods
– designation = "Teacher";
– collegeName = "BusyQA";
– does()  Teaching

▪ Create another class ‘ComputerTeacher’ which extends ‘Teacher’ class then create
 objects then call methods.

www.axessupskill.in
Agenda
▪ Java Interfaces

▪ Java Packages

▪ Access Modifier’s

www.axessupskill.in
Java Interface
▪ An interface in java is a blueprint of a class.
▪ Interface contains final and static variables.
▪ Interface contains abstract methods.
▪ An abstract method is a method contains definition but not body.
▪ Methods in interface are public by default.
▪ Interface supports the functionality of multiple inheritance.
▪ We can define interface with interface keyword.
▪ A class extends another class, an interface extends another interface but a class implements an
interface.
▪ We can create Object reference for Interface but we cannot instantiate interface.

class interface interface

class class interface

www.axessupskill.in
Java Interface
class interface interface
extends implements extends

class class interface


class A interface I1
interface I
{ {
{
//Variables //abstract methods
//abstract methods
//Methods //final static variables
//final static variables
} }
}
class B extends A Interface I2 extends I1
class B implements I
{ {
{
//Variables //abstract methods
//Method implementation;
//Methods //final static variables
}
} }
class B implements I2
{
//Methods implementation;
}

www.axessupskill.in
Multiple Inheritance in Java by
Interface
interface interface interface interface

interface
class

class

interface I extends I1, I2


class A implements I1, I2 {
{ //final static variables
//Implement all the methods from I1 & I2 //abstract methods
}
} class A implements I
{
//Implement all the methods from I
}

www.axessupskill.in
Hybrid inheritance in java by
interface
Class A

Interface B1 Interface B2

Class C

class C extends A implements B1, B2


{
//Implements methods from B1 & B2
}

www.axessupskill.in
Selenium WebDriver is an
interface
WebDriver

ChromeDriver InternetExplorerDriver FirefoxDriver

www.axessupskill.in
Java Packages
▪ A java package is a group of similar types of classes, interfaces and sub-packages.
▪ Package in java can be categorized in two forms.
• Built-in package
• User-defined package
▪ There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

www.axessupskill.in
Access package from another
package

▪ There are two ways to access the package from outside the package.
• import package.*;
• import package.classname;

www.axessupskill.in
Access Modifiers in java
▪ The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
▪ There are 4 types of java access modifiers:
• private
• default
• protected
• public

www.axessupskill.in
private access modifier

www.axessupskill.in
default access modifier
▪ If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.

▪ * In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

www.axessupskill.in
protected access modifier
▪ The protected access modifier is accessible within package and outside the package but through
inheritance only.

▪ The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

www.axessupskill.in
public access modifier
▪ The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

www.axessupskill.in
Access modifiers
Access Modifier within class within package outside package by outside package
subclass only

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

www.axessupskill.in
Assignment
1. Write a program to demonstrate interface.
– Interface A : int a, int b sum()
– Class B : Implements method from A and calculate sum of a and b

▪ 2. Write a program for multiple inheritance by using interface.


– Interface A : int a, int b add()
– Interface B : int x, int y mul()
– Class Calculation : Implements methods from A and B interfaces.

www.axessupskill.in
Agenda
▪ Exception Handling

www.axessupskill.in
Java Exceptions
▪ Exception is an abnormal condition.

▪ In java, exception is an event that disrupts the normal flow of the program.

▪ There are two types of exceptions.


1. Checked Exceptions
2. Un-checked Exceptions

Exception

Checked Un-Checked

www.axessupskill.in
Un Checked Exceptions
▪ Exceptions that are NOT checked by compiler are called Un-Checked Exceptions.
▪ Un checked Exceptions successfully compiled by Java compiler.
▪ At run time it throws exception.
▪ Examples:
– ArithmeticException
– NullPointerException
– NumberFormatException
– ArrayIndexOutOfBoundsException

www.axessupskill.in
Common Un-Checked exceptions
int a=50/0 ArithmeticException

String s=null; NullPointerException


System.out.println(s.length());

String s="abc";
int i=Integer.parseInt(s); NumberFormatException

int a[]=new int[5];


a[10]=50; ArrayIndexOutOfBoundsException

www.axessupskill.in
Checked Exceptions
▪ Exceptions that are checked by compiler are called Checked Exceptions.

▪ If a program contains checked-Exception code is not compiled.

▪ Examples:
– InterruptedException
– IOException
– FileNotFoundException etc.

www.axessupskill.in
Common Checked exceptions

Thread.sleep(3000); InterruptedException

FileReader fr = new FileReader("C:\\Test.txt"); FileNotException


BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine()); IOException

www.axessupskill.in
Java Exception Handling
Keywords
▪ try

▪ catch

▪ finally

▪ throws

www.axessupskill.in
Java try..catch block
▪ Java try block is used to enclose the code that might throw an exception.
▪ It must be applied at statement level within the method.
▪ Java try block must be followed by either catch or finally block.
▪ Used for both Un-checked and Checked Exceptions.
▪ Java catch block is used to handle the Exception. It must be used after the try block only.
▪ You can use multiple catch block with a single try.

www.axessupskill.in
Problem without exception
handling
▪ Output: Exception in thread main java.lang.ArithmeticException:/ by zero

www.axessupskill.in
Solution by exception handling
Output: Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

www.axessupskill.in
Java Multi catch block
▪ If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.

www.axessupskill.in
Java finally block
▪ Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
▪ Java finally block is always executed whether exception is handled or not.
▪ Java finally block follows try or catch block.

www.axessupskill.in
Usage of Java finally
▪ Cases
1. Exception doesn't occur.
2. Exception occurs and not handled.
3. Exception occurs and handled.

www.axessupskill.in
Case 1: Java finally example where exception
doesn't occur

www.axessupskill.in
Case 2: Java finally example where exception occurs and
not handled.
▪ Output:finally block is always executed

▪ Exception in thread main java.lang.ArithmeticException:/ by zero

www.axessupskill.in
Case 3: Java finally example where exception occurs and
handled.

Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always


executed rest of the code...

www.axessupskill.in
throws
▪ Used for only Checked Exceptions.
▪ It should be applied at Method level.

www.axessupskill.in
throws – Example1

www.axessupskill.in
throws – Example2

www.axessupskill.in
Un-Checked Checked Method Level Within the method
Try..Catch Y Y N Y
throws N Y Y N

www.axessupskill.in
Assingment
1. Write a java program for the following and handle exceptions by using try..catch and
finally blocks.
• Any number divide by zero.
• int a[]=null;
• a.length
• String s="abc";
• int i=Integer.parseInt(s);

2. Write a java program to handle IO Exception by using throws.

www.axessupskill.in
Agenda
▪ ArrayList

▪ HashMap

▪ JDBC

www.axessupskill.in
ArrayList
▪ ArrayList is pre defined class in Java used for dynamic array for storing elements.
▪ ArrayList can contains duplicate elements.
▪ We can add, insert and remove elements from ArrayList.

www.axessupskill.in
Java ArrayList Example1

www.axessupskill.in
Java ArrayList Example2

www.axessupskill.in
HashMap
▪ The important points about Java HashMap:
– A HashMap contains values based on the key.
– It contains only unique elements.
– It maintains no order.

www.axessupskill.in
Java HashMap Example

www.axessupskill.in
JDBC – Java Database Connectivity
▪ Java JDBC is a java API to connect and execute query with the database.

▪ JDBC API uses jdbc drivers to connect with the database.

www.axessupskill.in
Database and SQL
▪ Database: stores the data in the tables.
▪ SQL- a language used for communicate to the database.
– DML : Data Manipulation Language
– DDL : Data Definition Language
– DCL : Data Control Language
– TCL : Transaction Language

www.axessupskill.in
Database Components
▪ Database Client
– CLI
– GUI
▪ Database Server

www.axessupskill.in
4 Steps to connect to the
database in java
 Creating connection

 Creating statement

 Executing queries

 Closing connection

www.axessupskill.in
JDBC Example1

www.axessupskill.in
JDBC Example2

www.axessupskill.in

You might also like