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

Java Lab Manual

Uploaded by

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

Java Lab Manual

Uploaded by

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

GEMS POLYTECHNIC COLLEGE

(Approved by AICTE, Govt. of India, F. No Northern/2015/1-


2474317051) NH-2, Jogiya More, Ratanpura,
Aurangabad, Bihar – 824 121
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE &

ENGINEERING 2018507A – OBJECT ORIENTED

PROGRAMMING THROUGH JAVA LAB

STATE BOARD OF TECHNICAL EDUCATION, BIHAR V

SEMESTER DIPLOMA IN COMPUTER SCIENCE & ENGG.

(Effective from Session 2022 -25 Batch)

LABORATORY MANUAL
Prepared By
Ms. Meena Kumari,
Lecturer
INDEX
Sl. No Content Page No
1 Vision & Mission of the Institution & Department 3

2 Teaching and Examinations Scheme 4

3 Course Outcomes 5

4 Write programs using Java built-in functions using all data 6


types

5 Write programs using conditional statements and loop 8


statements.

6 Write a program to read data from keyboard. 12

7 Write a program to create class and objects. 13

8 Write programs using constructors. 14

9 Write a program to illustrate usage of command line 15


arguments.

10 Write programs using concept of overloading methods. 17

11 Exercise on inheritance. 19

12 Write a program using the concept of method overriding. 20

13 Exercise on importing packages. 22

14 Exercise on interfaces 24

15 Exercise on exception handling. 25

16 Exercise on multithreading and thread priorities. 27

17 Exercise on database connectivity using JDBC. 28

Prepared By Verified By

Faculty In-charge HOD/CSE

1
GEMS POLYTECHNIC COLLEGE
(Approved by AICTE, Govt. of India, F. No Northern/2015/1-

2474317051) NH-2, Jogiya More, Ratanpura,


Aurangabad, Bihar – 824 121

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VISION of the Department


To produce quality diploma Computer Science Engineers to serve
Ethically and Technically for the Advancement of the society.
MISSION of the Department
• To strengthen the technical knowledge in computer science through
analytical learning.
• To inculcate moral and ethical values and interpersonal skills among the
students.
• To impart quality education with social awareness and train them in the
development of community.

2
TEACHING AND EXAMINATIONS SCHEME

LABORATORY NAME OBJECT ORIENTED

PROGRAMMING THROUGH JAVA

LAB

LABORATORY CODE 2018507A

TEACHING Periods per Week 04


SCHEME

EXAMINATIO Hours of Exam. 03


N SCHEME
Practic Internal(A) 07
al
(ESE) External(B) 18

Total Marks (A+B) 25

Pass Marks in the Subject 10

Credits 02

3
Course Outcomes
Upon completion of this course, the students can able to acquire the
following Practical Skills:
Course Outcomes: Blooms
Taxonomy Level

CO307. 1 Describe the basic syntax and semantics of the Ap


Java language and programming environment.

CO307. 2 Explain the concepts of classes and objects Ap

CO307. 3 Implement decisions using if statements. Ap

CO307. 4 Do program loops with while, for and do statements Ap

CO307. 5 Illustrate the concepts of exception handling, Ap


multithreading and file handling.

CO307.6 Develop small software applications using JAVA Ap


Programing

Bloom’s Taxonomy Level


1 -Remembering 2-Understanding 3- Applying 4- Analyzing 5- Evaluating 6-

Course PO1 PO2 PO3 PO4 PO5 PO6 PO7 PSO1 PSO2
Outcome
CO307.1 3 - - - - - 1 3 2

CO307.2 3 1 1 1 1 1 2 3 2

CO307.3 3 1 1 2 1 1 2 3 2

CO307.4 3 1 1 2 2 1 1 3 2

CO307.5 3 1 1 1 1 1 2 3 2

CO307.6 3 2 2 2 2 2 2 3 2

4
Unit 1 – Write a program using Java built-in functions using all data types.
The program reads 3 string variables and then performs the following operations on them.
1. Find the length of the string using length () function.
2. Convert the string into uppercase and lowercase using toUpperCase () and
toLowerCase () functions respectively.
3. Concatenate two strings using concat () function.

Flowchart

Program:
package JavaExamples;
public class StringDemo
{
5
public static void main(String[] args)
{
int x, y;
String S = "Elephant";
String S1 = "Tiger";
String S3 = "Hello";
x = S.length();
y = S1.length();
System.out.println("Length of S=" + x);
System.out.println("Length of S1=" + y);
System.out.println(S.toUpperCase());
System.out.println(S.toLowerCase());
String S2 = S + S1;
System.out.println("S2=" + S2);
String S4 = S3.concat(S1);
System.out.println(S4);
}
}

Output:
Length of S=8
Length of S1=5
ELEPHANT
elephant
S2 = ElephantTiger
HelloTiger

Result: Thus, the program executed successfully.

6
Unit 2 – Write a program using conditional statements and loop statements.

Conditional statements: if-else statement


Procedure:

public class ifelseExample


{
public static void main(String[] args)
{
int age = 20;
if(age > 18)
{
System.out.println("Eligible for Driving license ");
}
else
{
System.out.println("Not Eligible for Driving license "); }
}
}

Output: Eligible for Driving License

7
Loop Statements: For loop
public class ForExample
{
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}

Output:
1
2
3
4
5
6
7
8
9
10

Loop Statements: while Loop


public class WhileExample
{
public static void main(String[] args) {
int i=0;
while(i < 5)
{
System.out.println(i);
i++;
}
}
}
Output:
0
1
2
3
4

8
Loop Statements: do while Loop

public class DoWhileExample


{
public static void main(String[] args) {
int choice = 0;
Scanner keypad = new Scanner(system.in); do {
System.out.println("--- Menu ---");
System.out.println("1.Task1");
System.out.println("2.Task2");
System.out.println("3.QUIT");
System.out.println("Enter choice:");
choice = keypad.nextInt();
if(choice == 1)
System.out.println("Perform Task1 for user.");
if(choice == 2)
System.out.println("Perform Task2 for user."); }
while(choice == 1 || choice == 2);
}
}

Output:

1.Task1
2.Task2
3.QUIT

Enter choice: 1
Perform Task1 for user.

— Menu —
1.Task1
2.Task2
3.QUIT

Enter choice: 2
Perform Task2 for user.

9
— Menu —
1.Task1
2.Task2
3.QUIT

Enter choice: 3
Quit

Result: Thus, the program executed successfully.

10
Unit 3 – Write a program to read data from keyboard.
import java.io.*;
class ReadDataDemo
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Output:
Enter your name
Amit
Welcome Amit

Result: Thus, the program executed successfully.

11
Unit 4 – Write a program to create class and objects.

Program:
void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}
class Main {
public static void main(String[] args) {
Lamp led = new Lamp();
Lamp halogen = new Lamp();
led.turnOn();
halogen.turnOff();
}
}

Output:

Light on? true


Light on? False

Result: Thus, the program executed successfully.

12
Unit 5 – Write programs using constructors. Program:

class Main {
private String name;
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Meena";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}

Output:

Constructor Called:
The name is Meena

Result: Thus, the program executed successfully.

13
Unit 6 – Write a program to illustrate usage of command line arguments.

To compile and run a java program in command prompt follow the steps written below. 1. Save
your program in a file with a .java extension
2. open the command prompt and go to the directory where your file is saved. 3. Run
the command – javac filename.java
4. After the compilation run the command – java filename
5. Make sure the Java path is set correctly.

Program:

a. Factorial of a number using command-line arguments class


Example1{
public static void main(String[] args){
int a , b = 1;
int n = Integer.parseInt(args[0]);
for(a = 1; a<= n ; a++)
{
b = b*a;
}
System.out.println("factorial is" +b);
}
}
Output: factorial is120

b. Sum of two numbers using command-line arguments class


Example2{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("The sum is" +sum);
}
}

Output: The sum is 8

14
c. Fibonacci Series program using command-line arguments

class Example3{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
int t1 = 0;
int t2 = 1;
for(int i = 1; i <=n; i++){
System.out.println(t1);
int sum = t1+t2;
t1 = t2;
t2 = sum;
}
}
}

Output:
0
1
1
2
3
5
8
13
21
34

Result: Thus, the program executed successfully.

15
Unit 7 – Write programs using the concept of overloading methods.

Programs:

a. Overloading by changing the number of parameters class


MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}

Output:
Arguments: 1
Arguments: 1 and 4

b. Method Overloading by changing the data type of parameters

