Java Oop Notes
Java Oop Notes
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
• 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
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.
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
• 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:
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:
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.
Arithmetic statement
If an Arithmetic Expression is assigned to a variable, it is known as
Arithmetic Statement.
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:
int sum = (int) 4.66;
char s = (char) 67;
char c = (char)68.9;
Basic Structure
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:
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:
Example:
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:
}
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?
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
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");}
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
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:
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
}
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. 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.
} Counter --- 4
} Counter --- 3
} Counter --- 2
Counter --- 1
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
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;
/* <applet code="GraphicsExcercise.class" width="320" height="320">
// 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
⚫ <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
For
st
1 Sem
MCA
During
2023-
25
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.
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.
PART-B
11. Write a JAVA program to implement the concept of importing classes from user
defined package and creating packages.
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.
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.
19. Write a JAVA program to list all the files in a directory including the files present in
all its subdirectories.
Program Code:
Output:
Enter the value of X: 40
Enter the value of Y: 20
Enter the value of Z: 10
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:
}
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 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();
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);
}
}
}
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();
}
}
}
}
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
I1.getItem();
I2.getItem();
I3.getItem();
I1.showItem()
;
I2.showItem()
;
I3.showItem()
;
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Output:
Program Code:
class Car
{
String carName;
String carType;
}
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 Code:
class Person
{
public void display()
{
System.out.println("Person can think and move");
}
}
Output
:
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 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:
PART-B
Program 11: Write a JAVA program to implement the concept of importing classes from
user defined package and creating packages.
Program Code:
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:
Output:
GIMS 1MCA8 OBJECT ORIENTED PROGRAMMING WITH JAVA LAB 20
Program Code:
import java.util.Scanner; //Scanner is a class in java.util package used to get the input
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:
}
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;
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");
}
}
}
for(int i=10;i>0;i--)
{
tr
y
{ Thread.sleep(1000);
}
catch(InterruptedException e)
{}
System.out.println("hello");
}
}
}
}
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 Code:
import java.io.*;
public class CombineFile2 {
private static final int BUFFER_SIZE = 4096;
try (
InputStream inputStream1 = new FileInputStream(inputFile1);
InputStream inputStream2 = new FileInputStream(inputFile2);
OutputStream outputStream = new FileOutputStream(outputFile);
){
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:
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)
{
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
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 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: