0% found this document useful (0 votes)
130 views39 pages

Practical Record Book: T.N. Chehul Chinnappa

The document contains a practical record book of a student named T.N. CHEHUL CHINNAPPA for the course OBJECT ORIENTED PROGRAMMING WITH JAVA. It includes details of the student like name, USN, program, semester etc. It also contains a laboratory certificate and a laboratory performance evaluation sheet with details of experiments/programs conducted by the student in the lab along with marks obtained and faculty signatures.

Uploaded by

Ahmad Raza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views39 pages

Practical Record Book: T.N. Chehul Chinnappa

The document contains a practical record book of a student named T.N. CHEHUL CHINNAPPA for the course OBJECT ORIENTED PROGRAMMING WITH JAVA. It includes details of the student like name, USN, program, semester etc. It also contains a laboratory certificate and a laboratory performance evaluation sheet with details of experiments/programs conducted by the student in the lab along with marks obtained and faculty signatures.

Uploaded by

Ahmad Raza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

PRACTICAL RECORD BOOK

Name T.N. CHEHUL CHINNAPPA

USN 1NH19CS751 Year 2020 - 2021

Program B.E. in CSE Semester 4 Section E

Course OBJECT ORIENTED PROGRAMMING WITH JAVA Course Code 19CSL46


LAB
Laboratory Certificate
This is to certify that
MR. T.N. CHEHUL CHINNAPPA
has satisfactorily completed the experiments prescribed by
New Horizon College of Engineering, Bangalore Affiliated to
Visvesvaraya Technological University
in …OOPS WITH JAVA LAB... Laboratory Course for
the……4th…semester of
Computer Science and Engineering Program.
Academic Year: 2020 to 2021 (EVEN Semester)

Marks Obtained Student Name: T.N. CHEHUL CHINNAPPA


USN: 1NH19CS751
Sem/Sec: 4 - E
Course Code: 19CSL46
Max. Marks

Signature of Student

Signature of the Faculty In-charge Head of the Department


LABORATORY PERFORMANCE EVALUATION SHEET

Name of Student: T.N. CHEHUL CHINNAPPA


USN: 1NH19CS751
Lab Course: OOPS WITH JAVA LAB
Course Code: 19CSL46
Sem/Sec: 4 - E
Session: EVEN Sem 2020-21

CIE - PART A - Record and Performance (Max Marks: 10)

SN Date of Name of Experiment/ Program 1 2 3 4 Total Faculty


Evaluation Signature
01 28/4/21 Java Program to demonstrate method
overloading, math class and arrays

02 05/5/21 Write a Java Program to define a


class, describe its constructor,
overload the Constructors and
instantiate its object, and use static
members.

03 12/5/21 Write a Java program to demonstrate


String class, String Buffer class
and its methods

04 12/5/21 Write a Java program to demonstrate


nested classes and array of
objects

05 19/5/21 Write a Java Program to implement


inheritance and demonstrate use of
method overriding

06 26/5/21 Write a Java Program to implement


multilevel inheritance by applying
various access controls to its data
members and methods
07 02/6/21 Write a program to demonstrate use of
implementing interfaces
Write a program to demonstrate use of
08 02/6/21 extending interfaces

Write a Java program to implement the


09(A) 09/6/21
concept of importing classes from user
defined package and creating packages.

09(B) 09/6/21 Write a Java Program to demonstrate


dynamic binding

10 16/6/21 Write a program to implement the


concept of threading by extending
Thread Class

11 16/6/21 Write a program to implement the


concept of threading by implementing
Runnable Interface

12 16/6/21 Write a java program that implements a


multi-thread application that has three
threads. First thread generates random
integer every 1 second and if the value is
even, second thread computes the
square of the number and prints. If the
value is odd, the third thread will print
the value of cube of the number.

13 23/6/21 Write a program to implement the


concept of Exception Handling
using predefined exception

14 23/6/21 Write a program to implement the


concept of Exception Handling by
creating user defined exceptions

15 10/7/21 Write a program to demonstrate File


I/O Operations
Write a program to demonstrate
16 24/7/21
ArrayList Class, LinkedList Class,
TreeSet Class.

AVG Marks (out of 10 marks)

1. Conduction of Experiment/ Writing the Program: 3 Marks