class MethodOverloading {
private static void display(int a){
System.out.println("Got Integer data.");
}
private static void display(String a){
System.out.println("Got String object.");
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}

16
Output:
Got Integer data.
Got String object.

c. Real world Example of overloading methods

class HelperService {
private String formatNumber(int value) {
return String.format("%d", value);
}
private String formatNumber(double value) {
return String.format("%.3f", value);
}
private String formatNumber(String value) {
return String.format("%.2f", Double.parseDouble(value)); }
public static void main(String[] args) {
HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}

Output:

500
89.993
550.00

Result: Thus, the program executed successfully.

17
Unit 8 – Exercise on inheritance.
Program:
package inheritancePractice;
public class P
{
// Declare an instance variable.
int a = 30;
}
public class Q extends P
{
// Declare an instance variable whose name is same as that of the superclass instance variable
name.
int a = 50;
}
public class Test extends Q {
public static void main(String[] args)
{
// Create an object of class Q and call the instance variable using reference variable q. Q q =
new Q();
System.out.println(" Value of a: " +q.a); // 'a' of Q is called.
// Declare superclass reference is equal to the child class object.
P p = new Q();
System.out.println("Value of a: " +p.a); // 'a' of P is called.
}
}

Output:
Value of a: 50
Value of a: 30

Result: Thus, the program executed successfully.

18
Unit 9 – Write a program using the concept of method overriding.

Program:

package inheritancePractice;
public class Baseclass
{
int x = 20;
// Overridden method.
void msg()
{
System.out.println("Base class method");
}
}
public class Childclass extends Baseclass
{
int x = 50;
int y = 100;
// Overriding method.
void msg()
{
System.out.println("Child class first method");
}
void msg2()
{
System.out.println("Child class second method");
}
}
public class MyTest extends Childclass {
public static void main(String[] args)
{
Childclass obj = new Childclass();
System.out.println("Value of x: " +obj.x); // x of class Childclass is called.
obj.msg(); // msg() of Childclass is called.

19
obj.msg2(); // msg2() of Childclass is called.
Baseclass obj2 = new Childclass();
System.out.println("Value of x: " +obj2.x); // x of Baseclass is called. // obj2.msg2(); //
Error because the method msg2() does not exist in Baseclass. }
}

Output:

Value of x: 50
Child class first method
Child class second method
Value of x: 20
Child class first method

Result: Thus, the program executed successfully.

20
Unit 10 – Exercise on Importing packages.
Program:
package employee;
public class Emp{
String name,empid, category;
int bpay;
double hra,da,npay,pf,grosspay,incometax,allowance;
public Emp(String n, String id, String c, int b)

{
name = n;
empid = id;
category = c;
bpay = b;
}
public void call()
{
da = bpay*0.05;
hra = bpay*0.09;
pf = bpay*0.11;
allowance = bpay*0.10;
grosspay = bpay+da+hra+allowance-pf;
incometax = 0.75*grosspay;
npay = grosspay- incometax;
}
public void display()
{
System.out.println("/n/n Employee Details");
System.out.println("/n/n Name:"+name);
System.out.println("/n/n Empid:"+empid);
System.out.println("/n/n Category:"+category);
System.out.println("/n/n bpay:"+bpay);

21
System.out.println("/n/n da:"+da);
System.out.println("/n/n hra:"+hra);
System.out.println("/n/n pf:"+pf);
System.out.println("/n/n all:"+allowance);
System.out.println("/n/n gs:"+grosspay);
System.out.println("/n/n Incometax:"+incometax);
System.out.println("/n/n npay:"+npay);

}
}

Output:
Employee Details
Name: ANU
Empid: 23
Category: Female
bpay: 12000
da: 600.0
hra: 1080.0
pf: 1320.0
allowance: 1200.0
grosspay: 13560.0
Incometax: 10170.0
npay: 3390 */

Result: Thus, the program executed successfully.

22
Unit 11 – Exercise on Interface.

Program:

interface Polygon {
void getArea(int length, int breadth);
}
// implement the Polygon interface
class Rectangle implements Polygon {
// implementation of abstract method
public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth)); }

}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}

Output:
The area of the rectangle is 30

Result: Thus, the program executed successfully.

23
Unit 12 – Exercise on exception handling.

Program:
a. Java try and catch
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old."); }

else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}

Output:
Something went wrong.

b. The Finally Keyword


public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}

24
}
}

Output:
Something went wrong.
The 'try catch' is finished.

c. The throw keyword


public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old."); }
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}

Output
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least
18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

Result: Thus, the program executed successfully.

25
Unit 13 – Exercise on multithreading and thread priorities.

Program:
public class MyThread extends Thread
{
public void run ()
{
for (int i = 0; i <= 50; i++)
{
System.out.println ("Run: " + i);
}
}
public static void main (String[]args)
{
MyThread mt = new MyThread ();
mt.run ();
for (int i = 0; i <= 50; i++)
{
System.out.println ("Main: " + i);
}
}
}

Output:
Main: 47
Main: 48
Main: 49
Main: 50

Result: Thus, the program executed successfully.

26
Unit 14 – Exercise on database connectivity using JDBC. Program:

import java.sql.*;
public class FirstExample {
static final String DB_URL = "jdbc:mysql://localhost/ShapeAI";
static final String USER = "scott";
static final String PASS = "tiger";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
public static void main(String[] args) {
// Open a connection
try(Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

27
Output:
Connecting to the database...
Creating statements...
ID: 100, Age: 23, First: Raj, Last: Sharma
ID: 101, Age: 24, First: Bala, Last: Singh
ID: 102, Age: 25, First: Anu, Last: Priya
ID: 103, Age: 26, First: Riya, Last: Khan

Result: Thus, the program executed successfully.

28

You might also like