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

Java Oop Notes

Uploaded by

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

Java Oop Notes

Uploaded by

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

D.K.S.

Charitable Institute ®
GLOBAL INSTITUTE OF MANAGEMENT SCIENCES
(Affiliated to Bangalore University, Recognized by Govt. of Karnataka and Approved by AICTE,
New Delhi)
#6, 3rd Cross, D Road, Ideal Homes Township, Rajarajeshwari Nagar, Bangalore-560098

NOTES

Course Faculty Name: Prof. Sumathi G K

Course/Cousre Code: Object Oriented Programming (1MCA5)

Object Oriented Programming with Java Lab (1MCA8)

Programme: MCA I semester (2023-2025)

Department: Computer Applications


Global Institute of Management Sciences
Department of Computer Applications

Course: MCA semester 1


Subject: Object Oriented Programming
Principles of OOP

• Data Abstraction
• Encapsulation
• Polymorphism
• Inheritance
• Data hiding
Advantages

• Object Oriented
• Simple
• Secured
• Robust
• Platform Independent
• Multi-threaded
OOP Languages

• Java
• Python
• C++
• C#
• Ruby
• PHP
• etc…
Limitations of OOP

• Java needs to be interpreted during runtime, which allows it to run on


every operating system, but it also makes it perform slower than the
languages like C and C++.
• Java program consumes more memory since it runs on top of Java virtual
machine.
• Java programming language is a bit costly due to its higher processing and
memory requirements. We need better hardware to run the Java program.
• Java lacks when it comes to interacting directly with machines, making it
less viable for the software that needs to run quickly and run directly with
the machine, as explicit pointers are also missing in Java.
• Java provides automatic garbage collection that cannot be controlled by
the programmer. It doesn't provide the methods like delete() and free() to
free the memory.
Evolution

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.

2) Initially it was designed for small, embedded systems in electronic


appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension
was .gt.

4) After that, it was called Oak and was developed as a part of the Green
project.
Features of Java

• Simple
• Object-Oriented
• Platform independent
• Secured
• Portable
• Robust
• Multi-threaded
Java compilation and execution

Keywords
• JVM - Java Virtual Machine
• Bytecode
• Java Compiler
• Source code
• Object code
Applications

• Mobile App Development


• Desktop GUI Applications
• Web-based Applications
• Gaming Applications
• Big Data Technologies
• Distributed Applications
• Cloud-based Applications
• IoT Applications
Types of java programs

• Stand-alone
• Applets
Tokens
1. Keywords

2. Identifiers

3. Literals

4. Operators

5. Separators
1. Keywords
• Java keywords are also known as reserved words.
• Keywords are particular words that act as a key to a code.
• These are predefined words by Java so they cannot be used as a
variable or object name or class name.

Example:

public, static, void, int, double, if, for etc….


2. Identifiers
They are names given to a class, variable, package, method, or interface
and allow the programmer to refer to the specific item from any place in the
program.

Example:
public class Sample
{
public static void main(String args[])
{
int a=23, b=56;
System.out.println(a+b);
}
}
The general rules for naming variables are:

● Names can contain letters, digits, underscores, and dollar signs


● Names should not begin with a digit
● Names must begin with a letter
● Names cannot contain whitespace
● Names can also begin with $ and _
● Names are case sensitive ("myVar" and "myvar" are different variables)
● Reserved words (like Java keywords, such as int or boolean) cannot
be used as names
3. Literals
• Literals in Java are a synthetic representation of boolean,
character, numeric, or string data.
• They are a means of expressing particular values within a program.
• They are constant values that directly appear in a program and can
be assigned now to a variable.
Example:
Types:

1. Integer literal→ int/long → 25.458,3214568


2. Real literal → float/double → 3.14, 42.568, 3.24578913245
3. Character literal → char → “d‟ “1‟ “A‟ “$‟
4. String literal → String → “gims” “savesoil#2023”
5. boolean literal → boolean → true, false
4. Operators
Operators are used to perform operations on variables and values.

Types
1. Arithmetic Operators

2. Relational Operators

3. Logical Operators
4. Bitwise Operators

5. Assignment Operators
1. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Unary:
+, -, ++, --

Binary:
+, -, /, *, %

Ternary:
?:
Java Unary Operator Example: ++ and --
1. class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10
Java Unary Operator Example 2: ++ and --
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21
2. Relational Operators
• Comparison operators are used to compare two values (or variables). This
is important in programming, because it helps us to find answers and
make decisions.
• The return value of a comparison is either true or false.

Operators:
>, <, >=, <=, ==, !=
3. Logical Operators
• You can also test for true or false values with logical operators.
• Logical operators are used to determine the logic between variables or
values
• They are also used to combine more than 1 conditions

Operators:
&& - Logical and
|| - Logical or
! – Logical not
4. Bitwise Operators
These operators perform operations on bits(0’s and 1’s).

Types:

• Bitwise AND
• Bitwise OR(Inclusive OR)
• Bitwise exclusive OR
• Bitwise Compliment
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise compliment
5. Assignment Operators
Assignment operators are used to assign values to variables.

c=a+b
c += a
c -= a
c *= a
c /= a
c %= a
Precedence and Associativity of Operators
5. Separators

In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon (;). As you have seen, it is
used to terminate the statements.

Examples:
;
,
()
{}
:
[]
Variables
• A variable is a container which holds the value while the java program is
executed.
• A variable is assigned with a data type.
• Variable is a name of memory location.
• There are three types of variables in java: local, instance and static.

Examples:
int number1 = 34;
double number2 = 3.41;
char Section = ‘A’;
String college_name = “GIMS”;
boolean res = true;
Data types
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
• Non-primitive data types: The non-primitive data types include classes,
interfaces and arrays.
Types of errors
• syntax errors
• logical errors
• runtime errors

Syntax errors
• Syntax errors are mistakes in the source code, such as spelling and
punctuation errors, incorrect labels, and so on, which cause an error
message to be generated by the compiler.
• These appear in a separate error window, with the error type and line
number indicated so that it can be corrected in the edit window.
Logical errors
A logic error is classified as a type of runtime error that can result in a program
producing an incorrect output.

Runtime errors
• Runtime error refers to an error that takes place while executing a program.
• As opposed to the compilation errors that occur during a program
compilation, runtime errors occur only during the execution of the
program.
• Runtime errors imply bugs in the program or issues that the developers
had expected but were unable to correct.
• For example, insufficient memory can often trigger a runtime error.
Arithmetic expression
Arithmetic expression is formed by operands (variables, functions, constants)
with arithmetic operators among them.

Example: a+b, a+6-b, 6+2.5+7

Arithmetic statement
If an Arithmetic Expression is assigned to a variable, it is known as
Arithmetic Statement.

Example: res = a + b, sum = 6+2.5+7


Type Conversion

1. Implicit/coercion
When an arithmetic expression has values (operands) of different data
types, compiler will convert from one data type to another depending on the
following hierarchy:

Example: double res = 4; res = 4 + 5.8 + 2.6;


2. Explicit/Type casting
Forcing the compiler to convert from one data type to another.

Example:
int sum = (int) 4.66;
char s = (char) 67;
char c = (char)68.9;
Basic Structure

<access specifier> class <name of the class>


{
public static void main(String args[ ])
{
Statements;
}
}
Console I/O
1. Command line arguments
The java command-line argument is an argument i.e. passed at the time
of running the java program.

Example:
public class Sample Execution procedure:
{
public static void main(String args[]) javac Sample.java
{ java Sample <input>
System.out.println(args[0]); args[0]
}
}
2. Scanner class
Step 1: create an object for the Scanner class in main function.

Step 2: Use the following functions for inputs depending on the type of
data required for the program.
int = nextInt();
long = nextLong();
float = nextFloat();
double = nextDouble();
char = next().charAt(0);
String = next() or nextLine()
Selection Structures
• Simple-If statement
• If-Else statement
• Nested If-Else statement
• Else-if ladder
• The Switch Statement
Simple if

Syntax:
if(condition)
statements;

Example:

if(10>8)
System.out.println(“10 is greater than 8”);
if-else

Syntax:
if(condition)
Statements;
else
Statements;

Example:
if(age>=18)
System.out.println(“eligible to
vote”); else
System.out.println(“eligible to vote”);
nested if-else

Syntax:
if(condtion)
{
if(condition)
Stmts;
else
Stmts;
}
else
Stmts;
Example:

if(pgcet_rank<2000)
{
if(comp_marks>90)
System.out.prntln(“eligble to take
admission”); else
System.out.println(“not eligible”);
}
else
System.out.println(“invalid”);
else if ladder

Syntax:
if(condition)
Statements;
else if(condition)
Statements;
:
:
else
Statements;
Example:

if((units>=1) && (units <=50))


Amount = units*3;
else if((units >=51) && (units<=100))
Amount = units*5;
else
Amount = units*7;
switch

Syntax:
switch(variable)
{
case 1:
Stmts;
case 2:
Stmts;
:
:
default: stmts;
}
}
Example:

switch(input)
{
case 1: System.out.println(“one”);
break;
case 2:System.out.println(“two”);
break;
case 3:System.out.println(“three”);
break;
default:
System.out.println(“invalid input”);
}
Looping Structures
• The while loop
• The For loop
• The Do-While loop
• Nested Loops
• The break Statement
• The continue Statement
• Labeled Loops
for loop
Syntax:
for(initialization expression ; test expression ; update expression)
{
Loop body
}

