OOPS Through JAVA
OOPS Through JAVA
Department of CSE
(Emerging Technologies)
Data Science, Cyber Security & IoT
B.TECH(R-20 Regulation)
(II YEAR – II SEM)
(2022-23)
EMERGING TECHNOLOGIES
Object Oriented Programming through JAVA
LAB
(R20A0585)
LAB MANUAL
Prepared by
D KALPANA, ASSIT. PROF
*(First Time Prepared Faculty)
On
20.02.2022
Updated by
M JYOTHI, ASSIT. PROF
**(Second-time Prepared Faculty if updated the existed Lecture Notes)
On
28.02.2023
EMERGING TECHNOLOGIES
Vision
Mission
The department of CSE (Emerging Technologies) is committed to:
To offer highest Professional and Academic Standards in terms of Personal growth and
satisfaction.
Make the society as the hub of emerging technologies and thereby capture
opportunities in new age technologies.
To create a benchmark in the areas of Research, Education and Public Outreach.
To provide students a platform where independent learning and scientific study are
encouraged with emphasis on latest engineering techniques.
QUALITY POLICY
To pursue continual improvement of teaching learning process of Undergraduate and
Post Graduate programs in Engineering & Management vigorously.
To provide state of art infrastructure and expertise to impart the quality education and
research environment to students for a complete learning experiences.
To offer quality relevant and cost effective programmes to produce engineers as per
requirements of the industry need.
SYLLABUS
M R C E T CAMPUS | AUTONOMOUS INSTITUTION - UGC, GOVT. OF INDIA
1. To prepare students to become familiar with the Standard Java technologies ofJ2SE
Week 1:
a) Write a java program to find the Fibonacci series using recursive and non-recursive
functions
Week 2:
a) Write a program to demonstrate execution of static blocks ,static variables & static
methods.
Week 3:
Week 4:
a) Write a program to create an abstract class named Shape that contains two integers and an
empty method named printArea (). Provide three classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method printArea () that prints the area of the given shape.
Week 5:
b) Write a program to create user defined package and demonstrate various access modifiers.
Week 6:
a) Write a program if number is less than 10 and greater than 50 it generate the exception out
of range. else it displays the square of number.
Week 7:
a) Write a Program to implement simple Thread by extending Thread class and implementing
runnable interface.
b) Write a program that implements a multi-thread application that has three threads
Week 8:
Week 9:
Week 10:
a) Write a program to list all the files in a directory including the files present in all its
subdirectories.
Week 11:
a) Write a program that connects to a database using JDBC display all records in a table.
b) Write a program to connect to a database using JDBC and insert values into it.
c) Write a program to connect to a database using JDBC and delete values from it
Week 12:
Write a program that works as a simple calculator. Use a Grid Layout to arrange
Buttons for digits and for the + - * % operations. Add a text field to display the result.
COURSE OUTCOMES:
Upon successful completion of this course, the students will be able to:
1. Analyze the necessity for Object Oriented Programming paradigm and over structured
programming and become familiar with the fundamental concepts in OOP.
2. Demonstrate an ability to design and develop Java programs, analyze, and interpret object
oriented data and report results.
5. Demonstrate an ability to visualize and work on laboratory and multidisciplinary tasks like
console and windows applications for standalone programs.
INDEX
S.No PageNos.
List of Programs
A)Write a java program to find the Fibonacci series using recursive and 1
nonrecursive functions
1 B) Write a java program to multiply two given matrices. 3
C) Write a java program for Method overloading and Constructoroverloading 4
A) Write a program to demonstrate execution of static blocks, static variables 9
& static methods.
2 B) Write a program to display the employee details using Scanner class 10
C) Write a program for sorting a given list of names in ascending order 11
A) Write a program to implement single and Multi level inheritance 13
3 B) Write a program to implement Hierarchical Inheritance. 15
C) Write a program to implement method overriding. 17
A) Write a program to create an abstract class named Shape that contains two
integers and an empty method named printArea (). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes extends 20
the class Shape. Each one of the classes contains only the method printArea ()
4 that prints the area of the given shape.
B) Write a program to implement Interface. 22
C) Write a program to implement multiple and Hybrid Inheritance 23
5 A)Write a program to create inner classes 26
B) Write a program to create user defined package and demonstrate various 27
access modifiers.
C) Write a program to demonstrate the use of super and final keywords. 31
A) Write a program if number is less than 10 and greater than 50 it generate 34
the exception out of range. else it displays the square of number.
6 B) Write a program with multiple catch Statements. 35
C) Write a program to implement nested try 37
A) Write a program to list all the files in a directory including the files present 60
10 in all its subdirectories.
B) Write a Program to Read the Content of a File Line by Line 63
A) Write a program that connects to a database using JDBC display all records 66
in a table.
B) Write a program to connect to a database using JDBC and insert values into 68
11
it
C) Write a program to connect to a database using JDBC and delete values 70
from it
Write a program that works as a simple calculator. Use a Grid Layout to 73
12 arrange Buttons for digits and for the + - * % operations. Add a text field to
display the result.
//creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3];
//3 rows and 3 columns
Aim: Write a java program for Method overloading and Constructor overloading Method
overloading:
Program:
Method overloading:
import java.io.*;
class MethodOverloadingEx
{
static int add(int a, int b)
{
return a + b;
}
Output:
Constructor overloading
EXERCISE:
1. Write a java program to find all even and odd integers up to a given integer.
2. Write a java program that reads a line of integers and displays each integers and the
product of all integers use String Tokenizer.
Aim: Write a JAVA program to demonstrate execution of static blocks ,static variables &
static methods.
Program:
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
Aim: Write a JAVA program to display the employee details using Scanner class
Program:
import java.util.*;
class EmployeeDetails
{
public static void main(String args[])
{
System.out.println("enter name,id,age,salary");
Scanner sc=new Scanner(System.in);
String n=sc.next();
int i=sc.nextInt();
int a=sc.nextInt();
float s=sc.nextFloat();
System.out.println("name is"+n+"idis"+i+"ageis"+a+"salaryis"+s);
}
}
Aim: Write a JAVA program for sorting a given list of names in ascending order
Program:
class AscendingNames {
public static void main(String[] args)
{
// storing input in variable
int n = 4;
Aim: Write a java program to implement single and Multi level inheritance
Program:
Single inheritance:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}
class A {
public void print_A() { System.out.println("Class A"); }
}
class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
}
class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
EXERCISE:
AIM: Write a JAVA program to create an abstract class named Shape that contains two integers
and an empty method named printArea (). Provide three classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes contains
only the method printArea () that prints the area of the given shape.
Program:
package project1;
import java.util.*;
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle(); r.area(2,5);
Circle c=new Circle(); c.area(5,5);
Triangle t=new Triangle(); t.area(2,5);
}
}
OUTPUT:
Program:
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank{
public float rateOfInterest(){
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
OUTPUT:
EXERCISE:
Program:
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
OUTPUT:
AIM: Write a JAVA program to create user defined package and demonstrate various access
modifiers.
Program:
// private access modifier
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
OUTPUT:
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
OUTPUT:
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
OUTPUT:
//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
OUTPUT:
EXERCISE:
AIM: Write a program to demonstrate the use of super and final keywords.
Program:
Program:
OUTPUT:
Program:
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
OUTPUT:
EXERCISE:
AIM: Write a JAVA program if number is less than 10 and greater than 50 it generate the
exception out of range. else it displays the square of number..
Program:
AIM: Write a JAVA program that implements a multi-thread application that has three threads
Program:
import java.util.Random;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
//This thread generates random number 10 times between 1 to 100 for every 1 second. The
generated random number is then passed as argument to Square and Cube threads.
Output varies each time a program is executed.
Program:
import java.lang.*;
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
}
}
OUTPUT:
EXERCISE:
AIM: Write a Program to implement simple Thread by extending Thread class and implementing
runnable interface.
Program:
Program:
a)array List
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
System.out.println(list);
OUTPUT:
b) Vector
import java.io.*;
import java.util.*;
class VectorDemo {
OUTPUT:
EXERCISE:
Program:
AIM: Write a JAVA program for producer and consumer problem using Threads
Program:
p1.start();
c1.start();
class CubbyHole {
try {
wait();
} catch (InterruptedException e) {}
available = false;
notifyAll();
return contents;
try {
wait();
} catch (InterruptedException e) { }
contents = value;
available = true;
notifyAll();
cubbyhole = c;
this.number = number;
int value = 0;
value = cubbyhole.get();
cubbyhole = c;
this.number = number;
cubbyhole.put(i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
OUTPUT:
EXERCISE:
Program:
AIM: Write a JAVA program to list all the files in a directory including the files present in all its
subdirectories.
Program:
import java.io.File;
public class DisplayFileExample1
{
public void printFileNames(File[] a, int i, int lvl)
{
// base case of the recursion i == a.length means the directory has no more files. Hence, the
recursion has to stop
if(i == a.length)
{
return;
}
// tabs for providing the indentation for the files of sub-directory
for (int j = 0; j < lvl; j++)
{
System.out.print("\t");
}
// checking if the encountered object is a file or not
if(a[i].isFile())
{
System.out.println(a[i].getName());
}
// for sub-directories
else if(a[i].isDirectory())
{
System.out.println("[" + a[i].getName() + "]");
// recursion for sub-directories
printFileNames(a[i].listFiles(), 0, lvl + 1);
}
// recursively printing files from the directory i + 1 means look for the next file
printFileNames(a, i + 1, lvl);
}
public static void main(String[] argvs)
{
// Providing the full path for the directory
String path = "E:\\Documents";
File fObj = new File(path); // creating a file object
DisplayFileExample1 obj = new DisplayFileExample1();
if(fObj.exists() && fObj.isDirectory())
{
// array for the files of the directory pointed by fObj
File a[] = fObj.listFiles();
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
System.out.println("Displaying Files from the directory: " + fObj);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
// Calling the method
obj.printFileNames(a, 0, 0);
}
}
}
OUTPUT:
EXERCISE:
Program:
AIM: Write a JAVA program that connects to a database using JDBC display all records in a
table
Program:
import java.sql.*;
class MysqlCon
{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Statement stmt=con.createStatement();
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
}
// To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.
Two ways to load the jar file:
Paste the mysqlconnector.jar file in jre/lib/ext folder
Set classpath
1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
1.temporary
2.permanent
AIM: Write a program to connect to a database using JDBC and insert values into it.
Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
OUTPUT:
C:\>javac JDBCExample.java
C:\>java JDBCExample
Inserting records into the table...
Inserted records into the table...
C:\>
EXERCEISE:
AIM: Write a program to connect to a database using JDBC and delete values from it
Program:
WEEK: 12 Date:
AIM: Write a program that works as a simple calculator. Use a Grid Layout to arrange
Buttons for digits and for the + - * % operations. Add a text field to display the result.
Program:
import javax.swing.*; import javax.swing.event.*; import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ActionListener
{
public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;
public JTextField tf1;
public JPanel p;
public String v = "";
public String v1 = "0";
public String op = "";
public A( )
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10);
p.add(tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1"); b1.addActionListener(this); add(b1);
b2 = new JButton("2"); b2.addActionListener(this); add(b2);
b3 = new JButton("3"); b3.addActionListener(this); add(b3);
b4 = new JButton("4"); b4.addActionListener(this); add(b4);
b5 = new JButton("5"); b5.addActionListener(this); add(b5);
b6 = new JButton("6"); b6.addActionListener(this); add(b6);
b7 = new JButton("7"); b7.addActionListener(this); add(b7);
b8 = new JButton("8"); b8.addActionListener(this); add(b8);
b9 = new JButton("9"); b9.addActionListener(this); add(b9);
b10 = new JButton("0"); b10.addActionListener(this); add(b10);
tf1.setText(v);
}
break;
case "7": {
v = v + "7";
tf1.setText(v);
}
break; case "8": {
v = v + "8";
tf1.setText(v);
}
break; case "9": {
v = v + "9";
tf1.setText(v);
}
break; case "0": {
v = v + "0";
tf1.setText(v);
}
break; case "+": {
op = "+";
v1 = tf1.getText(); v = "";
}
break; case "-": {
op = "-";
v1 = tf1.getText(); v = "";
}
break; case "*": {
op = "*";
v1 = tf1.getText(); v = "";
}
break; case "/": {
op = "/";
v1 = tf1.getText(); v = "";
}
break;
case "%": {
op = "%";
v1 = tf1.getText(); v = "";
}
break; case "=": {
switch (op) {
case "+": {
v = tf1.getText();
if (v.equals("")) { v = "0";
}
long i = Long.parseLong(v1) + Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break; case "-": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) - Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "*": {
v = tf1.getText(); if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) * Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "/": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) / Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
catch (Exception ex)
{ JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
case "%": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
}
}
break;
}
}
}
public class Calc
{
public static void main(String[] args)
{
A a = new A();
}
}
OUTPUT: