OOP Lecture Notes
OOP Lecture Notes
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.
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
Expressions
E.g. 9-x/y
Logical Operators.
System.out.println("Have you
considered a bicycle?" );
if ( ___________________________ )
System.out.println("Enough to buy this car!" );
else
int sum = 0;
sum = ++counter ;
*
***
*****
*******
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");
}
}
Answer.
import java.util.Scanner;
do Statement
Section 4 Methods
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.
import java.io.*;
System.out.println( );
}
}
Output:
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.
import java.io.*;
Output:
Hi 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.
Style : Our fourth style of method takes arguments AND returns a value.
Output:
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.
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.
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
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)
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.
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime.
• 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.
-1 1 20 100
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]);
}
}
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.
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.
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.
data member
method
constructor
block
class and interface
class <class_name>{
data member;
method;
}
class Student{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
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
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.
<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");
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
There are many differences between constructors and methods. They are given below.
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.
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.
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();
}
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.
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.
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);
}
}
} 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
e.g
class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle{
void 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
1) Checked Exception
. Checked exceptions are checked at compile-time. e.g.IOException, SQLException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.eg:
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc..
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:
1. try
2. catch
3. finally
4. throw
5. throws
try{
// try body
// body exception
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:
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.
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;
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();
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.
Running the CountVowels program on that file produces the following output:
Which file?
myFile.txt
The file contains 7 vowel(s)
package edu.ycp.cs201.countvowels;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
System.out.println("Which file?");
String fileName = keyboard.next();
int longest = 0;
while (true) {
reader.close();
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.
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)
Demo program:
package edu.ycp.cs201.countvowels;
import java.io.FileWriter;
import java.io.IOException;
writer.close();
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:
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.