Example:
for(i=1; i<11; i++)
{
System.out.println(“GIMS”);
}
while loop
Syntax:
IE;
while(test expression)
{
Loop body
}

Example:
i=1;
while( i<11)
{
System.out.println(“GIMS”);
i++;
}
do-while

Syntax:
IE;
do
{
Stmts;
}while(test expression);
Example:

i=1;
do
{
System.out.println(“GIMS”);
i++;
}while(i<11);
break statement

Example:

for(i=1 ; i<=7 ; i++)


{
if(i==4)
break;
System.out.println(i);
}
continue statement

Example:

for(i=1 ; i<=7 ; i++)


{
if(i==4)
continue;
System.out.println(i);
}
Nested loops
• It is also possible to place a loop inside another loop. This is called a
nested loop.
• The "inner loop" will be executed one time for each iteration of the
"outer loop":

Example:
for(i=1 ; i<=5; i++) outer loop
{
for(j=1 ; j<=5; j++) inner loop
{
System.out.println(j);
}
}
Example:

for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}
Labelled loops
• A label is a valid variable name that denotes the name of the loop
to where the control of execution should jump.
• To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.
Syntax:

labelname:

for(initialization; condition; incr/decr)

//functionality of the loop

}
Example:

outer:
for(int i=1;i<=5;i++)
{
inner:
for(int j=1;j<=5;j++)
{
System.out.print(j);
if(j==4)
break inner;
}
System.out.println();
}
Example:

outer:
for(int i=1;i<=5;i++)
{
inner:
for(int j=1;j<=5;j++)
{
System.out.print(j);
if(i==3)
break outer;
}
System.out.println();
}
Method Overloading
and
Method Overriding in Java
Method Overloading
• When a class has two or more methods by the
same name but different parameters, at the time
of calling based on the parameters passed
respective method is called (or respective
method body will be bonded with the calling line
dynamically). This mechanism is known as
method overloading.
or
• If a class has multiple methods having same name
but different in parameters, it is known as Method
Overloading.
• Suppose you have to perform addition of the
given numbers but there can be any number
of arguments, if you write the method such as
a( int, int) for two parameters, and b(int, int
,int) for three parameters then it may be
difficult for you as well as other programmers
to understand the behavior of the method
because its name differs.
• So, we perform method overloading to figure
out the program quickly.
Different ways to overload the
method
• By changing number of
arguments
• By changing the data type
Method Overloading: changing no. of arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static int add(int a, int b, int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11))
;
}
}
• we have created two methods, first add()
method performs addition of two numbers
and second add method performs addition of
three numbers.
Method Overloading: changing data type of arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(10,10));
System.out.println(Adder.add(11.3,11.6));
}
}
• we have created two methods that differs in
data type. The first add method receives two
integer arguments and second add method
receives two double arguments.
Why Method Overloading is not possible by
changing the return type of method only?

In java, method overloading is not possible by


changing the return type of the method only
because of ambiguity. Let's see how ambiguity
may occur:
c la ss Adder
{
static int add(int a,int b){
return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambig uity
}}
Compile Time Error: method add(int, int) is
already defined in class Adder

System.out.println(Adder.add(11,11)); //Here,
how can java determine which add()
method should be called?
Output:

a a 10
Method Overriding
Method Overriding
⚫ If a method of the subclass has the same
signature(name and parameter list) and
return type as that of the method in super
class then we say that the methods are
overrided.
⚫ The process is known as “Method
Overriding”
⚫ The ability of a subclass to override a
method allows a class to modify behavior
as needed.
Contd.,
• In other words, If subclass provides the
specific implementation of the method that
has been provided by one of its parent class, it
is known as method overriding.
Usage of Java Method
Overriding
• Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
• Method overriding is used for runtime
polymorphism
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.
• must be IS-A relationship (inheritance).
Understanding the problem without method overriding

class Vehicle{
void run(){
System.out.println("Vehicle is running");} }
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}}
Example of method overriding
class Vehicle{
void run(){System.out.println("Vehicle is running");} }
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}
}
java
• 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.
super is used to refer immediate parent class instance
variable.
• We can use super keyword to access the data
member or field of parent class. It is used if parent
class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog
class
System.out.println(super.color);//prints color
of Animal class
}}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}
super is used to invoke parent class constructor.