2. Specimen Calculation / Results: 2 Marks
3. Record Writing: 3 Marks
4. Viva Voce: 2 Marks
CIE- PART B - Lab Test (Max Marks: 50)

Date of Lab Procedure Conduction Viva Voce Total Faculty


Test and Write and Results (10 Marks) (50 Marks) Signature
Up (25 Marks)
(15 Marks)
Test 1 07.07.2021

Test 2 31.07.2021
AVG Marks (out of 15 marks)

CIE - Marks Obtained


CIE-Part A CIE-Part B Total Faculty Signature
Record and Lab Test (25 Marks)
Performance (Scaled to 15 Marks)
(10 Marks)
PROGRAM NO.: 1
Course Code: 19CSL46
PROGRAM NO.: 1.
Java Program to demonstrate method overloading, math class and arrays
AIM: To demonstrate method overloading, math class and arrays

THEORY: Over loading allows different methods to have same name and different signature where
signature can differ by number or type of input parameters.
Mathclass class provides several methods to work on math calculations like min(),max(),avg(),sin()etc.
In java array is an object of a dynamically generated class. Java array inherits object class, and implements
the serializable as well as cloneable interface.

CODE:
PROGRAM 1(A)
public class MethodOverloading_arg_datatype {

private static void display(int a){


System.out.println("Arguments: " + a);
System.out.println("Got Integer data.");

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

// this method accepts String object


private static void display(String a){
System.out.println("Got String object."+a);
}

public static void main(String[] args) {


display(1);
display(1, 4);

display("Hello");
}
}

OUTPUT:

Page No: 1
Course Code: 19CSL46

PROGRAM(1B)
public class Mathclass1 {
public static void main(String[] args)
{
double x = 28;
double y = 4;

// return the maximum of two numbers


System.out.println("Maximum number of x and y is: " +Math.max(x, y));

// return the square root of y


System.out.println("Square root of y is: " + Math.sqrt(y));
//returns 28 power of 4 i.e. 28*28*28*28
System.out.println("Power of x and y is: " + Math.pow(x, y));

// return the logarithm of given value


System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10


System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

// return the log of the sum of the argument and 1


System.out.println("log1p of x is: " +Math.log1p(x));

// return Euler’s no: raised to the power of a double value


System.out.println("exp of a is: " +Math.exp(x));

// return calculate the power of E and subtract one from it


System.out.println("expm1 of a is: " +Math.expm1(x));
}
}

OUTPUT:

Page No: 2
Course Code: 19CSL46
PROGRAM 1(C)
import java.util.Scanner;

class MatrixMultiplication {
public static void main(String args[]) {
int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];

System.out.println("Enter elements of first matrix");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
first[c][d] = in.nextInt();

System.out.println("Enter the number of rows and columns of second matrix");


p = in.nextInt();
q = in.nextInt();

if (n != p)
System.out.println("The matrices can't be multiplied with each other.");
else {
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

System.out.println("Enter elements of second matrix");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
second[c][d] = in.nextInt();

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++) {
for (k = 0; k < p; k++)
sum = sum + first[c][k] * second[k][d];

multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("Product of the matrices:");

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++)
System.out.print(multiply[c][d] + "\t");

Page No: 3
Course Code: 19CSL46
System.out.print("\n");
}
}
}
}
OUTPUT: 1

OUTPUT: 2

Page No: 4
Course Code: 19CSL46
PROGRAM NO.: 2.
Program 2
Write a Java Program to define a class, describe its constructor, overload the Constructors and
instantiate its object, and use static members.
AIM: to define a class, describe its constructor, overload the Constructors and instantiate its object, and
use static members.
THEORY: A java class file contains java bytecode that can be executed on the JVM. A java class file used
to produce by compiler.
A constructor is a special method that is called when an object is instantiated. A java class constructor
initializes instances of the class.

CODE:
Program 2 (A):
Write a Java Program to define a class, describe its constructor, overload the Constructors and
instantiate its object.
class Student{
String name,dept;
int id;
double marks;

Student()
{
name="abc";
id=1;
dept="CSE";
marks=70;
}

Student(String n,int id1,String d,double m)


{
name=n;
id=id1;
dept=d;
marks=m;
}

Student(Student st)
{
name=st.name;
id=st.id;
dept=st.dept;
marks=st.marks;
}

void display(){
System.out.println("Name: "+name+" Id: "+id+" Dept: "+dept+" Marks: "+marks);
}

public static void main(String[] args)


Page No: 5
Course Code: 19CSL46
{
Student s1=new Student();
s1.display();
Student s2=new Student("John",2,"CSE",78);
s2.display();
Student s3=new Student(s2);
s3.display();
}
}

