Oops Through Java Lab Manual - R22
Oops Through Java Lab Manual - R22
B. TECH CSE
(II YEAR – II SEM)
R22 REGULATION
(2023-24)
Name :
Roll no:
Section:
Year :
Vision
To acknowledge quality education and instill high patterns of discipline making the
students technologically superior and ethically strong which involves the improvement
in the quality of life in human race.
Mission
To achieve and impart holistic technical education using the best of infrastructure,
outstanding technical and teaching expertise to establish the students in to competent and
confident engineers.
Evolving the center of excellence through creative and innovative teaching learning
practices for promoting academic achievement to produce internationally accepted
competitive and world class professionals.
After the completion of the course, B. Tech Computer Science andEngineering,the graduates will
have the following Program Specific Outcomes:
1. Fundamentals and critical knowledge of the Computer System:- Able to Understand the
working principles of the computer System and its components , Apply the knowledge to build,
asses, and analyze the software and hardware aspects of it .
3. Applications of Computing Domain & Research: Able to use the professional, managerial,
interdisciplinary skill set, and domain specific tools in development processes, identify the
research gaps, and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multi disciplinary environments.
12 .Life- long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
Write a java program to find the Fibonacci series using recursive and non
1 1
recursive functions
Week
2 Write a java program to multiply two given matrices. 4
1
Write a java program for Method overloading and Constructor
3 7
overloading
Write a program to demonstrate execution of static blocks, static
4 10
variables & static methods.
Week
5 Write a java program to display the employee details using Scanner class 12
2
Week Write a program to create user defined package and demonstrate various
14 27
5 access modifiers.
Week Write a program if number is less than 10 and greater than 50 it generate
16 31
6 the exception out of range. else it displays the square of number.
17 Write a program with multiple catch Statements. 32
Write a program to list all the files in a directory including the files
Week 25 53
present in all its subdirectories.
10
26 Write a Program to Read the Content of a File Line by Line 56
PROGRAM-1 WRITE A JAVA PROGRAM TO FIND THE FIBONACCI SERIES USING RECURSIVE AND
NON RECURSIVE FUNCTIONS:
//Class to write the recursive and non recursive functions.
class fib
{
int a,b,c;
//Non recursive function tofind theFibonacci series.
void nonrecursive(int n)
{ a=0; b=1;
c=a+b;
System.out.print(b);
while(c<=n)
{
System.out.print(c);
a=b;
b=c;
c=a+b;
}
}
// Recursive function to find the Fibonacci series. int recursive(int n)
{
if(n==0) return (0);
if(n==1) return (1);
else
return(recursive(n-1)+recursive(n-2));
}
}
EXERCISE:
1. Write a java program to print the multiplication table.
2. Write a java program to find the Factorial of a given integer using recursive and non recursive
functions
// Constructor Overloading
public class Student {
//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
EXERCISE:
1. Write a java program to sort the given integers in ascending/descending order.Write a
java program to display characters in a string in sorted order.
2. Write a program that uses a sequence input stream to output the contents of two files.
3. Write a java program that reads a file and displays the file on the screen, with an asterisk
mark before each line.
4. Write a java program that displays the number of characters, lines, words, white spaces
in a text file.
PROGRAM-5 WRITE A JAVA PROGRAM TO DISPLAY THE EMPLOYEE DETAILS USING SCANNER
CLASS
importjava.util.*;
class EmployeeDetails
{
public static void main(String args[])
{
System.out.println("entername,id,age,salary");
Scanner sc=newScanner(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);
}
}
EXERCISE:
1. Write a java program to Read and display the student details using Scanner class.
PROGRAM-6 WRITE A PROGRAM FOR SORTING A GIVEN LIST OF NAMES IN ASCENDING ORDER
// Single Inheritance
class Animal
{
void sleep(){System.out.println("sleeping. ");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking. ");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.sleep();
}
}
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
// Hybrid Inheritance
class HumanBody
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");
}
}
interface Male
{
public void show();
}
interface Female
{
public void show();
}
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in interfaces Male and Female");
}
public void displayChild()
{
System.out.println("Method defined inside Child class");
}
class A
{
int a=10;
voiddisplay() {
B b=new B(); b.show();
}
class B {
int b=20;
void show() {
System.out.println(" a value is " +a);
System.out.println(" b value is " +b);
}}}
classInnerDemo {
public static void main(String args[]) {
A a=new A();
a.display();
}}
Three Test Outputs:
com/example/Calculator.java
package com.example;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("Cannot divide by zero!");
}
}
}
Now, create another file outside the "com" folder to access the Calculator class from the user-
defined package.
PackageExample.java
import com.example.Calculator;
public class PackageExample {
PROGRAM-15 WRITE A PROGRAM TO DEMONSTRATE THE USE OF SUPER AND FINAL KEYWORDS.
// Super Keyword
class employee {
int wt = 8;
}
class clerk extends employee {
int wt = 10; //work time
void display() {
System.out.println(super.wt); //will print work time of clerk
}
public static void main(String args[]) {
clerk c = new clerk();
c.display();
}
}
// Final Keyword
class stud {
final void show() {
System.out.println("Class - stud : method defined");
}
}
class books extends stud {
void show() {
System.out.println("Class - books : method defined");
}
public static void main(String args[]) {
books B2 = new books();
B2.show();
}}
classCustomTest {
public static void main(String arr[]) {
try {
int a=Integer.parseInt(arr[0]);
if(a<0||a>50)
throw(new outofRangeException("valid range is 10 to 50"));
{
int s=a*a;
System.out.println("Square is:"+s);
}
}catch(Exception ex)
{
System.out.println(ex);
}
}}
Three test outputs
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");
}
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Three test outputs:
import java.util.*;
// class for Even Number
class EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// Driver class
public class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
Example 2:
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
t1.start();
t2.start();
t3.start();
}
}
Signature of Faculty
// Array List
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
// Vector
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
// stack
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Department of Computer Science and Engineering
Page 45
OOPS THROUGH JAVA 2023 - 2024
// Hash Table
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
PROGRAM-24 WRITE A PROGRAM FOR PRODUCER AND CONSUMER PROBLEM USING THREADS
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list and consumer (removes items).
public static class PC {
// and sleep
Thread.sleep(1000);
}
}
}
}
}
PROGRAM-25 WRITE A PROGRAM TO LIST ALL THE FILES IN A DIRECTORY INCLUDING THE FILES
PRESENT IN ALL ITS SUBDIRECTORIES.
import java.io.File;
// for files
if (arr[index].isFile())
System.out.println(arr[index].getName());
// for sub-directories
else if (arr[index].isDirectory()) {
System.out.println("[" + arr[index].getName()
+ "]");
// Driver Method
public static void main(String[] args)
{
// Provide full path for directory(change accordingly)
String maindirpath = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
// File object
File maindir = new File(maindirpath);
import java.io.FileReader;
import java.io.BufferedReader;
class Main {
public static void main(String[] args) {
// Creates a FileReader
FileReader file = new FileReader("input.txt");
// Creates a BufferedReader
BufferedReader input = new BufferedReader(file);
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array);
PROGRAM-27 WRITE A PROGRAM THAT CONNECTS TO A DATABASE USING JDBC DISPLAY ALL
RECORDS IN A TABLE.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/testDb","username", "password");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
} catch(SQLException e) {
System.out.println("SQL exception occured" + e);
}
}
}
PROGRAM-28 WRITE A PROGRAM TO CONNECT TO A DATABASE USING JDBC AND INSERT VALUES
INTO IT.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
PROGRAM-29 WRITE A JAVA PROGRAM TO CONNECT TO A DATABASE USING JDBC AND DELETE
VALUES FROM IT
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Three test outputs:
PROGRAM 30 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.
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
Department of Computer Science and Engineering
Page 67
OOPS THROUGH JAVA 2023 - 2024
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
} }