class Animal{ Animal()


{System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
Java
Inheritance
Inheritance
⚫ Inheritance in Java is a mechanism in which
one object acquires all the properties and
behaviors of a parent object. It is an important
part of OOPs (Object Oriented programming
system).

⚫ The class which inherits the properties of other


is known as subclass (derived class, child class)
and the class whose properties are inherited is
known as superclass (base class, parent class).
extends Keyword
⚫ extends is the keyword used to inherit the
properties of a class. Following is the syntax
of extends keyword.
Syntax:
class Super {
.....
.....
}
class Sub extends Super { .....
..... }
⚫ The idea behind inheritance in Java is that
you can create new classes that are built
upon existing classes. When you inherit from
an existing class, you can reuse methods and
fields of the parent class. Moreover, you can
add new methods and fields in your current
class also.
⚫ Inheritance represents the IS-A
relationship which is also known as a
parent-child relationship.
Example
Types of Inheritance
⚫ Single Inheritance
⚫ Multilevel Inheritance
⚫ Hierarchical Inheritance
⚫ Multiple Inheritance

Note: Java supports only single, multilevel and


hierarchical inheritance. It does not support
for multiple inheritance. The multiple
inheritance will be achieved in difference way
by using Interfaces.
Single Inheritance
⚫ In Single Inheritance one class extends form
another
class.
Multilevel Inheritance
⚫ When there is a chain of inheritance, it is
known as multilevel inheritance.
⚫ In the following example we have three
classes – Car, Maruti and Maruti800.
⚫ We have done a setup – class Maruti extends
Car and class Maruti800 extends Maruti.
With the help of this Multilevel hierarchy
setup our Maruti800 class is able to use the
methods of both the classes (Car and
Maruti).
Hierarchical Inheritance
⚫ Many classes extending from single super
class. One super class and many sub-classes.
Multiple Inheritance
⚫ When one class extends more than
one classes then this is called
multiple inheritance. For example:
Class C extends class A and B then
this type of inheritance is known
as multiple inheritance.
⚫ Java doesn’t allow multiple
inheritance.
Why multiple inheritance is not supported in java?

⚫ The problem occurs when there


exist methods with same signature in
both the super classes and subclass.
⚫ On calling the method, the compiler
cannot determine which class
method to be called and even on
calling which class method gets the
priority.
Example

Compiler error
class C extends A,B{//suppose if it were
^
1 error
INTERFACES
Interface:
⚫ An interface in Java is a blueprint of a
class. It has static constants and abstract
methods.
⚫ The interface in Java is a mechanism
to achieve abstraction. There can be only
abstract methods in the Java interface, not
method body. It is used to achieve abstraction
and multiple inheritance in Java.
⚫ In other words, you can say that interfaces
can have abstract methods and variables. It
cannot have a method body.
An interface is similar to a class in the following
ways −
⚫ An interface can contain any number of methods.
⚫ An interface is written in a file with a .java
extension, with the name of the interface
matching the name of the file.
⚫ The byte code of an interface appears in a .class
file.
⚫ Interfaces appear in packages, and their
corresponding bytecode file must be in a
directory structure that matches the package
name.
Syntax
interface MyInterface {
/* All the methods are public
abstract by default
* As you see they have no
body */ public void
method1();
public void method2();
}
The relationship between classes and interfaces
Defining Interface
interface
interface_name{ [pub
lic static variables]
[public abstract
methods]
}
Structure of interface: Example
Interface Animal{
public static final int
age=10; public abstract
void eat(); public
abstract void travel();
}
The above code can be rewritable as
shown below: Interface Animal{
int
age=10;
void eat();
void
travel();
}
Extended interfaces
⚫ We can extend an interface from another
interface just like we extend a java class
from another java class.
⚫ Note that , an interface can only be
extended from another interface.
⚫ We cannot extend an interface from a class.
⚫ A class can be extended from only one
class but an interface can be extended
from multiple interfaces.
Example 1:
Interface i1{
void
method1();
}
interface i2
extends i1{ void
method2();
}
Example 2
interface i1{
void method1();
}
interface i2{
void
method2();
}
interface i3 extends
i1,i2{ void
method3();
}
Implementing Interfaces
⚫ To implement an interface, a class must
provide bodies (implementations) for the
methods described by the interface.
⚫ Each class is free to determine the details
of its own implementation.
⚫ Two classes might implement the same
interface in different ways, but each class
still supports the same set of methods.
General Syntax:
calss classname implements interfacename{
<Body of the class>
}
The class can implement more than one
interface as shown below:
class classname implements interface1,
interface2{
<Body of the class>
}
Rules for declaring interface
⚫ While declaring a method in an interface,
there is no need to explicitly specify the
public and abstract keywords. All interface
methods are implicitly public and abstract.
⚫ An interface declares only constants and not
the instance variables.
⚫ All variables declares in an interface are
public, static, and final. No need to mention
these keywords.
⚫ All the variables are implicitly public, static and
final.
Contd.,
⚫ Interface methods must not be static or final.
⚫ An interface can extend one or more interfaces.
⚫ An interface cannot implement another
interface or class.
⚫ An interface must be declared using the
interface keyword.
PACKAGE
Introduction
⮚A java package is a group of similar types
of classes, interfaces and sub-packages.
⮚A Package serves two purposes:
⮚ First, it provides a mechanism by which
related pieces of a program can be organized
as a unit. Classes defined within a package
must be accessed through their package
name.
⮚ Second, a package participates in java’s access
control mechanism. Classes defined within a
package can be made private to that package
and not accessible by code outside the
package.
The Java packages are classified
into two categories.
PACKAGES
PACKAGE
S
Java
JavaAPI
API Packages User Defined Packages
Packages

• The Java API packages contain the built-in classes provided by


the Java.
• The user defined packages are the packages which the
programmer develops.
Java API Package
⮚ The java provides thousands of
built-in classes and remembering
each class name is very difficult.
⮚ The java organized the collection
of classes into packages based
on the functionality.
⮚ We can easily remember the
package name instead of class
name.
Java

lan

uti even
t
l

aw

sql
Using Java API Packages
⮚ If the class we want to use is in the
package java.lang (for example, System
or String), we can simply use the class
name to refer to that class.
⮚ The java.lang classes are automatically
available to all java programs. No need
to import java.lang classes.
⮚ If the class we want to use is in some
other package other than java.lang
package, then we need to import that
class into our program using import
statement.
Import java.util.Vector;
Vector v=new Vector();
⮚ It imports the class Vector from util package
and hence we can create an object of Vector
class
⮚ Vector is like the dynamic array which can grow
or shrink its size. Unlike array, we can store n-
number of elements in it as there is no size
limit.
⮚ If we do not want to import the class, then we
can also create an object of Vector class as
shown below: Java.util.Vector V=new java.util.Vector();
⮚ Suppose if we are using more number of
util classes in our program, then
instead of importing each class, we
can import all the classes in the util
package using below statement.
import java.util.*;
Vector v=new
Vector();
ArrayList a=new ArrayList();
HashSet s=new HashSet();
Here, we have used ArrayList, Vector and HashSet classes.
All these classes are belongs to util package. Instead of
importing each class, we can import whole package.
Defining User Defined
Packages
⮚ Default package is not good for
real applications. Most of the
time we will define one or more
packages for our code.
⮚ To create user defined package,
put a package command at the top
of the java source file.
⮚ The classes declared within that
file will then belong to the specified
package.
⮚ package pkg;
Here, pkg is the name of the
package. For example, the following
statemetn creates package called
Project1
⮚ package pack1;
Java uses thr file system to
manage packages, with each
package stored in its own
directory.
⮚ We can create a hierarchy of
packages. To do so, simply
separate each package nae with
period.
⮚ The general form of a
multileveled package statement is
shown below: Package
pack1,pack2,pack3……packN;
Creating User Defined
Packages
⮚ Step 1: Let us create a program
which is part of package called
pack1.
package pack1;
public class
packageExample{ public
void packMethod(){
System.out.println(“I’m
packMethod() in
pack1.packageExample”);
}
}
⮚ Step 2: Place this file
packageExample.java n C:\ and compile
the program as shown below. We have
to use –d option to create a the pack1
directory automatically.
⮚ The command is
javac –d . packageExample.java (there is
dot after d)
⮚ We can see that pack1 directory
is automatically created by
compiler. The
packageExample.class will also
present in the same directory as
shown below.
⮚ Step 3: Create another file called
packageDemo.java in pack2 package
as shown below
package pack2;
package pack2;
import pack1.*;
public class packageDemo{
public static void main(String args[]){
packageExample obj=new packageExample();
}
}
⮚ In this file, we are trying to import the pack1
classes and creating an object of
packageExample class and call packMethod().
⮚ Step 4: Place this file also in C:\ and compile
the program using –d option as shown below.
It is very clear that pack2 directory is created and class
file is also copied to that directory automatically
⮚ Step 5: The compilation of both
the classes are completed. Now,
let us execute the packageDemo
class.
java pack2.packageDemo
I’m packMethod() in
pack1.packageExample
Write a program to implement package.

//Vehicle.java
package
vehicles;
interface
Vehicle
{
public void run();
public void
speed();
}
//Car.java
package
vehicles;
public class Car implements Vehicle
{
public void run()
{
System.out.println("Car is running.");
}
public void speed()
{
System.out.println("Speed of Car: 50 Km/h");
}
public static void main(String args[])
{
Car Car = new Car();
Car.run();
Car.speed();
}
}
⮚ Output
Exception handling
in Java
⚫ The Exception Handling in
Java is one of the powerful
mechanism to handle the
runtime errors so that normal
flow of the application can be
maintained.
⚫ Advantage of Exception Handling
⚫ The core advantage of exception handling
is to maintain the normal flow of the
application. An exception normally
disrupts the normal flow of the application
that is why we use exception handling. Let's
take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception
occurs statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10
statements in your
program and there occurs an
exception at statement 5,
the rest of the code will not be
executed i.e. statement 6 to 10 will
not be executed.
If we perform exception handling, the
rest of the statement will be
executed.
That is why we use exception
handling in Java.
✔The Throwable class is the superclass of all errors and
exceptions in the Java language.
✔RuntimeException is the superclass of those exceptions that can
be
thrown during the normal operation of the Java Virtual Machine.
✔An Error is a subclass of Throwable that indicates serious
problems that a reasonable application should not try to
catch.
✔IOException: This exception happens when there is a failure
during
reading, writing and searching file or directory operations.
✔NullPointerException is a RuntimeException. In Java, a
special
null
value can be assigned to an object reference.
⚫ Types of Java Exceptions
⚫ There are mainly two types of exceptions:
checked and unchecked. Here, an error is
considered as the unchecked exception.
According to Oracle, there are three types of
exceptions:
⚫ Checked Exception
⚫ Unchecked Exception
⚫ Error
⚫ Difference between Checked and
Unchecked Exceptions: 1) Checked
Exception: The classes which directly
inherit Throwable class except
RuntimeException and Error are known as
checked exceptions e.g. IOException,
SQLException etc. Checked exceptions are
checked at compile-time.
⚫ 2) Unchecked Exception: The classes
which inherit RuntimeException are
known as unchecked
exceptions e.g.
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at
compile-time, but they are checked at
runtime.
⚫ 3)Error: Error is
irrecoverable e.g.OutOfMemoryError,
VirtualMachineError etc.
Java Exception Keywords
Java Exception Handling Example
public class
JavaExceptionExample{ public
static void main(String args[]){
try{
//code that may raise
exception int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the
code...");
}
}
Output: Exception in thread main
java.lang.ArithmeticException:/ by zero
rest of the code...
Java catch multiple exceptions
⚫ A try block can be followed by one or
more catch blocks. Each catch block must
contain a different exception handler. So,
if you have to perform different tasks at
the occurrence of different exceptions, use
java multi-catch block.
⚫ Points to remember
⚫ At a time only one exception occurs and
at a time only one catch block is
executed.
⚫ All catch blocks must be ordered from
most specific to most general, i.e. catch
for ArithmeticException must come
before catch for Exception.
public class MultipleCatchBlock1
{ public static void main(String[]
args) {
try{ int a[]=new
int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds
Exception occurs"); }
catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
} }
Output: Arithmetic Exception
occurs rest of the code
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.
⚫ Finally block in java can be used to
put "cleanup" code such as closing a
file, closing connection etc.
Let's see the java finally example where exception
occurs and not handled.
class TestFinallyBlock1{
public static void main(String
args[]){ try{
int data=25/0;
System.out.println(dat
a);
} catch(NullPointerException e)
{System.out.println(e);} finally{
System.out.println("finally block is always
executed");} System.out.println("rest of the
code..."); }}
Output:finally block is always executed
Exception in thread main
java.lang.ArithmeticException:/
by zero
Declaring our own Exception
⚫ If you are creating your own
Exception that is known as custom
exception or user- defined exception.
⚫ Java custom exceptions are used to
customize the exception according to
user need.
⚫ By the help of custom exception,
you can have your own exception and
message.
class InvalidAgeException extends Exception{
InvalidAgeException(Stri
ng s){ super(s);
} }
class TestCustomException1{
static void validate(int
age)throws
InvalidAgeException
{ if(age<18)
throw new InvalidAgeException("not
valid"); else
System.out.println("welcome to
vote");
}
public static void main(String
args[]){ try{
validate(13);
}catch(Exception m)
{
System.out.println("Exception occured:
"+m);} System.out.println("rest of the
code..."); } }
Output:Exception occured:
InvalidAgeException:not valid rest of the
code...
Custom Exception Example 2
Write a JAVA program to
implement the concept of
exception handling by creating
user defined exceptions.
import java.util.Scanner;
class AgeDoesnotMatchException extends Throwable{
AgeDoesnotMatchException(String
msg){ super(msg);
}
}
public class
CustomException{ priva
te String name;
private int age;
public CustomException(String name,
int age){ try {
if (age<17||age>24) {
String msg = "Age is not between 17 and 24";
AgeDoesnotMatchException ex = new
AgeDoesnotMatchException(msg); throw ex;
}
}catch(AgeDoesnotMatchExcepti
on e) { e.printStackTrace();
}
this.name =
name; this.age
= age;
}
public void display(){
System.out.println("Name of the Student:
"+this.name ); System.out.println("Age of the
Student: "+this.age );
}
public static void main(String
args[]) { Scanner sc= new
Scanner(System.in);
System.out.println("Enter the name of the
Student: "); String name = sc.next();
System.out.println("Enter the age of the Student, should be
17 to 24 (including 17 and 24): ");
int age = sc.nextInt();
CustomException obj = new CustomException(name, age);
obj.display();
}
}
Output
Nested Try Block
⚫ The try block within a try block is known
as nested try block in java.
⚫ Use of nested try block
⚫ Sometimes a situation may arise where a part
of a block may cause one error and the entire
block itself may cause another error. In such
cases, exception handlers have to be nested.
Syntax
...
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Example for Nested try
class NestedtryExp{
public static void main(String
args[]){ try{
try{
System.out.println("going to
divide"); int b =39/0;
}catch(ArithmeticExce
ption e)
{System.out.println(e);
}
try{
int a[]=new
int[5]; a[5]=10;
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}

System.out.println("other statement");
}catch(Exception e)
{System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Output
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.
Finally block in java can be used to
put "cleanup" code such as closing a
file, closing connection etc.
Case 1:Java finally example where exception doesn't
occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(e);}
finally{System.out.println("finally block is always
executed");} System.out.println("rest of the
code...");
}
}
Output:5 finally block is always executed rest
of the code...
Case2: Java finally example
where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(d
ata);
}
catch(NullPointerException e)
{System.out.println(e);}
finally{System.out.println("finally block is always
executed");} System.out.println("rest of the
code...");
}
}
Output:
finally block is always executed
Exception in thread main
java.lang.ArithmeticException:/
by zero
Case 3: Java finally example
where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(d
ata);
}
catch(ArithmeticException e)
{System.out.println(e);}
finally{System.out.println("finally block is always
executed");} System.out.println("rest of the
code...");
}
}
Output:

Exception in thread main


java.lang.ArithmeticException:/ by zero
finally block is always executed rest of the
code...
Multi Threaded
Programming
What is Multi Threading?
⮚ Multithreading in java is a process of executing multiple
threads
simultaneously.
⮚ A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
⮚ However, we use multithreading than multiprocessing
because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and
context-switching between the threads takes less time than
process.
Advantages of Java Multithreading
⮚1) It doesn't block the user because
threads are independent and you can perform
multiple operations at the same time.
⮚2) You can perform many operations
together, so it saves time.
⮚3) Threads are independent, so it doesn't
affect other threads if an exception occurs in
a single thread.
What is Process?
✔ A process is a program executing within its won address space.
A process consists of the memory space allocated by the
operating system that can contain one or more threads.

✔ A thread cannot exist on its own. It must be a part of


a process. What is Thread?
A thread is part of a program that is running. A thread is a
single sequential flow of control within a process. A thread is
also referred to as lightweight process.
▪ Why threads a re called as light weight
process?
▪ Threads are light weight because they utilize
minimum resources of the system. This means
they take less memory and less processor
time.
✔ Multitasking
✔ Multitasking is a process of executing multiple
tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved
in two ways:
✔ Process-based Multitasking (Multiprocessing)
✔ Thread-based Multitasking (Multithreading)
⮚ 1) Process-based Multitasking (Multiprocessing)
⮚ Each process has an address in memory. In other
words, each process allocates a separate memory
area.
⮚ A process is heavyweight.
⮚ Cost of communication between the process is high.
⮚ Switching from one process to another requires some time
for
saving and loading registers, memory maps, updating lists,
etc.
⮚ 2) Thread-based Multitasking (Multithreading)
⮚ Threads share the same address space.
⮚ A thread is lightweight.
⮚ Cost of communication between the thread is low.
⮚ Threads are independent. If there occurs exception in one
thread, it
doesn't affect other threads. It uses a shared memory area.
Thread Life
States in threads
New − A new thread begins its life cycle in the new state. It remains in this state until the program
starts
the thread. It is also referred to as a born thread.

Runnable − After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.

Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
significant time ● The starting thread's initialization
periods: ● The moment that thread begins to
execute
main()
● The moment that thread begins to
execute
start()
● The moment start() creates a new
thread and returns to main()
● The new thread's initialization
● The moment the new thread begins
to execute run()
● The different moments each
thread
terminates
Functions for Threads
Functions for running threads
Managing threads
Thread control
Thread control
● How to create thread
● There are two ways to create a thread:
● By extending Thread class
● By implementing Runnable interface.
● Thread class:
● Thread class provide constructors and methods
to create and perform operations on a thread.
Thread class extends Object class and
implements Runnable interface. Commonly
used Constructors of Thread class:
● Thread()
● Thread(String name)
● Thread(Runnable r)
● Thread(Runnable r,String name)
Commonly used methods of Thread class:
▪ public void run(): is used to perform action for a thread.
▪ public void start(): starts the execution of the
thread.JVM calls the run() method on the thread.
▪ public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily
cease execution) for the specified number of
milliseconds.
▪ public void join(): waits for a thread to die.
▪ public void join(long miliseconds): waits for a
thread to die for the specified miliseconds.
⮚ public int getPriority(): returns the priority of the
thread.
⮚ public int setPriority(int priority): changes
the priority of the thread.
⮚ public String getName(): returns the name of the
thread.
⮚ public void setName(String name): changes
the name of the thread.
⮚ public Thread currentThread(): returns the
reference of
currently executing thread.
⮚ public int getId(): returns the id of the thread.
⮚ public Thread.State getState(): returns the state of the
thread.
⮚ public boolean isAlive(): tests if the thread is alive.
⮚ public void yield(): causes the currently executing
thread object to temporarily pause and allow other threads
to execute.
⮚ public void suspend(): is used to suspend the
thread(depricated).
⮚ public void resume(): is used to resume the suspended
thread(depricated).
⮚ public void stop(): is used to stop the thread(depricated).
Runnable interface:
⮚ The Runnable interface should be implemented by any class
whose instances are intended to be executed by a thread.
Runnable interface have only one method named
run().public void run(): is used to perform action for a
thread.
⮚ Starting a thread:
⮚ start() method of Thread class is used to start a newly
created thread. It performs following tasks:A new thread
starts(with new callstack).
⮚ The thread moves from New state to the Runnable state.
⮚ When the thread gets a chance to execute, its target run()
method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is
running...");
}
public static void main(String
args[]){ Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2)Java Thread Example by implementing Runnable interface
class Multi3 implements
Runnable{ public void run(){
System.out.println("thread is
running...");
}
public static void main(String
args[]){ Multi3 m1=new
Multi3();
Thread t1 =new
Thread(m1); t1.start();
}
}
Output:thread is running...
Thread -Implements runnable

To implement Runnable interface, a class need only implement a single method called run( ),
which is declared like this: Inside run( ), we will define the code that constitutes the new thread

Example:
Thread run()

To execute the run() method by a thread, pass an instance of MyClass to a Thread in its constructor(A
constructor in Java is a block of code similar to a method that’s called when an instance of an object is created). Here is
how that is done:

When the thread is started it will call the run() method of the MyClass instance instead of executing its own
run() method. The above example would print out the text “MyClass running“.
Extending Java Thread
create a new class that extends Thread, then override the run() method and then to
create an instance of that class. The run() method is what is executed by the
thread after you call start(). Here is an example of creating a Java Thread
subclass:To create and start the above thread you can do like this:

When the run() method executes it will print out the text “MyClass running“.
Creating Multiple Threads

public void run() {


for(int i = 5; i > 0; i--) {
try {

System.out.println(name + ": " + i);


Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
New t h read: Thread[One,5,main]
New thread:
Creating Multiple Threads Thread[Two,5,main]
New thread:
class MultiThread { Thread[Three,5,main]
public static void One: 5
main(String args[]) { Two: 5
new MyThread("One"); Three: 5
new MyThread("Two"); One: 4
Two: 4
new
Three: 4
NewThread("Three"); One: 3
try { Three: 3
Thread.sleep(10000); Two: 3
} catch One: 2
(InterruptedException e) { Three: 2
Two: 2
System.out.println("Main One: 1
thread Interrupted"); Three: 1
Two: 1
}
One exiting.
Two exiting.
System.out.println("Main
Three exiting.
thread exiting."); Main thread exiting.
}
}
Multi thread
GuruThread1.java
package demotest;
public class GuruThread1 implements Runnable{
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are
following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}

}
Dead lock
Thread Synchronization

When we start two or more threads within a program, there may be a situation when multiple threads try to access
the same resource and finally they can produce unforeseen result due to concurrency issues.

synchronized(objectidentifier) {

// Access shared variables and other shared resources The synchronization is mainly used to

} 1. To prevent thread interference.


2. To prevent consistency problem.

There are two types of thread synchronization mutual


exclusive and inter-thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
class PrintDemo {
class ThreadDemo extends Thread { public void start () {
public void printCount() {
private Thread t; System.out.println("Starting
try { " + threadName );
private String threadName;
for(int i = 5; i > 0; i--) if (t == null) {
{ PrintDemo PD;
t = new Thread (this,
PrintDemo
ThreadDemo( String name, threadName);
System --- pd) { t.start ();
.out.println("Counter
" + i );
threadName = name;
}
}
PD = pd;
}
} catch (Exception e) {
}
}
System.out.println("Thread
public void run() {
interrupted.");
public class TestThread {
synchronized(PD) {
}
public static void main(String
PD.printCount(); args[]) {
}
} PrintDemo PD = new
}
PrintDemo();
System.out.println("Thread "
+ threadName + " exiting."); ThreadDemo T1 = new
ThreadDemo( "Thread - 1 ", PD );
}
ThreadDemo T2 = new
ThreadDemo( "Thread - 2 ", PD );
T1.start();
Starting Thread -
T2.start() ;
1 Starting Thread

- 2

Counter --- 5
// wait for threads to end
Counter --- 4
try {
Counter --- 3
T1.join();
Counter --- 2
T2.join();
Counter --- 1
} catch ( Exception e) {
Thread Thread - 1 exiting.

System.out.println("Interrupted"); Counter --- 5

} Counter --- 4

} Counter --- 3

} Counter --- 2

Counter --- 1

Thread Thread - 2 exiting.


public class TestThread { System.out.println("Thread 2:
public static Object Lock1 = new System.out.println("Thread Waiting for lock 1...");
Object(); 1: synchronized (Lock1) {
public static Object Lock2 = Waiting for lock 2..."); System.out.println("Thread 2:
new Object(); synchronized (Lock2) { Holding lock 1 & 2...");
public static void main(String System.out.println("Threa }
args[]) { ThreadDemo1 T1 = d 1: }
new Holding lock 1 & 2..."); }
ThreadDemo1();
} }
ThreadDemo2 T2 = new
} }
ThreadDemo2()
; T1.start(); }
T2.start(); }
} private static class
ThreadDemo2 extends Thread
private static class ThreadDemo1 {
extends public void run() {
Thread { synchronized Output
public void run() { (Lock2) { Thread 1: Holding lock 1...
synchronized (Lock1) { System.out.println("Thread
System.out.println("Thread 2: Thread 2: Holding lock 2...
1: Holding lock 2..."); Thread 1: Waiting for lock 2...
Holding lock 1..."); try
{ Thread.sleep(10); } Thread 2: Waiting for lock 1…
try { Thread.sleep(10); } catch (InterruptedException
catch (InterruptedException e) {} Dead Lock Example
e) {}
public class TestThread { catch (InterruptedException e) {} synchronized (Lock2) {
public static Object Lock1 = new System.out.println("Thread System.out.println("Thread 2:
Object(); 1: Holding lock 1 & 2...");
public static Object Lock2 = Waiting for lock 2..."); }
new Object(); synchronized (Lock2) { }
public static void main(String System.out.println("Thread
1: }
args[]) { ThreadDemo1 T1 =
new Holding lock 1 & 2..."); }
ThreadDemo1(); } }
ThreadDemo2 T2 = new }
ThreadDemo2() }
; T1.start(); }
T2.start(); private static class Output
} ThreadDemo2 extends Thread Thread 1: Holding lock 1...
private static class {
ThreadDemo1 public void run() { Thread 1: Waiting for lock 2...
extends synchronized
(Lock1) { Thread 1: Holding lock 1 & 2...
Thread {
public void run() { System.out.println("Thread
2: Thread 2: Holding lock 1...
synchronized (Lock1) {
System.out.println("Thread Holding lock
Thread 2: Waiting for lock 2...
1..."); try {
1:
Holding lock Thread.sleep(10); Thread 2: Holding lock 1 & 2…
1..."); try { } catch
(InterruptedException e) {}
Thread.sleep(10);
System.out.println("Thread 2: Synchronized to avoid
} Waiting for lock 2..."); dead lock
Managing
Input/output Files
in Java
Introduction
A File is a collection of related
records placed in a particular
area on the disk.
A record is composed of several
fields and a filed is a group of
characters.
Streams in java
⚫ A stream can be defined as
a sequence of data. The
InputStream is used to read
data from a source and the
OutputStream is used for
writing data to a destination.
Concept of Streams
⚫ A stream is a flow of information from a
source to a destination.
⚫ For example: A keyboard (source) and a
Monitor (destination)
⚫ A page of text on a monitor (Source) and a
file on a hard drive (destination)
⚫ A file on a hard drive (source) and a
monitor (destination)
⚫ A keyboard (source) and a string (destination)
⚫ A text file (source) and a printer (destination)
STREAM CLASSES
⚫ The Java Input/Output (I/O) is a part of
java.io
package.
⚫ The java.io package contains a relatively
large number of classes that support input
and output operations.
⚫ These classes are categorized into two
groups based on the data type on which they
operate:
1. Byte stream classes that provide support for
handling I/O operations on bytes.
2. Character stream classes that provide
support for managing I/O operations on
characters.
Classification of I/O Stream

Pipes are used to channel the output from one thread into the input of another.
Byte Stream Classes
⚫ Byte stream classes have been designed to
provide functional features for creating and
manipulating streams and files for reading
and writing bytes.
⚫ Since the streams are unidirectional, they
can transmit bytes in only one direction.
⚫ Therefore java provides two types of byte
stream classes
1. Input stream classes and
2. Output stream classes
Input Stream
⚫ The InputStream class is used for reading
the data such as a byte and array of bytes
from an input source. An input source can be
a file, a string, or memory that may contain
the data.
⚫ It is an abstract class that defines the
programming interface for all input streams
that are inherited from it.
⚫ An input stream is automatically opened
when you create it. You can explicitly close a
stream with the close( ) method, or let it be
closed implicitly when the object is found as a
garbage.
The subclasses inherited from the InputStream
class can be seen in a hierarchy manner
Input Stream
- ByteArrayInputStream- it can be used to read byte array as
input stream.
- FileInputStream- obtains input bytes from a file in a file system
- ObjectInputStream- readObject() method
read an object from the
ObjectInputStream.
- FilterInputStream- class Methods It is used to return an
estimate number of bytes that can be read from the input
stream
- PipedInputStream- Pipes in IO provides a link between two
threads
running in JVM at the same time.
- StringBufferInputStream-class helps in
creating an Input Stream where,
one can read bytes from the string.
FilterInputStream
o BufferedInputStream- adds functionality to another
input stream-namely, the ability to buffer the input
and to support the mark and reset methods.
o DataInputStream- class allows an application to
read primitive data from the input stream in a
machine-independent way.
o LineNumberInputStream- class is simply an
extension of input stream providing a extra facility to
keep the record of current line number
o PushbackInputStream- It is used to read the next
byte of data from the input stream
Output Stream
⚫ The OutputStream class is a sibling to
InputStream that is used for writing byte and
array of bytes to an output source.
⚫ Similar to input sources, an output source
can be anything such as a file, a string, or
memory containing the data. Like an input
stream, an output stream is automatically
opened when you create it.
⚫ You can explicitly close an output stream
with the close( ) method, or let it be closed
implicitly when the object is garbage
collected.
The classes inherited from the OutputStream
class can be seen in a hierarchy structure
- ByteArrayOutputStream- used to write
common data into multiple files
- FileOutputStream- for writing data to a File
- ObjectOutputStream- writes primitive data
types to an OutputStream.
- FilterInputStream- obtains input bytes from
a file in a file system.
- PipedOutputStream- classes can be
used to read and write data simultaneously.
-
-StringBufferInputStream- allows an
application to
create an input stream in which the bytes
read are supplied by the contents of a
string.
- FilterOutputStream
o BufferedOutputStream- It creates
the new buffered output stream which
is used for writing the data to the
specified output stream.
o DataOutputStream- It is used to write
the specified byte to the underlying
output stream.
o PrintStream-The PrintStream enables
you to write formatted data to an
underlying OutputStream.
Character Streams
⚫ It supports 16-bit Unicode character
input and output. There
⚫ are two classes of character stream as
follows:
⚫ o Reader
⚫ o Writer
⚫ These classes allow internationalization
of Java I/O and also allow text to be
stored using international character
encoding.
Write a program to create a text file and write some
texts in it.
import java.io.*;
import java.util.Scanner; public class FileExp
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the file name: "); String name=sc.nextLine();
FileOutputStream fos=new FileOutputStream(name, true);
System.out.print("Enter file content: ");
String str=sc.nextLine()+"\n"; byte[] b= str.getBytes(); fos.write(b);
fos.close();
System.out.println("file saved.");
}
catch(Exception e)
{
e.printStackTrace();} } }
Output
Reading/Writing Characters
⚫ We have to use FileReader and FileWriter
classes.
⚫ By using the FileWriter class we can write
data into a file.
⚫ To the constructor of FileWriter class we
should pass name of the file and boolean
value true as arguments.
⚫ This make the file to be opened in the write
mode and keeps the file pointer at the end of
file location so that existing data will not be
over-written with the new data that we write
into the file.
Contd.,
⚫ When we convert a string into character
format, we get an array of characters.
Therefore, we call toCharArray() method on
the string class object.
⚫ This returns an array of characters and these
are stored in the character array ch.
⚫ Character array is passed as an argument to
the write() metod.
Write a program to write data into a file named File2.txt using
FileWriter class.
Java FileReader Class
⚫ Java FileReader class is used to read data
from the file.
⚫ It returns data in byte format like
FileInputStream class.
⚫ It is character-oriented class which is used
for file It is character-oriented class which is
used for file handling in java
Write a program to read from a file named
File2.txt using FileReader class
Java DataInputStream Class
⚫ Java DataInputStream class allows
an application to read primitive data
from the input stream in a machine-
independent way.
⚫ Java application generally uses the
data output stream to write data
that can later be read by a data
input stream.

Java DataInputStream class Methods
Java DataOutputStream Class

⚫ Java DataOutputStream classJava


DataOutputStream class allows an
application to write primitive Java
data types to the output stream in a
machine- independent way.
⚫ Java application generally uses the
data output stream to write data
that can later be read by a data
input stream.
Write a program to read and write primitive data using
DataInputStream and DataOutputStream classes
Output
Concatenating Files
⚫ It is possible to concatenate two or more files
into a single file.
⚫ This is achieved using SequenceInputStream
class.
⚫ A SequenceInputStream represents the
logical concatenation of other input streams.
⚫ It starts out with an ordered collection of
input streams and reads from the first one
until end of file is reached, whereupoin it
reads from the second one, and so on, until
end of file is reached on the last of the
contained input streams.
To demonstrate concatenation of files
Buffering Files
⚫ File buffering is a mechanism where the data
is read/written into a buffer memory area
rather than directly on to disk.
⚫ This hugely improves the I/O performance
when reading or writing files large files since
the application doesn't have to wait for the
disk read or write to finish.
⚫ File buffering is implemented in Java using
four streams –
⚫ BufferedInputStream,
BufferedOutputStream, BufferedReader
and BufferedWriter.
⚫ The difference between these buffered streams
are:
⚫ BufferedInputStream and
BufferedOutputStream are byte streams while
BufferedReader and BufferedWriter are
character streams.
⚫ Byte streams read and write data of 8-bit size
each at a time.
⚫ Characters streams are used specifically for
character data as it converts the data to local
character set.
Ouput
Interactive Input and Output
⚫ The process of reading data from
the keyboard and displaying output
on the screen is known as interactive
input and output.
⚫ We can use DataInputStream or
InputStreamReader classes to read
the data from keyboard.
To read the data from the keyboard and
display the result to console
Output
APPLET
Introduction
✔Applet is a small application that is embedded in
a HTML page, which is accessed and transported
over the Internet, automatically installed into the
client machines and run as part of a web page.
✔Applets are great for creating dynamic and
interactive web applications.
✔Applets can be used to provide dynamic user-
interfaces and a variety of graphical effects for
web pages.
How Applets differ from
Applications
Applet Life Cycle
⚫ init(): The init() method is the first method to
execute when the applet is executed. Variable
declaration and initialization operations are
performed in this method.
⚫ start(): The start() method contains the actual
code of the applet that should run. The start()
method executes immediately after the init()
method. It also executes whenever the applet
is restored, maximized or moving from one tab
to another tab in the browser.
⚫ stop(): The stop() method stops the execution
of the applet. The stop() method executes
when the applet is minimized or when moving
from one tab to another in the browser.
⚫ destroy(): The destroy() method executes
when the applet window is closed or when the
tab containing the webpage is closed. stop()
method executes just before when destroy()
method is invoked. The destroy() method
removes the applet object from memory.

⚫ paint(): The paint() method is used to
redraw the output on the applet display area.
The paint() method executes after the
execution of start() method and whenever the
applet or browser is resized.
⚫ The method execution sequence
when an applet is executed is:
◦init()
◦start()
◦paint()
⚫ The method execution sequence
when an applet is closed is:
◦stop()
◦destroy()
Example
⚫ Output
Applet initialized
Applet execution
started Painting…
Applet execution stopped
Applet destroyed
A "Hello, World" Applet
Following is a simple applet named
HelloWorldApplet.java − import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}
These import statements bring the classes into the scope of our applet class
− java.applet.Applet
java.awt.Graphics
Without those import statements, the Java compiler would not recognize the
classes Applet and Graphics, which the applet class refers to.
Invoking an Applet

⚫ The <applet> tag is the basis for embedding an


applet in an HTML file.
Following is an example that invokes the "Hello,
World"
applet −
<html>
<body>
<applet code="HelloWorld.class" width=200
height=60>
</applet>
</body>
</html>
Commonly used methods of
Graphics class
⚫ public abstract void drawString(String str, int x,
int y): is used to draw the specified string.
⚫ public void drawRect(int x, int y, int width, int
height): draws a rectangle with the specified width and
height.
⚫ public abstract void fillRect(int x, int y, int width,
int height): is used to fill rectangle with the default
color and specified width and height.
⚫ public abstract void drawOval(int x, int y, int
width, int
height): is used to draw oval with the specified width and
height.
⚫ public abstract void fillOval(int x, int y, int width,
int height): is used to fill oval with the default color
and specified width and height.
⚫ public abstract void drawLine(int x1, int y1, int x2,
int y2): is used to draw line between the points(x1, y1)
and (x2, y2).
⚫ public abstract boolean drawImage(Image img, int x,
int y, ImageObserver observer): is used draw the
specified image.
⚫ public abstract void drawArc(int x, int y, int width,
int height, int startAngle, int arcAngle): is used
draw a circular or elliptical arc.
⚫ public abstract void fillArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used to fill
a circular or elliptical arc.
⚫ public abstract void setColor(Color c): is used to
set the graphics current color to the specified color.
⚫ public abstract void setFont(Font font): is used to
set the
graphics current font to the specified font.
Graphic Example
<html>
<body>
<applet code="GraphicsDemo.class" width=200 height=60>
</applet>
</body>
</html>
Using Control Loops in
Applets

We can use all iterative


statements like for, while, do-
while inside an applet. This is
used for drawing shapes in an
applet repeatedly.
import java.awt.*;
import
java.applet.*;
/*<applet code="ControlLoops.class" width=500
height=500></applet>*/ public class ControlLoops extends
Applet
{
public void paint(Graphics g)
{
for(int i=1;i<=4;i++)
{
if(i%2==0)
{
g.fillOval(90,i*50+10,50,50);
g.setColor(Color.black);
}
else
{
g.drawOval(90,i*50+10,50,50);
g.setColor(Color.red);
} }}}
Program to draw a different shapes in
Applet window

import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;
/* <applet code="GraphicsExcercise.class" width="320" height="320">

</applet> */ public class GraphicsExcercise extends Applet {


public void paint(Graphics g) {
// For rounded rectangle and filled
oval
g.drawRoundRect(20,20,140,100,10
,10); g.fillOval(65,43,50,50);

// For triangle
g.drawLine(200,20,200,12
0);
g.drawLine(200,20,300,12
0);
g.drawLine(300,120,200,1
20);
// For smiley
g.drawOval(20,150,150,150); // For
head g.fillOval(50,190,15,15); //
Left Eye g.fillOval(120,190,15,15);
// Right Eye int x[] =
{95,85,106,95};
int y[] = {215,234,234,215};
g.drawPolygon(x, y, 4); // Nose
g.drawArc(55,225,78,50,0,-180); //
Smile
g.drawLine(50,256,60,246);
g.drawLine(128,245,139,256);

// For diamond
int x1[ ] =
{203,252,301,252,203}; int y1[
] = {225,176,225,274,225};
g.fillPolygon(x1, y1, 4);
}
}
OUTPUT

C:\>javac GraphicsExcercise.java
C:\>appletviewer
GraphicsExcercise.java
Passing Parameters to
Applets
⚫ Parameters can be passed to applets
using the param tag and retrieving the
values of parameters using
getParameter method.
⚫ Parameters specify extra information
that can be passed to an applet from the
HTML page. Parameters are specified
using the HTML’s param tag.
Param Tag

⚫ The <param> tag is a sub tag of the <applet>


tag.
⚫ The <param> tag contains two attributes:
name and value which are used to specify the
name of the parameter and the value of the
parameter respectively.
For example, the param tags for passing name
and age parameters looks as shown below:

⚫ <param name=”name”
value=”Ramesh” />
<param name=”age” value=”25″ />
⚫ Now, these two parameters can be accessed in
the applet program using the getParameter()
method of the Applet class.

⚫ getParameter() Method

⚫ The getParameter() method of the Applet class can


be used to retrieve the parameters passed
from the HTML page.
⚫ The syntax of getParameter()
method is as follows:
String getParameter(String param-
name)
Example
import
java.awt.*;
import
java.applet.*;
public class MyApplet extends Applet
{
String
n;
String
a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet.class"
height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Output
D.K.S. Charitable Institute ®
GLOBAL INSTITUTE OF MANAGEMENT SCIENCES
(Affiliated to Bangalore University, Recognized by Govt. of Karnataka and Approved by
AICTE, New Delhi)
#6, 3rd Cross, D Road, Ideal Homes Township, Rajarajeshwari Nagar, Bangalore-560098

DEPARTMENT OF COMPUTER APPLICATIONS

1MCA8: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB

For
st
1 Sem
MCA

During
2023-
25

Submitted by: Sumathi G K, Associate Professor


GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 2

List of

Programs

PART-A
1. Develop a JAVA program to demonstrate the precedence and associativity among
arithmetic operators. The program should also demonstrate how the default
precedence can be overridden.

2. Write a JAVA program to validate a date. The program should accept day, month
and year and it should report whether they form a valid date or not.

3. Write a JAVA program to display the following pattern.


1
22
333
4444
55555
4. Write a JAVA program to print the first n members of Fibonacci series.

5. Write a program to generate the multiplication tables of a range of numbers between


m and n inclusive and m < n.

6. Write a JAVA program to define a class, define instance methods for setting
and retrieving values of instance variables and instantiate its object.

7. Write a JAVA program to demonstrate static member data and static member methods.

8. Write a JAVA Program to demonstrate nested classes.

9. Write a JAVA program to demonstrate dynamic method dispatch.

10. Write a JAVA program to implement inheritance and demonstrate use of


method overriding.

PART-B
11. Write a JAVA program to implement the concept of importing classes from user
defined package and creating packages.

12. Write a program to demonstrate abstract class and abstract methods.

13. Write a JAVA Program to implement an array of objects of a class.

14. Write a JAVA program to demonstrate String class and its methods.

15. Write a JAVA program to implement the concept of exception handling by creating
user defined exceptions.

16. Write a JAVA program using synchronized threads, which demonstrates


producer consumer concept.
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 3

17. Write a JAVA program that creates three threads. First thread displays “Good Morning”
every one second, second thread displays “Hello” every two seconds and the third thread
displays “Welcome” every three seconds.

18. Write a JAVA program which uses FileInputStream / FileOutPutStream Classes.

19. Write a JAVA program to list all the files in a directory including the files present in
all its subdirectories.

20. Write a JAVA program to demonstrate the life cycle of applet.


GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 4

Program 1: Develop a JAVA program to demonstrate the precedence and associativity


among arithmetic operators. The program should also demonstrate how the default
precedence can be overridden.

Program Code:

import java.util.Scanner; //Scanner is a class in java.util package used to get the


input class Operator_prec_assoc
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of X:
")
; double x = sc.nextDouble();
System.out.println("Enter the value of Y:
")
; double y = sc.nextDouble();
System.out.println("Enter the value of Z:
")
; double z = sc.nextDouble();

double r1 = x + y / z; //precedence of division higher than


addition double r2 = (x + y) / z; // overriding default precedence using
brackets double r3 = x / y * 2 + z; //Associativity- division first then
multiplication double r4 = x / (y * 2) + z; // overriding default associativity
using brackets

System.out.println("Result using operator precedence : " + r1);


System.out.println("Result using overriding operator precedence: " + r2);
System.out.println("Result using operator associativity : " + r3);
System.out.println("Result using overriding operator associativity: " + r4);
}
}

Output:
Enter the value of X: 40
Enter the value of Y: 20
Enter the value of Z: 10

Result using operator precedence : 42


Result using overriding operator precedence: 6

Result using operator associativity : 14


Result using overriding operator associativity: 11
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 5

Program 2: Write a JAVA program to validate a date. The program should accept day,
month and year and it should report whether they form a valid date or not.

Program Code:

import java.util.Scanner; //Scanner is a class in java.util package used to get the


input class validate
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in); //invoke constructor of Scanner class with
arg int day, month, year;
System.out.println("Enter Day: ");
day = sc.nextInt(); //The nextInt() method returns the int value scanned from the
input System.out.println("Enter Month");
month = sc.nextInt();
System.out.println("Enter Year");
year = sc.nextInt();
System.out.print(+day);
System.out.print("/");
System.out.print(+month);
System.out.print("/");
System.out.print(+year);

boolean isTrueDate = true;


if(month > 12)
{
isTrueDate = false;
}
else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
month == 10 || month == 12)
{
if (day <= 31)
{
isTrueDate = true;
}
else if (day >= 31)
{
isTrueDate = false;
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
if (day <= 30)
{
isTrueDate = true;
}
else if (day >= 30)
{
isTrueDate = false;
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 6

}
else if (month == 2) // February check
{
if (year % 4 == 0) // Leap year check for February
{
if (day <= 29)
{
isTrueDate = true;
}
else if (day >= 29)
{
isTrueDate = false;
}
}
else if (year % 4 != 0)
{
if (day <= 28)
{
isTrueDate = true;
}
else if (day >= 28)
{
isTrueDate = false;
}
}
}
if(isTrueDate)
{
System.out.println("Valid Date");
}
if(!isTrueDate)
{
System.out.println("Invalid Date");
}
}
}

Output:
Enter Day: 23
Enter Month: 06
Enter Year: 1999
23/06/1999 valid date

Enter Day: 31
Enter Month: 06
Enter Year: 1999
23/06/1999 Invalid date
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 7

Program 3: Write a JAVA program to display the following pattern.


1
22
333
4444
55555

Program Code:

import java.util.Scanner;
public class pattern
{
public static void main(String[] arg)
{
int row;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of rows for pattern display: ");
row = sc.nextInt();

for (int i = 1; i <= row; i++)


{
for(int j=1; j<=row-i;j++)
{
System.out.print(" ");
}
for(int k=1;k <i;k++)
{
System.out.print(i+" ");
}
System.out.println( );
}
}
}

Output: Enter no. of rows for pattern display: 5


1
22
333
4444
55555
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 8

Program 4: Write a JAVA program to print the first n members of Fibonacci series.

Program Code:

import java.util.Scanner;
class fibo
{
public static void main(String args[])
{
int n1=0,n2=1,n3,count;
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of terms for Fibonacci series : ");
count=sc.nextInt();
System.out.println(n1+" "+n2);
for(int i=2;i<count;++i)
{
n3=n1+n2;
n1=n2;
n2=n3;
System.out.print(" "+n3);
}
}
}

Output: enter the number of terms for Fibonacci series : 8


0
1
1
2
3
5
8
13
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 9

Program 5: Write a program to generate the multiplication tables of a range of numbers


between m and n inclusive and m < n.

Program Code:

import java.util.Scanner;
public class Mult
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.println("enter the m and n range for multiplication table: ");
int m=sc.nextInt();
int n=sc.nextInt();
if(m<=n)
{
for(i=m;i<=n;i++)
{
for(j=1;j<=10;j++)
{
System.out.println(i+"x"+j+"="+i*j);
}
System.out.println();
}
}
}
}

Output: Enter the m and n range for multiplication table: 4


6 4x1=4
4x2=8
4x3=12
4x4=16
4x5=20
4x6=24
4x7=28
4x8=32
4x9=36
4x10=40

5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 10

5x9=45
5x10=50

6x1=6
6x2=12
6x3=18
6x4=24
6x5=30
6x6=36
6x7=42
6x8=48
6x9=54
6x10=60
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 11

Program 6: Write a JAVA program to define a class, define instance methods for setting
and retrieving values of instance variables and instantiate its object.

Program Code:

import java.lang.*;
class student
{
String name;
int id;
String address;
void getdata(String name,int id,String address)
{
this.name=name;
this.id=id;
this.address=address;
}
void putdata()
{
System.out.println("Student details are :");
System.out.println("Name :" +name);
System.out.println("ID :" +id);
System.out.println("Address :" +address);
}
}
class StudentDemo
{
public static void main(String arg[])
{
student s1=new student();
s1.getdata("Raju",123,"Bangalore");
s1.putdata();
}
}

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 12

Program 7: Write a JAVA program to demonstrate static member data and static member
methods.

Program Code:

import java.util.*;

class Item
{
private String itemName;
private int quantity;
private static int cnt = 0; //variable to count

public void getItem()


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter item name: ");
itemName = sc.next();
System.out.print("Enter item quantity: ");
quantity = sc.nextInt();
cnt++;
}

public void showItem()


{
System.out.println("Item Name: " + itemName + "\tQuantity: " + quantity);
}
public static int getCounter()
{
return cnt;
}
}

public class StaticVar {


public static void main(String[] s)
{
try
{
Item I1 = new
Item(); Item I2 =
new Item(); Item I3
= new Item();

I1.getItem();
I2.getItem();
I3.getItem();

I1.showItem()
;
I2.showItem()
;
I3.showItem()
;

System.out.println("Total object created (total items are): " + Item.getCounter());


GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 13

} catch (Exception e) {
System.out.println(e.toString());
}
}
}

Output:

Enter item name: Dove


Enter item quantity: 5
Enter item name: Rin
Enter item quantity: 10
Enter item name: Fenna
Enter item quantity: 20
Item Name: Dove Quantity: 5
Item Name: Rin Quantity:
10 Item Name: Fenna Quantity:
20
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 14

Program 8: Write a JAVA Program to demonstrate nested classes.

Program Code:

class Car
{
String carName;
String carType;

public Car(String name, String type) // assign values using constructor


{
this.carName = name;
this.carType = type;
}
private String getCarName() // private method
{
return this.carName;
}
class Engine // inner class
{
String engineType;
void setEngine()
{
if(Car.this.carType.equals("4WD")) //Access the carType property of Car
{
if(Car.this.getCarName().equals("Crysler")) //Invoke method of Car
{
this.engineType = "Smaller";
}
els
e
{ this.engineType = "Bigger";

}
els
e
{ this.engineType = "Bigger";
}
}
String getEngineType()
{
return this.engineType;
}
}
}
public class NestedClassDemo1
{
public static void main(String[] args)
{
Car car1 = new Car("Mazda", "8WD"); // create object of the outer class Car
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 15

Car.Engine engine= car1.new Engine(); //create obj of inner class from outer class
engine.setEngine();
System.out.println("Engine Type for 8WD= " + engine.getEngineType());
Car car2 = new Car("Crysler", "4WD");
Car.Engine c2engine = car2.new Engine();
c2engine.setEngine();
System.out.println("Engine Type for 4WD = " + c2engine.getEngineType());
}
}

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 16

Program 9: Write a JAVA program to demonstrate dynamic method dispatch.

Program Code:
class Person
{
public void display()
{
System.out.println("Person can think and move");
}
}

class Girl extends Person


{
public void display()
{
System.out.println("Girls can also think and move");
}
}

public class New123


{

public static void main(String args[])


{
Person a = new Person(); // Person reference and object
Person b = new Girl(); // Person reference but Girl
object

a.move(); // runs the method in Person class


b.move(); // runs the method in Girl class
}
}

Output
:

Person can think and move


Girl can also think and move
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 17

Program 10: Write a JAVA program to implement inheritance and demonstrate use of
method overriding.

Program Code:

class Student
{
public void data() // method in the superclass
{
System.out.println("My name is XYZ");
}
}

class Marks extends Student // Marks inherits Student


{
@Override // overriding the data()
method public void data()
{
System.out.println("I got good theory marks");
}
public void more_data() // new method in subclass
{
System.out.println("I also got good IA marks");
}
}

class Main
{
public static void main(String[] args)
{
Marks MCA = new Marks(); // create an object of the
subclass MCA.data(); // call the data() method
MCA.more_data();
}
}

Output:

I got good theory marks


I also got good IA
marks
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 18

PART-B

Program 11: Write a JAVA program to implement the concept of importing classes from
user defined package and creating packages.

Program Code:

FileName : Car_specific.java // command line argument program

package Car;
public class car_specific
{
public void run()
{
System.out.println("Car is running");
}
public void speed()
{
System.out.println("Speed of car is 50km/hr");
}
}
FileName: Car_main.java

package Car1;
import Car.*;
class car_main
{
public static void main(String args[])
{
car_specific obj=new car_specific();
obj.run();
obj.speed();
}
}

To Compile
javac –d . Car_specific.java
javac –d . Car_main.java

To Execute
java Car1.car_main

Output:
Car is running
Speed of car is 50km/hr
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 19

Program 12: Write a program to demonstrate abstract class and abstract methods.

Program Code:

abstract class Bike


{
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely..");
}
}
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 20

Program 13: Write a JAVA Program to implement an array of objects of a class.

Program Code:

import java.util.Scanner; //Scanner is a class in java.util package used to get the input

public class ArrayOfObjects


{
public static void main(String args[])
{
Product[] obj = new Product[5] ; //create an array of product
object int pid;
String pname;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of products: ");
int n = sc.nextInt();
for (int i=0;i<n;i++)
{
System.out.println("Enter product ID:
"); pid = sc.nextInt();
sc.nextLine();
System.out.println("Enter product Name: ");
pname = sc.nextLine();
obj[i] = new Product(pid,pname); //initialize obj using constructor
}
System.out.println("Product Details:");
for (int i=0;i<n;i++)
{
obj[i].display(); //display the product object data
}
}
}

class Product //Product class with product Id and product name as attributes
{
int p_Id;
String p_name;
Product(int pid, String pname) //Product class constructor
{
p_Id = pid;
p_name = pname;
}
public void display()
{
System.out.print("Product Id= "+p_Id + " " + " Product Name= "+p_name);
System.out.println();
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 21

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 22

Program 14: Write a JAVA program to demonstrate String class and its methods.

Program Code:

import java.util.*;
class StringOp
{
public static void main(String args[])
{
String first=" ",second=" ";
Scanner sc=new Scanner(System.in);
System.out.println("String operation");
System.out.print("enter the first string : ");
first=sc.nextLine();
System.out.print("enter the second string : ");
second =sc.nextLine();
System.out.println("the strings are:"+first+","+second);
System.out.println("the length of the first string is:"+first.length());
System.out.println("the length of the second string is:"+second.length());
System.out.println("the first character of "+first+"is :"+first.charAt(0));
System.out.println("the uppercase of "+first+"is:"+first.toUpperCase());
System.out.println("the lowercase of "+first+"is:"+first.toLowerCase());
System.out.print("enter the occurance of a character in "+first +”: “);
String str=sc.next();
char c=str.charAt(0);
System.out.println("the "+c+"occurs at position "+first.indexOf(c)+"is:"+first);
System.out.println("the substring of "+first+" starting from index 3 ending at 6
is:"+first.substring(3,7));
System.out.println("replacing 'a' with 'o' in "+first+"is :"+first.replace('a','o'));
boolean check=first.equals(second);
if(!check)
System.out.println("Both Strings are not same");
else
System.out.println("Both Strings are same");
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 23

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 24

Program 15: Write a JAVA program to implement the concept of exception handling by
creating user defined exceptions.

Program Code:

import java.util.Scanner;
class AgeDoesnotMatchException extends Throwable{
AgeDoesnotMatchException(String msg){
super(msg);
}
}
public class CustomException{
private String name;
private int age;
public CustomException(String name, int age){
try {
if (age<17||age>24) {
String msg = "Age is not between 17 and 24";
AgeDoesnotMatchException ex = new
AgeDoesnotMatchException(msg); throw ex;
}
}catch(AgeDoesnotMatchException e) {
e.printStackTrace();
}
this.name = name;
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name of the Student: ");
String name = sc.next();
System.out.println("Enter the age of the Student, should be 17 to 24 (including 17 and 24): ");
int age = sc.nextInt();
CustomException obj = new CustomException(name, age);
obj.display();
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 25

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 26

Program 16: Write a JAVA program using synchronized threads, which demonstrates
producer consumer concept.

Program Code:

public class ProducerConsumer


{
public static void main(String[] args)
{
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Shop
{
private int materials;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
tr
y
{ wait();

}
catch (InterruptedException ie)
{
}
}
available = false;
notifyAll();
return materials;
}
public synchronized void put(int value)
{
while (available == true)
{
tr
y
{ wait();

}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
materials = value;
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 27

available = true;
notifyAll();
}
}
class Consumer extends Thread
{
private Shop Shop;
private int num;
public Consumer(Shop c, int num)
{
Shop = c;
this.num = num;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = Shop.get();
System.out.println("Consumed value "+ this.num+ " got: "+ value);
}
}
}
class Producer extends Thread
{
private Shop Shop;
private int num;

public Producer(Shop c, int num)


{
Shop = c;
this.num = num;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
Shop.put(i);
System.out.println("Produced value " + this.num+ " put: " + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 28

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 29

Program 17: Write a JAVA program that creates three threads. First thread displays
“Good Morning” every one second, second thread displays “Hello” every two seconds and
the third thread displays “Welcome” every three seconds.

Program Code:

import java.lang.*;
import java.util.*;
import java.awt.*;
class One implements Runnable
{
One()
{
new Thread(this,"one").start();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{}
}
public void run()
{
for(int i=10;i>0;i--)
{
tr
y
{ Thread.sleep(1000);

}
catch(InterruptedException e)
{}
System.out.println("good morning");
}
}
}

class Two implements Runnable


{
Two()
{
new Thread(this,"two").start();
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{}
}
public void run()
{
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 30

for(int i=10;i>0;i--)
{
tr
y
{ Thread.sleep(1000);

}
catch(InterruptedException e)
{}
System.out.println("hello");
}
}
}

class Three implements Runnable


{
Three()
{
new Thread(this,"three").start();
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{}
}
public void run()
{
for(int i=10;i>0;i--)
{
tr
y
{ Thread.sleep(3000);

}
catch(InterruptedException e)
{}
System.out.println("welcome");
}
}
}

class MyThread1
{
public static void main(String args[])
{
One o1=new One();
Two o2=new Two();
Three o3=new Three();
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 31

Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 32

Program 18: Write a JAVA program which uses FileInputStream / FileOutPutStream


Classes.

Program Code:

import java.io.*;
public class CombineFile2 {
private static final int BUFFER_SIZE = 4096;

public static void main(String[] args) {


if (args.length < 3) {
System.out.println("Please provide file1, file2,output files");
System.exit(0);
}

String inputFile1 = args[0];


String inputFile2 = args[1];
String outputFile = args[2];

try (
InputStream inputStream1 = new FileInputStream(inputFile1);
InputStream inputStream2 = new FileInputStream(inputFile2);
OutputStream outputStream = new FileOutputStream(outputFile);
){

byte[] buffer = new byte[BUFFER_SIZE];


int bytesRead = -1;

while ((bytesRead = inputStream1.read(buffer)) != -1) {


outputStream.write(buffer, 0, bytesRead);
}

while ((bytesRead = inputStream2.read(buffer)) != -1) {


outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 33

Output
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 34

Program 19: Write a JAVA program to list all the files in a directory including the files
present in all its subdirectories.

Program Code:

// Recursive Java program to print all files in a folder (and sub-folders)

import java.io.File;
public class FileDir2
{
static void RecursivePrint(File[] arr, int level)
{
// for-each loop for main directory files
for (File f : arr)
{

for (int i = 0; i < level; i++) // tabs for internal


levels System.out.print("\t");

if(f.isFile())
System.out.println(f.getName());
else if(f.isDirectory())
{
System.out.println("[" + f.getName() + "]");
RecursivePrint(f.listFiles(), level + 1); // recursion for sub-directories
}
}
}
public static void main(String[] args)
{
String maindirpath = " C:\\Java\\jdk1.7.0_07\\bin"; // Provide full path
for directory
File maindir = new File(maindirpath); // File object

if(maindir.exists() && maindir.isDirectory())


{
File arr[] = maindir.listFiles(); // array for dir, sub-dir, files pointed by
maindir
System.out.println("**********************************************")
; System.out.println("Files from main directory : " + maindir);
System.out.println("**********************************************")
; RecursivePrint(arr, 0); // Calling recursive method
}
}
}
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 35

Output
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 36

Program 20: Write a JAVA program to demonstrate the life cycle of applet.

Program Code:

import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code="AppletLifeCycleExample" width=100 height=100>
</applet>
*/

public class AppletLifeCycleExample extends Applet


{
public void init() // init is called only once and used to initialize variables
{
super.init();
}

public void start() // start method is called every time to start applet after stop
{
super.start();
}

public void stop() // stop method is called when the the user navigates away
// from html page containing the applet.
{
super.stop();
}

public void paint(Graphics g) //paint method is called when applet redraws its o/p
{
super.paint(g);
}

public void destroy() //destroy method is called when browser removes applet
//from memory. It also free resources initialized by init()
{
super.destroy();
}
}

To Execute
appletviewer <filename>
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 37

Output:

You might also like