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

OOP Lecture Notes

This document provides an overview of Java program structure and basics. It discusses that a Java program must be defined within a class with a main method. The main method is where program execution begins. It also summarizes that Java code is compiled to bytecode that can run on any machine with a Java Virtual Machine. Key concepts covered include Java classes, comments, data types, variables, expressions, and assignment statements. The document then introduces decision making and loops in Java using if/else statements and logical operators.

Uploaded by

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

OOP Lecture Notes

This document provides an overview of Java program structure and basics. It discusses that a Java program must be defined within a class with a main method. The main method is where program execution begins. It also summarizes that Java code is compiled to bytecode that can run on any machine with a Java Virtual Machine. Key concepts covered include Java classes, comments, data types, variables, expressions, and assignment statements. The document then introduces decision making and loops in Java using if/else statements and logical operators.

Uploaded by

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

Section 2 Java Program Structure

class Hello {
Java Basics public static void main ( String[] args ) {
System.out.println("Hello World!");
• Developed by James Gosling at Sun }
Microsystems. }
• Introduced in 1995.
• Is one the fastest growing programming? • The file must be named Hello.java to
Technologies of all time. match the class name containing the main
Bytecode method.• Java is case sensitive. This
• Java programs are translated into an program defines a class called “Hello”.
intermediate language called bytecode. • The line public static void main ( String[] args
• Bytecode is the same no matter which )
computer platform it is run on. shows where the program will start running. The
• Bytecode is translated into native code that the word main means that this is the main method –
computer can execute on a program called the The JVM starts running any program by
Java Virtual Machine (JVM). executing this method first.
• The Bytecode can be executed on any • The main method in Hello.java consists of
computer that has the JVM. Hence Java’s asingle statement
slogan, “Write once, run anywhere”. System.out.println("Hello World!");
• The statement outputs the characters
between quotes to the console.
A class is an object oriented construct. It is
designed to perform a specific task. A Java
class is defined by its class name, an open
curly brace, a list of methods and fields, and
close curly brace.
Comments
Line comment: A line comment is
preceded by two slashes (//) in a line.
Paragraph comment: A paragraph
comment is enclosed between /* and */
in one or multiple lines.

Introduction to JavaJDK Editions Data types, variables and Expressions


Java Standard Edition (J2SE)
• A data type is a scheme for representing
J2SE can be used to develop client-side
values. An example is int which is the integer, a
standalone applications or applets.
data type.
 Java Enterprise Edition (J2EE) The data type defines the kind of data that is
J2EE can be used to develop server-side represented by a variable. Java data types are
applications such as Java servlets and Java case sensitive.
ServerPages. • All data in Java falls into one of two
Java Micro Edition (J2ME). categories: primitive data and objects. There
J2ME can be used to develop applications for are only eight primitive data types. Any data
mobile devices such as cell phones. This Course type you create will be an object.
uses J2SE to introduce Java programming. • An object is a structured block of data. An
object may use many bytes of memory.
• The data type of an object is its class.

Java Object Oriented Programming ( OOP) [email protected]


• Many classes are already defined in the Java • Use only the characters 'a' through 'z', 'A'
Development Kit. through 'Z', '0' through '9', character '_', and
• A programmer can create new classes to meet character '$'.
the particular needs of a program. • A name cannot contain the space character.
• Do not start with a digit.
• A name can be of any reasonable length.
• Upper and lower case count as different
characters. I.e., Java is case sensitive. So SUM
and Sum are different names.
• A name cannot be a reserved word (keyword).
• A name must not already be in use in this
block of the program.

Reserved Words
Reserved words or keywords are words that
have a specific meaning to the compiler and
cannot be used for other purposes in the
program. For example, when the compiler sees
the word class, it understands that the word
after class is the name for the class. Other
reserved words are public, static, and void.
Their use will be introduced later in the book.
Abstract, assert,Boolean,break,byte
Variables ,case,catch,char,class,const,continue,d
efault,do,double,else,enum,extends,fina
Variables are labels that describe a particular location l,float,for,false,goto,if,implements,
in memory and associate it with a data type. instanceof,int,interface,long,native,new
public class example { etc many more key words( reserved
public static void main ( String[] args ) { words)
int states = 50; // a declaration of
a variable Assignment Statements
System.out.println(“The variable
states contains: ” + states); Variables are expected to vary by having new
}
values placed into them as the program runs.
}
•A declaration of a variable is where the An assignment statements one way to change
program allocates memory for the variable. the value of a variable. See the example below.
•The declaration in the example program
requested a 32 bit section of memory which will
use primitive data type int and will be named
states.
•A variable cannot be used in a program unless
it has been declared.
•A variable can be declared only once in a
particular section of code.

Names of Variables

Java Object Oriented Programming ( OOP) [email protected]


The assignment statement puts the value 50
into the variable.
Assignment Statement Syntax
variableName = expression;
• The equal sign "=" means "assignment."
• variableName is the name of a variable that
has been declared somewhere in the program.
• Expression an expression that has a value.
• An assignment statement asks for the
computer to perform two steps, in order:
1. Evaluate the expression (that is: calculate a
value.)
2. Store the value in the variable.

Expressions

An expression is a combination of literals,


operators, variables, and parentheses used to
calculate a value.

E.g. 9-x/y

• Literal: characters that denote a value, like:


3.56

• Operator: a symbol like plus ("+") or times


("*").

• Variable: a section of memory containing a


value. With the highest to lowest precedence ,
brackets parenthesis ->modulo(%) ->division -
• Parentheses: "(" and ")". > multiplication -> addition -> subtraction.

Java Object Oriented Programming ( OOP) [email protected]


Section 3.

Decision making and Loops

The if else Statements

Java Object Oriented Programming ( OOP) [email protected]


If statement Generalized form

Logical Operators.

• A logical operator combines true


and false values into a single true or
false value.

• Three types of logical operators:

Java Object Oriented Programming ( OOP) [email protected]


– AND (&&) if ( __________________________ )
System.out.println("Enough to rent
– OR (||)
this car!" );
– NOT (!)
else

System.out.println("Have you
considered a bicycle?" );

// check that both qualifications are met

Java Object Oriented Programming ( OOP) [email protected]


// check that at least one qualification is met

if ( ___________________________ )
System.out.println("Enough to buy this car!" );

else

System.out.println("Have you considered a Yugo?" );

Increment and Decrement Operators

Java Object Oriented Programming ( OOP) [email protected]


• The increment operator can be
used as part of an arithmetic
expression

int sum = 0;

int counter = 10;

sum = ++counter ;

System.out.println("sum: "+ sum " +


counter: " + counter );

• The counter will be incremented


before the value it holds is used.

• In the example, the assignment


statement will be executed in the
usual two steps:

Step 1: evaluate the expression on


the right of the "=":, the value will be
11 (because counter is incremented
before use.)

Java Object Oriented Programming ( OOP) [email protected]


Step 2: assign the value to the The Switch statement
variable on the left of the "=":
double discount;
• sum will get 11.
char code = 'B' ;
• The next statement will write out:
switch ( code ) {
sum: 11 counter: 1
case 'A': discount = 0.0; break;
• When used with a variable alone, it
doesn’t matter whether you use case 'B': discount = 0.1; break;

prefix or postfix operator. case 'C': discount = 0.2; break;

• counter ++ is the same as ++ default: discount = 0.3;


counter.
}

• A choice is made between options based


on the value in code.

• To execute this fragment, look down the


list of cases to match the value in code.

• The statement between the matching


case and the next breaks is executed. All
other cases are skipped. If there is no
match, the default case is chosen.

1. The character Expression is evaluated. –


In this example, the expression is just a
variable, code, which evaluates to the
character 'B'. 2. The case labels are
inspected starting with the first.

3. The first one that matches is case


'B':

. The corresponding statement Lists


tarts executing. – In this example,
there is just one statement. – The
statement assigns 0.1 to discount.

Java Object Oriented Programming ( OOP) [email protected]


5. The break statement is
encountered.

6. The statement after the switch For Statement


statement is executed.

Java Object Oriented Programming ( OOP) [email protected]


Answer:
*
public class Loop{ **
***
****
*****
Assignment 1.
Write a java Program that will print the
following structure

*
***
*****
*******
What is the O/P of the following program
*********
public static void ***********
main(String[] args)
{
for(int i = 0; i < 7;
i++)
{
for(int j=0; j<i;
j++)
{

System.out.print("*");
}

System.out.print("\n");
}
}

Java Object Oriented Programming ( OOP) [email protected]


Lab exercise

Program to Add up User-entered Integers

•Ask user how many integers to enter.

•Write a program that will produce a sum


of each integer the user enters.

Answer.

import java.util.Scanner;

public class addUpNumbers { public static


void main (String[] args ){

Scanner sc= new Scanner( System.in ) ;


int num; // total numbers of integers int
value; // data entered by the user
int sum = 0; // initialize the sum
System.out.println( "Enter how many
integers :" );
num =sc.nextInt();
// get the first value

Java Object Oriented Programming ( OOP) [email protected]


System.out.println( "Enter first integer :" ); The do statement is similar to the while
value = sc.nextInt(); statement with an important difference: the do
while ( num != 0 ) { statement performs a test after each execution
sum = sum + value; of the loop body. Here is a counting loop that
prints integers from 0 to 9:
System.out.println( "Enter next integer
int count = 0; // initialize count to 0
(enter 0 to quit):" );
do { System.out.println( count );
value = sc.nextInt(); // loop body: includes code to count++ ;
num = num –1; // change the count
} }while ( count < 10 ); // test if the loop body
System.out.println( "Sum of the integers: " should be executed again.
+ sum );
}
}

do Statement

Section 4 Methods

Java Object Oriented Programming ( OOP) [email protected]


Methods are time savers, in that they allow for the repetition of sections of code without
retyping the code. In addition, methods can be saved and utilized again and again in newly
developed programs.

In Java, parameters sent to methods are passed-by-value:


Definition clarification: What is passed "to" a method is referred to as an
"argument". The "type" of data that a method can receive is referred to as a
"parameter". (You may see "arguments" referred to as "actual parameters" and "parameters" referred to as
"formal parameters".)

Java Object Oriented Programming ( OOP) [email protected]


First, notice that if the arguments are
variable names, the formal
parameters need not be those same
names (but must be the same data type).

Pass-by-value means that when a


method is called, a copy of the value of
each argument is passed to the
method. This copy can be
changed inside the method, but such a
change will have NO effect on
the argument.

Style 1: Our first style of method will simply perform an independent task. It
will not receive any parameters and it will not return any values. Such a method
definition starts with the reserved words public static void, followed by the name of
the method and a set of parentheses. The word public indicates that there are no
restrictions on the use of the method. The word static means that all of the method's
data will come from parameters or internal computations, with no reference to
variables. The word void is used to indicate that no value is returned.

//Demo Program for Methods

import java.io.*;

public class DisplayClass


{
public static void main (String[ ] args)
{
System.out.println("Calling all methods!");
asterisks( ); //invoking method (calling the method)
System.out.println("Great job, method!");
asterisks( ); //invoking method again
System.out.println("We're outta here!");
}

//Method for astericks


public static void asterisks( ) // Method definition
{

Java Object Oriented Programming ( OOP) [email protected]


int count;
for(count = 1; count<=20; count++)
System.out.print("*");

System.out.println( );
}
}

Output:

Calling all methods!


********************
Great job, method!
********************
We're outta here!

Style 2: Our second style of method will take arguments (parameters) but will not
return a value. The parameter list in the parentheses specifies the types and number of
arguments that are passed to the method.

//Demo Program for Methods

import java.io.*;

public class DisplayClass


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

Java Object Oriented Programming ( OOP) [email protected]


greeting(5); // Method call with actual argument 5
int number;
do
{
number = Console.readInt("\nPlease enter value(1-10): ");
}
while ((number < 1) || (number > 10));
greeting(number); //Method call again with a variable argument
}

// Method for greeting


public static void greeting(int x) //parameter shows need for int
{
int i; // declaring LOCAL variable*
for(i = 0; i < x; i++)
{
System.out.print("Hi ");
}
System.out.println( );
}
}

Output:
Hi Hi Hi Hi Hi

Please enter value(1-10):


Hi Hi Hi Hi

* A local variable is a variable that is used only within the method. Such a variable
is NOT recognized by main. When execution returns to main, the local variable will
no longer be available for use.

Style 3: Our third style of method takes no arguments, but will return a value. Up
until now, we have been communicating information TO an invoked method. Now
we will be returning information FROM the method by using the method return
value. The return value can be a constant, a variable, or an expression. The only
requirement is that the return value be of the type specified in the method
definition.

Java Object Oriented Programming ( OOP) [email protected]


A method call (that returns a value) is replaced by the method's return value when the
method is finished ... so be sure to do something with that return value. Store the return
value somewhere; print the return value to the screen; use the return value in a
calculation; just use it!!

//Demo Program for Methods


import java.io.*;
public class method1test
{
public static void main(String[ ] args)
{
greeting(5); //first method call
int response;
response = getNumber(); //second method call
greeting (response); //first method call again
}

//First Method for greeting


public static void greeting(int x)
{
int i;
for(i = 0; i < x; i++)
{
System.out.print("Hi ");
}
System.out.println( );
}

//Second method which returns a number


public static int getNumber( )
{
int number;
do
{
number = Console.readInt("\nPlease enter value(1-10): ");
}
while ((number < 1) || (number > 10)); //error trap
return number; //return the number to main
}
}

Java Object Oriented Programming ( OOP) [email protected]


Hi Hi Hi Hi Hi

Please enter value(1-10): 5


Hi Hi Hi Hi Hi

Style : Our fourth style of method takes arguments AND returns a value.

//Demo Program for Methods


import java.io.*;

public class method1test


{
public static void main(String[ ] args)
{
int test1 = 12, test2 = 10;
// notice in this next line the method called min
System.out.println("The minimum of " + test1 + " and " + test2
+ " is " + min(test1,test2) + ".");
}
//Method to find minimum
// This method needs to receive two integers and returns one integer.
public static int min(int x, int y)
{
int minimum; // local variable
if (x < y)
minimum = x;
else
minimum = y;
return (minimum); // return value to main
}
}

Output:

The minimum of 12 and 10 is 10.

Java Object Oriented Programming ( OOP) [email protected]


Section 5- Java collection
Arrays In java.
What is an array?

An array is a collection of data storage locations, each of which holds the same type of
data. Think of an array as a "box" drawn in memory with a series of subdivisions,
calledelements, to store the data.

The box below could represent an array of 10 integers

7 6 5 8 3 9 2 6 10 2

While this array contains only 10 elements. Arrays are traditionally used to handle large amounts
of data. It is important to remember that all of the elements in an array must contain the same
type of data.

Let's declare an array of 10 integer values.

This declaration declares an array named num that contains 10 integers. When the compiler encounters this
declaration, it immediately sets aside enough memory to hold all 10 elements.

The square brackets ([ ]) after the "type" indicate that num is going to be an array of type int rather than a single

Java Object Oriented Programming ( OOP) [email protected]


instance of an int. Since the new operator creates (defines) the array, it must know the type and size of the
array. The new operator locates a block of memory large enough to contain the array and associates the array
name, num, with this memory block.

A program can access each of the array elements (the individual cells) by referring to the name of the array followed
by the subscript denoting the element (cell). For example, the third element is denoted num[2].

num [ 0 ] always OK
num [ 9 ] OK (given the above declaration)
num [ 10 ] illegal (no such cell from this declaration)
num [ -1 ] always NO! (illegal)
num [ 3.5 ] always NO! (illegal)

If the value of an index for an array element is negative, a decimal, or greater than or equal to the length of the
array (remember that the last subscript is array length - 1), an error message will
be ArrayIndexOutOfBoundsException.
If you see this message, immediately check to see how your array is being utilized.

Array Length: When dealing with arrays, it is advantageous to know the number of elements contained within the
array, or the array's "length". This length can be obtained by using the array name followed by .length. If an array
named numbers contains 10 values, the code numbers.length will be 10. ** You must remember that
the length of an array is the number of elements in the array, which is one more than the largest subscript.

value.length value.length( )
is used to find the length is a method used to find the length of
of an array named value. a String namedvalue(not an array)

Advantage of Java Array

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array

 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime.

Types of Array in java

Java Object Oriented Programming ( OOP) [email protected]


There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Two Dimensional Array

• An array with a single subscript is called a one dimensional array. The slots of the array can be thought of as
lined up one after the other in a line. Two dimensional arrays, three dimensional arrays, and higher
dimensional arrays also exist.

• The slots of an array are often called elements. In a one dimensional array, the elements are accessed using
a single index. In a two dimensional array, the elements are accessed using two indices.

int [][] arr=new int[1][3];

-1 1 20 100

90 -10 120 200

arr[0][0]=-1,arr[1][2]=120 and so on
To display two dimensional array we have to use nested for loop using the values row and column.
for(int i=0;i<col;i++){
for(int j=0;j<row;j++){
System.out.println(arr[i][j]);
}
}

Java Object Oriented Programming ( OOP) [email protected]


Section 6 Java Object Oriented
Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). The example of
intangible object is banking system.

An object has three characteristics:

 State: represents data (value) of an object.


 Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
 Identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects


are created. So object is the instance (result) of a class.

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.

Java Object Oriented Programming ( OOP) [email protected]


A class in java can contain:

 data member
 method
 constructor
 block
 class and interface

Syntax to declare a class:

class <class_name>{
data member;
method;
}

Simple Example of Object and Class


In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing the
objects value.

class Student{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student s1=new Student();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Instance variable in Java

A variable that is created inside the class but outside the method, is known as instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when object (instance) is created. That is why, it is known as instance variable.

Method in Java :In java, a method is like function i.e. used to expose behavior of an object.

Advantage of Method

 Code Reusability
 Code Optimization

new keyword :is allocate memory used to at runtime.

Java Object Oriented Programming ( OOP) [email protected]


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. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor : A constructor that have no parameter is known as default


constructor.

Syntax of default constructor:

<class_name>(){}
Example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
Class Bike1 {
Bike1 () {
System.out.println("Bike is created");

Java Object Oriented Programming ( OOP) [email protected]


}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on
the type. Example of default constructor.

class Student3{
int id;
String name;
void display(){
System.out.println(id++name);

}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}

} output: 0 null

0 null

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.

Java Object Oriented Programming ( OOP) [email protected]


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student{
int id;
String name;

Student(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+” ”+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behavior of an
object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you don't have Method is not provided by compiler in any
any constructor. case.

Constructor name must be same as the class name. Method name may or may not be same as
class name.

Java Object Oriented Programming ( OOP) [email protected]


Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods
only.The interface in java is a mechanism to achieve fully abstraction. There can be only
abstract methods in the java interface not method body.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.

The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.
1. In other words, Interface fields are public, static and final bydefault, and methods are public
and abstract.

In this example, Printable interface have only one method, its implementation is provided in the A class.

interface printable{
void print();
}

class A6 implements printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){

Java Object Oriented Programming ( OOP) [email protected]


A6 obj = new A6();
obj.print();
}
}
Output:Hello

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.Abstraction lets you focus on what the
object does instead of how it does it.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

A class that is declared as abstract is known as abstract class. It needs to be extended


and its method implemented. It cannot be instantiated.
abstract class Bike{
abstract void run();
}

class Honda4 extends Bike{


void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda4();
obj.run();
}
}
Output: running safely...

Java Object Oriented Programming ( OOP) [email protected]


Method Overloading in Java

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the
program.

Advantage of method overloading? Method


overloading increases the readability of the program.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

class Calculation{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(int a,int b,int c){
System.out.println(a+b+c);
}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
} Output: 30
40

Method Overriding
If subclass (child class) has the same method as declared in the parent class. If subclass provides the
specific implementation of the method that has been provided by one of its parent class

Method overriding is used for runtime polymorphism Rules for Java


Method Overriding

1. method must have same name as in the parent class


2. method must have same parameter as in the parent class.

e.g

class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle{
void run(){

Java Object Oriented Programming ( OOP) [email protected]


System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}

What is exception

Dictionary Meaning: Exception is an abnormal condition.In java, exception is an event that disrupts the normal flow
of the program. It is an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc. The core
advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the
normal flow of the application that is why we use exception handling. Let's take a scenario:

1. statement 1;
2. statement 2;
3. statement 4;
4. statement 5;//exception occurs
5. statement 6;
6. statement 7;
Suppose there is 5 statements in your program and there occurs an exception at statement 5, rest of the code will not
be executed i.e. statement 6 to 7 will not run. If we perform exception handling, rest of the statement will be
executed. That is why we use exception handling in java.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception.

1. Checked Exception
2. Unchecked Exception

Difference between checked and unchecked exceptions

1) Checked Exception
. Checked exceptions are checked at compile-time. e.g.IOException, SQLException etc.

Java Object Oriented Programming ( OOP) [email protected]


2) Unchecked Exception

Unchecked exceptions are not checked at compile-time rather they are checked at runtime.eg:
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc..

ArithmeticException

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

NullPointerException

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException

ArrayIndexOutOfBoundsException

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

try catch body

try{

// try body

Catch( Exeption e){

// body exception

Java Object Oriented Programming ( OOP) [email protected]


Section 7
I/O: File Reading and Writing
File I/O allows a Java program to read information from files and save information to files.

There are two general kinds of file I/O: byte I/O and character I/O.

Byte I/O is useful for reading from and writing to binary files.

Character I/O is useful for reading from and writing to text files.

The InputStream and OutputStream classes are used to read and write bytes to and from files (and other
sources/destinations for binary data).

The Reader and Writer classes are very much like InputStream and OutputStream, but they are used to read and
write characters rather than bytes.

All 4 of the basic Input/OutputStream and Reader/Writer classes come in many different "flavors". For example:

 FileInputStream is an InputStream that reads bytes from a file


 FileWriter is a Writer that writes characters to a file

Making the situation even more complicated, some kinds of Stream and Reader/Writer classes are used as "adapters"
or "wrappers" to add functionality to another Stream or Reader/Writer object. For example:

 A BufferedReader object can be used as an adapter to make any Reader object capable of reading
complete lines of text at a time.
 A Scanner object can be used as an adapter to make any InputStream or Reader object capable of
reading tokens of input

One of the keys to writing code to do file I/O in Java is knowing which classes, or combinations of classes, you need
to use.

Reading characters from a file

Here's a program to read every character of text from a FileReader, and count the number of occurrences of the
vowels A, E, I, O, and U.

package edu.ycp.cs201.countvowels;

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class CountVowels {


public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);

Java Object Oriented Programming ( OOP) [email protected]


String fileName;
System.out.println("Which file? ");
fileName = keyboard.next();

FileReader reader = new FileReader(fileName);

int vowelCount = 0;

while (true){
int c = reader.read();

if (c < 0) {
break;
}

char ch = (char) c;

ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}
reader.close();

System.out.println("The file contains " + vowelCount + "


vowel(s)");
}
}

Note that when the read method returns a negative value, it means that the reader has reached the end of the input
file, and there are no more text characters to be read.

Also note that after the program is done using a Stream or a Reader/Writer, it is important to call the closemethod on
the object.

Assume that the file myFile.txt contains the following text:

Fourscore and seven years ago...

Running the CountVowels program on that file produces the following output:

Which file?
myFile.txt
The file contains 7 vowel(s)

Java Object Oriented Programming ( OOP) [email protected]


Reading all lines of text from a file

The BufferedReader class is handy for reading a text file line-by-line.

Here is a program to find the longest line in an input text file:

package edu.ycp.cs201.countvowels;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FindLongestLine {


public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);

System.out.println("Which file?");
String fileName = keyboard.next();

FileReader fileReader = new FileReader(fileName);


BufferedReader reader = new BufferedReader(fileReader);

int longest = 0;

while (true) {

String line = reader.readLine();


if (line == null) {
break;
}

if (line.length() > longest) {


longest = line.length();
}
}

reader.close();

System.out.println("The longest line contained " + longest + "


character(s)");
}
}

Note several interesting things going on in this program.

The BufferedReader object serves as an "adapter" or "wrapper" for the FileReader. That means that
theBufferedReader object uses the FileReader object for reading characters, but adds some additional capabilities
(specifically, the ability to read complete lines of text.) Here's a picture showing how this works:

The BufferedReader object contains a reference to the underlying FileReader object in one of its (private) fields.

Java Object Oriented Programming ( OOP) [email protected]


Also note that the BufferedReader's readLine method returns the special null reference after all of the lines of text
in the file have been read.

Finally, note that calling the close method on the BufferedReader causes the underlying

Running the program on the same text file as the previous example:

Which file?
myFile.txt
The longest line contained 32 character(s)

Writing to a text file

The FileWriter class is useful for writing text to a text file.

Demo program:

package edu.ycp.cs201.countvowels;

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {


public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("pandp.txt");

writer.write("It is a truth universally acknowledged, that a


single man in\n");
writer.write("possession of a good fortune, must be in want of a
wife.\n");

writer.close();

System.out.println("File written successfully!");


}
}

Note that when calling the write to write a string of text, you must manually insert newlines (\n) whenever you want
to end a line and begin a new line.

This program writes the first sentence of Pride and Prejudice to a file called pandp.txt. Running the program
produces the following output:

File written successfully!

After you run the program, right-click on the name of the project and choose Refresh. You will see a text file
called pandp.txt appear in the project. When you open the file, you should see the two files written.

Java Object Oriented Programming ( OOP) [email protected]


THANK YOU

Java Object Oriented Programming ( OOP) [email protected]

You might also like