OUTPUT

Page No: 6
Course Code: 19CSL46
Program 2(B) :
Write a Java Program to define a class, define instance methods for setting and Retrieving values of
instance variables and instantiate its object

class Student
{
String name,dept;
int id;
double marks;

void setData(String n,int id1,String d,double m)


{
name=n;
id=id1;
dept=d;
marks=m;
}

void display(){
System.out.println("Name: "+name+" Id: "+id+" Dept: "+dept+" Marks: "+marks);
}

public static void main(String[] args)


{
Student s1=new Student();
s1.setData("John",2,"CSE",78);
s1.display();
}
}

OUTPUT

Page No: 7
Course Code: 19CSL46
Program 2(C):
Write a Java Program to define a class, describe its constructor, overload the Constructors and
instantiate its object, and use static members.

class Student{
int rollno;
String name;
static String college = "ENGG";

//static method to change the value of static variable


static void change(){
college = "NHCE";
}

//constructor to initialize the variable


Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display() {
System.out.println(rollno+" "+name+" "+college);}
}

//Test class to create and display the values of object


public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

OUTPUT:

Page No: 8
Course Code: 19CSL46
PROGRAM NO.: 3
Write a Java program to demonstrate String class, String Buffer class
and its methods
AIM: To demonstrate String class, String Buffer class and its methods
THEORY: The string class represent strings. All string literals in java programs, such as "abc" are
implemented as instances of the class. Strings are constant, their values cannot be change.
String buffer is a peer class String that provides much of the functionality of strings. String represents fixed-
length, immutable character sequences. StringBuffer may have characters and substrings inserted in the
middle or appended at the end.
CODE:
Program 3(A)
Write a Java program to practice using String class and its methods

public class Student{

public static void main(String[] args)


{
String str1="Hello";
String str2="World";
//String str3= new String(“Bye”);
System.out.println("Character at 1 in String1 :"+str1.charAt(1));
System.out.println("Index of 'e' in String1 :"+str1.indexOf('e'));
if (str1.compareTo(str2)>0)
System.out.println("String 1 is greater than String 2");
else
System.out.println("String 1 is less than String 2");

str1.concat(str2);
System.out.println(str1);
System.out.println(str1.concat(str2));

String str3="This is a test";


String[] a=str3.split(" ");

for (int i=0;i<a.length;i++)


System.out.println(a[i]);

}
}

Output

Page No: 9
Course Code: 19CSL46
Program 3(B)
Write a Java program to practice using String Buffer class and its methods
public class Student
{

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("Hello");
System.out.println(sb.length());
System.out.println(sb.capacity());
sb.append("World");
System.out.println(sb);

System.out.println(sb.insert(1, 'i'));
System.out.println(sb.delete(2,5));
System.out.println(sb.deleteCharAt(2));

}
}

Output:

Page No: 10
Course Code: 19CSL46
PROGRAM NO.: 4
: Write a Java program to demonstrate nested classes and array of
Objects
AIM: To demonstrate nested classes and array of Objects
THEORY In java it allows to define a class within another class. Which is known as nested class, is a
member of its enclosing class.
The array of objects as defined its name, stores an array of objects. An object represents a single record in
memory.

CODE: Program 4(A)


Write a Java Program to demonstrate use of nested class
class Outer
{
int x=10;

void test()
{
Inner in=new Inner();
in.display();
}

class Inner
{
int y=20;
void display()
{
System.out.println("Outer x : " + x);
System.out.println("Inner y : " + y);
}
}}

public class Student


{
public static void main(String[] args)
{
Outer out = new Outer();
out.test();
}}

OUTPUT:

Page No: 11
Course Code: 19CSL46
Program 4(B)
Write a Java Program to implement array of objects

class Student
{
String name,dept;
int id;
double marks;

Student(String n,int id1,String d,double m)


{
name=n;
id=id1;
dept=d;
marks=m;
}

void display()
{
System.out.println("Name: "+name+" Id: "+id+" Dept: "+dept+" Marks: "+marks);
}

public static void main(String[] args) {


Student[] st=new Student[3];
st[0]=new Student("Alex",1,"cse",95);
st[1]=new Student("Berdych",2,"ise",95);
st[2]=new Student("Charlie",3,"ece",85);

for (int i=0;i<st.length;i++)


st[i].display();
}

OUTPUT:

Page No: 12
Course Code: 19CSL46
PROGRAM NO.: 5.
Write a Java Program to implement inheritance and demonstrate use of method overriding
AIM: To implement inheritance and demonstrate use of method overriding
THEORY: Inheritance is basically parent and child relation between the classes. There are three types of
inheritance single, multilevel, hierarchical.
If the subclass same method as declared in the parent class, it known as method overriding in java. method
that has been declared by one parent class is known as method overriding
CODE:
Program 5 (a) Single Inheritance
class Employee {
String companyName;
int salary;

Employee(String n,int s) {
companyName=n;
salary=s;
}
void showDetails() {
System.out.println("Employee's company name is: "+companyName+" salary
is: " +salary);
}
void status() {
System.out.println("I am the Parent class:Employee");
}
}

class Programmer extends Employee {


int bonus,totsal;

Programmer(String n,int s,int b) {


super(n,s);
bonus=b;
}

void showDetails() {
super.status();
super.showDetails();
this.status();
totsal=salary+bonus;
System.out.println("Programmer's Company name is: "+companyName+" total salary
is: "+totsal);

}
void status() {
System.out.println("I am the Child class:"+this.getClass().getSimpleName());
}

public static void main(String[] args) {


Programmer p=new Programmer("HSS",40000,10000);
p.showDetails();
}
}
Page No: 13
Course Code: 19CSL46
OUTPUT:

Program 5(b) : Method Overriding


class AXIS extends Bank {
int getRateOfInterest() {
return 9;
}
}

// Test class to create objects and call the methods


class Test2 {
public static void main(String args[]) {
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("SBI Rate of Interest: " + s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: " + i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: " + a.getRateOfInterest());
}
}

Output:

Page No: 14
Course Code: 19CSL46
PROGRAM NO.: 6.
Write a Java Program to implement multilevel inheritance by applying various access controls to its
data members and methods
AIM: To implement multilevel inheritance by applying various access controls to its data members and
methods
THEORY: When class extends a class, which extends another class then its is called multilevel inheritance.
So in this case class C is implicitly inheriting the properties and methods of class along with class B what is
called multilevel inheritance.

CODE:
class Person {
private int pwd = 63106; // can be accessed only within class Person
public String name; // can be accessed anywhere
String addr; // default-can be accessed only within the same package
protected String status; // can be accessed within same package or subclass in another pkg

Person(String n, String a, String s) {


name = n;
addr = a;
status = s;
}

// private methods are not overridden


void dispwd() {
System.out.println("Person password is: " + pwd);
}

protected void disp() {


System.out.println("Personal Information : ");
System.out.println("Name Address Status");
System.out.println(name + " " + addr + " " + status);
}
}

class Student_1 extends Person {


private int spwd = 7908526;
String sem, dept, usn;

Page No: 15
Course Code: 19CSL46
Student_1(String n, String a, String s, String se, String d, String u) {
super(n, a, s);
sem = se;
dept = d;
usn = u;
}

// new dispwd() method unique to Student_1 class


void dispwd() {
System.out.println("Student password is: " + spwd);
}

// overriding method with more accessibility


public void disp() {
super.dispwd();
System.out.println("Student College Information : ");
System.out.println("Semester Dept USN");
System.out.println(sem + " " + dept + " " + usn);
}
}

class Marks extends Student_1 {


String sub[];
int marks[], total;

Marks(String n, String a, String s, String se, String d, String u, String[] su, int[] m) {
super(n, a, s, se, d, u);
sub = su;
marks = m;
}

void total_marks() {
for (int i = 0; i < marks.length; i++)
total = total + marks[i];

public void display() {


Page No: 16
Course Code: 19CSL46
super.disp();
total_marks();
System.out.println("Total marks are : " + total);
System.out.println("Subjects are :");
for (int i = 0; i < sub.length; i++)
System.out.println(sub[i] + " : " + marks[i]);

}
}
public class MultiLevelAccessCntrldemo_6 {
public static void main(String[] args) {
String[] sub1 = { "Java", "Arm", "Maths" };
int[] marks1 = { 91, 92, 93 };
Marks m1 = new Marks("Deepak", "SubhasNagar", "Student", "4thsem", "CSE", "1NH19CS716", sub
1, marks1);
m1.display();
}
}

OUTPUT:

Page No: 17
Course Code: 19CSL46
PROGRAM NO.: 7.
Write a program to demonstrate use of implementing interfaces
AIM: To demonstrate use of implementing interfaces
THEORY: Interface is an abstract type, which is used to specify behaviour that classes must implement.
They are similar to protocols. Interfaces are declared using the interface key word, and may only contain
method signature
CODE:
package pk1;

interface Printable
{
void print();
}
interface Showable
{
intYear=2020;

void show();
}

class InterfaceDemo1 implements Printable,Showable


{

public static void main(String[] args)


{
InterfaceDemo1 d=newInterfaceDemo1();
d.print();
d.show();

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

}
public void show()
{
System.out.println("Welcome "+Year);
//Year=Year+1;

}
}

OUTPUT:

Page No: 18
Course Code: 19CSL46
PROGRAM NO.: 8.
Write a program to demonstrate use of extending interfaces
AIM: To demonstrate use of extending interfaces
THEORY: And interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface. One interface can extends many interface but a class
implements many classes.
CODE:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}

public class ExtIntfMain implements Showable


{

publicstaticvoid main(String[] args)


{
ExtIntfMainobj = newExtIntfMain();
obj.print();
obj.show();
}
Public void print()
{
System.out.println("Hello");
}
Public void show()
{
System.out.println("Welcome");
}

OUTPUT:

Page No: 19
Course Code: 19CSL46
PROGRAM NO.: 9.
9(A): Write a Java program to implement the concept of importing classes from user defined package
and creating packages.
AIM: To demonstrate implement the concept of importing classes from user defined package and creating
packages.
THEORY: A java package organizes java classes into namespaces, providing a unique namespace for each
type it contains. Classes in the same package can access each other's package and protected members
CODE:
Package mypack;

public class SimplePack1


{
int var1=10;
private int var2=20;
protected int var3 = 30;
public int var4=40;

public static void main(String args[])


{
SimplePack1 obj=new SimplePack1();
obj.display();

public void display()


{
System.out.println("Welcome to package");
System.out.println("Private Var Value "+var1);
}

package mypack1;

import mypack.*;

public class SimplePack2


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

public static void main(String args[])


{
SimplePack1 obj1 = new SimplePack1();
SimplePack2 obj2 = new SimplePack2();
obj1.display();
obj2.print();
}

Page No: 20
Course Code: 19CSL46
}

package mypack2;
class SimplePack3
{

SimplePack3()
{
SimplePack1 obj3=new SimplePack1();
System.out.println("Default Variable value = "+obj3.var3);
}

public static void main(String args[])


{
new SimplePack3();
}
}

OUTPUT:

Page No: 21
Course Code: 19CSL46
PROGRAM NO.: 9.
9(B): A Java Program to demonstrate dynamic binding.
AIM: To demonstrate dynamic binding.
THEORY: In dynamic binding the method call is boned to method body runtime.WHich is also known as
late binding. This is done by using instance methods
CODE:
publicclassDynamicDispatch
{

publicstaticvoid main(String[] args)


{
Bank b;
b=newSBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=newICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=newAXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}

class Bank
{
intgetRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank
{
intgetRateOfInterest()
{
return 8;
}
}

class ICICI extends Bank


{
intgetRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
intgetRateOfInterest()
{
return 9;
}
}

Page No: 22
Course Code: 19CSL46
OUTPUT:

Page No: 23
Course Code: 19CSL46
PROGRAM NO.: 10.
Write a program to implement the concept of threading by extending Thread Class
AIM: To implement the concept of threading by extending Thread Class
THEORY: Extend thread class creates a tread by a new class that extends thread class and create an instance
of the class.
CODE:
import java.lang.Thread;
class NewThread1 extends Thread {
Thread t;
NewThread1() {
t=new Thread(this,"DemoThread");//Constructor Thread(Runnable r,String name)
System.out.println("Child Thread" +t);
t.start();
}
public void run() {
try {
for(int i=5;i>0;i--) {
System.out.println("Child Thread"+i);
Thread.sleep(3500);
}}

catch(InterruptedException e) {
System.out.println("Child Interrupted");
}
System.out.println("Child Thread exiting");
}}
public class NewThread{
public static void main(String[] args) {
new NewThread1();
try {
for(int n=5;n>0;n--){
System.out.println("Main Thread"+n);
Thread.sleep(500);
}}
catch(InterruptedException e) {
System.out.println("Main Thread Interrupted");
}
System.out.println("Main Thread exiting");
}}
OUTPUT:

Page No: 24
Course Code: 19CSL46
PROGRAM NO.: 11.
Write a program to implement the concept of threading by implementing Runnable Interface
AIM: To implement the concept of threading by implementing Runnable Interface
THEORY: The runnable should be implemented by any class whose instance are intended to be executed
by a thread. The class must define a method of no arguments called run.
CODE:
import java.lang.Thread;

class ImplementingRunnableThread implements Runnable


{
Thread t;
int i;
String s[]={"Welcome","to","Java","Programming","Language"};
ImplementingRunnableThread()
{
t=new Thread(this,"Runnable Interface Thread");
System.out.println("Thread is:"+t);
t.start();
}
public void run()
{
String name=t.getName();
for(int i=0;i<s.length;++i)
{
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
System.out.println(name+":"+s[i]);
}
}
}
public class RunnableInterfaceExample
{
public static void main(String args[])
{
new ImplementingRunnableThread();
}
}

OUTPUT:

Page No: 25
Course Code: 19CSL46
PROGRAM NO.: 12.
Write a java program that implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and if the value is even, second thread computes the square
of the number and prints. If the value is odd, the third thread will print the value of cube of the number.

AIM: To implements a multi-thread application that has three threads


THEORY: Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process
CODE:
import java.util.*;

class Generate extends Thread{

public void run(){

Random r = new Random();

while(true) {

int num = r.nextInt(100);

if(num % 2 == 0)
new Square(num).start();
else
new Cube(num).start();

try {
sleep(1000);
}

catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Square extends Thread{


private int n;

public Square (int num){


n=num;
}
public void run(){
System.out.println(" Square of "+n+" : " + (n*n));
}
}

class Cube extends Thread{


private int n;

public Cube (int num){


n=num;
}
public void run(){
System.out.println(" Cube of "+n+" : " + (n*n*n));
}
}

public class GenerateMain {


Page No: 26
Course Code: 19CSL46
public static void main(String[] args) {
Generate t1 = new Generate();
t1.start();
}
}

OUTPUT:

Page No: 29
Course Code: 19CSL46
PROGRAM NO.: 13.
Write a program to implement the concept of Exception Handling
using predefined exception

AIM: To implement the concept of Exception Handling using predefined exception


THEORY: The exception handelling is one of the powerful mechanism to handel the runtime errors so that
normal flow of the apllication can be maintained.
CODE:
class PreDefExcep{
public static void main(String argv[])
{
int a = 10, b = 5, c = 5, x, y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Exception caught! Divison by zero!");
}
y = a/(b+c);
System.out.println("y = " + y);
}
}

OUTPUT:

Page No: 30
Course Code: 19CSL46

PROGRAM NO.: 14.


Write a program to implement the concept of Exception Handling by creating user defined exceptions
AIM: To implement the concept of Exception Handling by creating user defined exceptions
THEORY: The exception handling is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
CODE:
import java.util.*;

class VoteException extends Exception {

VoteException(String message) {
super(message);
}
}

class UserDefExcep {
public static void main(String a[]) {
int age;
Scanner in = new Scanner(System.in);

try {
System.out.println("Enter your age:");
age = in.nextInt();

if (age< 18) {
throw new VoteException("You are not eligible to vote! ");
}
else {
System.out.println("You are eligible to vote!");
}
}

catch (VoteException e) {
System.out.println("Caught VoteException");
System.out.println(e.getMessage());
}

}
}

OUTPUTS:

Page No: 31
Course Code: 19CSL46

PROGRAM NO.: 15

Write a program to demonstrate File I/O Operations

AIM: To demonstrate file input output operations.


THEORY: Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.

CODE:
import java.io.*;

public class Main {


public static void main(String args[]) throws IOException, FileNotFoundException {

String str[] = new String[100];


int i;

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader br = new BufferedReader(isr);

System.out.println("Enter lines of text.");


System.out.println("Enter 'stop' to quit.");

FileWriter fw = new FileWriter("input.txt");

for(i=0; i<100; i++) {


str[i] = br.readLine();
if(str[i].equals("stop"))
break;
fw.write(str[i]+"\n");
}

fw.close();
//Writing to input file is over. Hence close FileOutputStream

//Now, copy content of input.txt into output.txt


FileInputStream fin;
FileOutputStream fout;

fin = new FileInputStream ("input.txt");


fout = new FileOutputStream("output.txt");

fin = new FileInputStream("input.txt");


fout = new FileOutputStream("output.txt");

do {
i = fin.read();
if(i != -1) fout.write(i);
}
while(i != -1);

fout.close();
fin.close();

Page No: 32
Course Code: 19CSL46
//Now read contents of input.txt and output.txt
FileInputStream fin1;
FileInputStream fin2;

fin1 = new FileInputStream("input.txt");


fin2 = new FileInputStream("output.txt");

System.out.println("\n\nContent of input.txt: ");


do {
i = fin1.read();
if(i != -1)
System.out.print((char) i);
}
while(i != -1);

System.out.println("\n\nContent of output.txt: ");


do {
i = fin2.read();
if(i != -1)
System.out.print((char) i);
}
while(i != -1);

fin1.close();
fin2.close();

}
}

OUTPUT:

Page No: 33
Course Code: 19CSL46
PROGRAM NO.: 16

Write a program to demonstrate ArrayList Class, LinkedList Class,


TreeSet Class.

AIM: To demonstrate ArrayList Class, LinkedList Class and Treeset Class


THEORY: ArrayList is a part of collection framework and is present in java.util package. It provides us
with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs
where lots of manipulation in the array is needed. This class is found in java.util package.

LinkedList is a part of the Collection framework present in java.util package. This class is an
implementation of the LinkedList data structure which is a linear data structure where the elements are not
stored in contiguous locations and every element is a separate object with a data part and address part. The
elements are linked using pointers and addresses.

TreeSet class in java implements the Set interface that uses a tree for storage. It inherits AbstractSet class
and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.

CODE:
import java.util.*;

public class Main {


public static void main(String args[]){

ArrayList<String>al = new ArrayList<String>();


System.out.println("\nArray List");
System.out.println("Initial size of al: " + al.size()); //1
al.add("A"); //2
al.add("B");
al.add("C");
al.add("D");
al.add(2, "A2");
al.remove("A"); //3
System.out.println("Element at index 3 is: "+ al.get(2)); //4
System.out.println("Is ArrayList empty? :"+ al.isEmpty()); //5
System.out.println("Index of A2 in ArrayList is: " + al.indexOf("A2")); //6
System.out.println("Does ArrayList contain G? :"+ al.contains("G")); //7
al.set(2, "Rahul"); //8
al.trimToSize(); //9
al.toArray(); //10
System.out.println("Content: "+ al);

LinkedList<String>ll = new LinkedList<String>();


System.out.println("\nLinked List");
ll.add("A"); //1
ll.add("B");
ll.add("C");
ll.add("D");
ll.add("E");
ll.addLast("Z"); //2
ll.addFirst("A"); //3
ll.remove("F"); //4
ll.removeFirst(); //5
ll.removeLast(); //6
System.out.println("Element at index 3 is: "+ ll.get(2)); //7
ll.set(2, " Rahul"); //8
Page No: 34
Course Code: 19CSL46
System.out.println("Index of A2 in LL is: " + ll.indexOf("C")); //9
System.out.println("Size of LL: " + ll.size()); //10

TreeSet<String>ts = new TreeSet<String>();


System.out.println("\nTree Set");
ts.add("A"); //1
ts.add("B");
ts.add("C");
ts.add("D");
ts.add("E");
ts.add("F");
System.out.println(ts.subSet("B", "E")); //2
System.out.println(ts.ceiling("C")); //3
System.out.println(ts.lower("C")); //4
System.out.println(ts.higher("D")); //5
System.out.println(ts.pollFirst()); //6
System.out.println(ts.pollLast()); //7
System.out.println("Does TreeList contain G? :"+ ts.contains("G")); //8
System.out.println("Is TreeList empty? :"+ ts.isEmpty()); //9
System.out.println("Size :"+ ts.size()); //10
}
}

OUTPUT:

Page No: 35

You might also like