Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 89

Second year: Computer Engineering

[Skill Lab : OOPs with Java]

Experiment

Name :

Experiment : Use of Scanner Class , BufferedReader and wrapper class

Title of Experiment : Use of Scanner Class , BufferedReader and wrapper class

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

1|Page
Practical 1
Program 1 :Using Scanner Class
package Scanner_Pack;
import java.util.*;
public class Scanner_Class_2 {

public static void main(String[] args) { String


s = "Hello, This is Watumull."; //Create
scanner Object and pass string in it Scanner
scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " +
scan.hasNext()); //Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int age = in.nextInt();
System.out.println("Age: " + age);
System.out.print("Enter your ID: ");
int ID = in.nextInt();
System.out.println("Age: " + ID);
System.out.print("Enter your salary: ");
double Salary = in.nextDouble();
System.out.println("Salary: " + Salary);
in.close();
}
}

Program 2 : Using BufferedReader Class


package BufferedReader_Package;
import java.io.*;
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStreamReader;

public class BufferedReader_Class_2 {

2|Page
public static void main(String[] args) throws Exception
{ BufferedReader reader =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your name: ");
String name = reader.readLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(reader.readLine());
System.out.println("Enter your Id: ");
int id = Integer.parseInt(reader.readLine());
System.out.println("Enter your Salary: ");
float Salary= Float.parseFloat(reader.readLine());
//long l= Long.parseLong(reader.readLine());
//double d= Double.parseDouble(reader.readLine());
//String s=reader.readLine();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("ID: " + id);
System.out.println("Salary: " + Salary);
}
}

Program 3 : Using Wrapper Class


package Wrapper_Pack;

public class Wrapper_Class {

public static void main(String[] args) {


//Java Program to convert all primitives into
its //corresponding wrapper objects and vice-versa

byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
3|Page
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);

//Unboxing: Converting Objects to


Primitives byte bytevalue=byteobj; short
shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);

}
}

Conclusion :
Studied use of scanner class and Buffered reader class

Studied wrapper class and its difference with primitive datatype.

4|Page
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Control Statements

Title of Experiment : Use of if..else , switch..case , for loop , for each loop , while loop and

do..while loop.

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

5|Page
Practical 2
Programs on if , if else
Program 1 : Find the Largest of three numbers using for loop

package if_else;

import java.util.*;

public class greaterThree {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the First


Number :"); // Numerical input
int Num1 = myObj.nextInt();
System.out.println("Enter the Second Number :");
// Numerical input
int Num2 = myObj.nextInt();
System.out.println("Enter the Third
Number :"); // Numerical input
int Num3 = myObj.nextInt();
if (Num1>Num2)
{
if (Num1 > Num3)
{
System.out.println("First Number is Larger than other
Two Numbers :" + Num1);
}
else
{
System.out.println("Third Number is Larger than other
Two Numbers :" + Num3);
}
}
else if (Num2 > Num3)
{
System.out.println("Second Number is Larger than
other Two Numbers :" + Num2);
}
else
{

6|Page
System.out.println("Third Number is Larger than other
Two Numbers :" + Num3);
}

myObj.close();

Program 2 : To Find whether given year is leap year or not.

package if_else;

import java.util.*;

public class Leap_Year {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Year to check whether Leap


Year or Not :");
// Numerical input
int Year = myObj.nextInt();
if (Year%4==0 && Year%100 !=0 || Year % 400 ==0)
{
System.out.println(" Leap Year :" + Year);
}
else
{
System.out.println(" Not a Leap Year :" + Year);
}

Conclusion: Studied use of if else condition loop.

7|Page
Programs on switch case
Program :Using int type data in switch case
package SwitchCase;

public class ArithmeticSwitch {

public static void main(String[] args) {


/ TODO Auto-generated method stub
for (int i = 0; i < 12; i++)
switch (i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than
5"); break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}

Program 2 :Using char type data in switch case

package SwitchCase;

public class CharSwitch {

public static void main(String[] args) {


/ TODO Auto-generated method
stub char operator = '*';
int num1 = 5,
num2 = 8, result;

8|Page
switch (operator)
{ // "char" selector
case '+': // "char" value
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 !=0)
{
result = num1 / num2;
}
else
System.out.println("Divide by zero Error");
break;
default:
System.out.println("Unknown operator");
}
}
}

Program 3 :Using enum type data in switch case

package SwitchCase;

public class EnumSwitch {


enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY ;}
public static void main(String[] args) {
/ TODO Auto-generated method stub

Day day =Day.FRIDAY;

switch (day) {
case SUNDAY:
System.out.println( " Day is : Sunday ");
break;
case MONDAY:
System.out.println( " Day is : Monday ");
break;
case TUESDAY:

9|Page
System.out.println( " Day is : Tuesday
"); break;
case WEDNESDAY:
System.out.println( " Day is : Wednesday
"); break;
default:
System.out.println( " Day is not in the list ");
break;
}

}
}

Program :Using string type data in switch case

package SwitchCase;

public class StringSwitch {

public static void main(String[] args) {


/ TODO Auto-generated method
stub String str = "two";
switch (str)
{ case
"one":
System.out.println("one");
break;
case "two":
System.out.println("two");
break;
case "three":
System.out.println("three");
break;
default:
System.out.println("no
match"); break;
}

Conclusion: Studied use of switch case .

10 | P a g e
Programs on while Loop
Program1 : To find count of Digits and Sum of Digits of a given Number

package whileLoop;

import java.util.Scanner;

public class sum_count_Digit {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to


find count and sum of digits:");
// Numerical input
int Num = myObj.nextInt();
int sum=0,count=0,digit;
while (Num > 0)
{
digit=Num%10;
sum=sum+digit;
count++;
Num=Num/10;
}

System.out.println("Sum of Digit : " + sum);


System.out.println("Count of Digit : " + count);
myObj.close();

11 | P a g e
Program 2 : To find factorial of a given Number

package whileLoop;

import java.util.*;

public class Factorial {

public static void main(String[] args)


{ long fact=1;
/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to find its


Factorial:"); // Numerical input
int Num = myObj.nextInt();
int i=1;
while (i<=Num)
{
fact=fact*i;
i++;
}

System.out.println("Factorial: " +
fact); myObj.close();
}
}

12 | P a g e
Program 3 : To find a given Number is Armstrong Number or Not.

package whileLoop;

import java.util.Scanner;

import java.lang.Math;

public class armstrongNumber {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to check Armstrong


Number:");

/ Numerical input

int Num = myObj.nextInt();

int temp,count=0;

temp=Num;

while (Num > 0)

Num=Num/10;

count++;

int digit,sum=0;

13 | P a g e
Num=temp;

while (Num > 0)

digit=Num % 10;

sum= sum + (int)Math.pow(digit,count);

Num=Num/10;

if (sum==temp)

System.out.println(temp +" is an Armstrong Number " );

else

System.out.println("Not an Armstrong Number " + temp);

myObj.close();

Conclusion: Studied use of while loop.

14 | P a g e
Programs using do while loop
Program 1 : Find the multiplication table of a given number

package doWhile;

import java.util.Scanner;

public class multiplyTable {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to find its


Multiplication Table:");
// Numerical input
int Num = myObj.nextInt();
int i=1;
do
//for (int i=1 ; i <= 10 ; i++)
{
System.out.println(Num + " * " + i + " = " +
Num*i); i++;
} while(i<=10);

myObj.close();

Program 2 : Find a given number is palindrome number or not

package doWhile;

import java.util.Scanner;

public class Palindrome {

public static void main(String[] args) {


// TODO Auto-generated method stub

15 | P a g e
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to check Palindrome


Number:");
// Numerical input
int Num = myObj.nextInt();
int temp;
temp=Num;
int digit,reverse=0;
do
{
digit=Num % 10;
reverse= reverse * 10 + digit;
Num=Num/10;
}while (Num > 0);
if (reverse==temp)
{
System.out.println(temp +" is an Palindrome Number " );
}
else
{
System.out.println("Not an Palindrome Number " + temp);
}
myObj.close();

Conclusion: Studied use of do while loop.

16 | P a g e
Program on for loop
Program 1 : Sum of N Natural Numbers using for loop

package forLoop;

import java.util.Scanner;

public class sumNNatural {

public static void main(String[] args) {


/ TODO Auto-generated method stub
/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number upto which


you want sum of natural numbers:");
// Numerical input
int Num = myObj.nextInt();
int sum=0;
for (int i=1 ; i <= Num ; i++)
{
sum = sum + i;

}
System.out.println( "Sum of first " + Num + "
Natural Numbers is : " + sum );
myObj.close();
}
}

Program 2 : Factorial of a Numbers using for loop

package forLoop;

import java.util.Scanner;

public class factorial {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to find its Factorial:");

17 | P a g e
// Numerical input
int Num = myObj.nextInt();
int fact = 1;
for (int i=1 ; i <= Num ; i++)
{
fact=fact*i;

System.out.println("Factorial: " +
fact); myObj.close();

Program 3 : Fibonacci series using for loop

package forLoop;

import java.util.Scanner;

public class fibonacci {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number of elements you want in


fibonacci series:");
// Numerical input
int Num = myObj.nextInt();
int term1=0;
int term2=1;
System.out.print("Fibonacci series is : " + term1 + "," +
term2);
int nextTerm ;
for (int i=3 ; i <= Num ; i++)
{
nextTerm = term1+term2;
System.out.print("," + nextTerm);
term1=term2;
term2=nextTerm;
}
myObj.close();

18 | P a g e
}
}

Program 4 : To check whether given number is prime or not using for loop

package forLoop;

import java.util.Scanner;

public class prime {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Number to check prime or


not:"); // Numerical input
int Num = myObj.nextInt();
boolean primeFlag=true;
for (int i=2 ; i < Num ; i++)
{
if ( Num % i==0)
{
primeFlag=false;
break;
}

if (primeFlag==false)
{
System.out.println(Num + " is Not Prime " );
}
else
{
System.out.println(Num + " is Prime " );
}

myObj.close();

19 | P a g e
Program 5 : To find prime numbers in a given range using for loop

package forLoop;

import java.util.Scanner;

public class primeRange {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Range Start Number to check


prime or not:");

int Num1 = myObj.nextInt(); // Numerical input


System.out.println("Enter the Range End Number to check
prime or not:");
int Num2 = myObj.nextInt();
int Num;
if (Num1 == 1)
{
Num1=2;
}
for (Num = Num1; Num <= Num2 ; Num++)
{
boolean primeFlag=true;
for (int i=2 ; i < Num ; i++)
{
if ( Num % i==0)
{
primeFlag=false;
break;
}
}

/*
if (primeFlag==false)
{
System.out.println(Num + " is Not Prime " );
}
else
{
System.out.println(Num + " is Prime " );
}
*/

20 | P a g e
if (primeFlag == true)
{
System.out.println(Num);
}
myObj.close();
}
}
}

Conclusion: Studied use of for loop.

21 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Classes Objects &Constructors

Title of Experiment : Program on class ,objects ,Constructor and Parameterized constructor

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

22 | P a g e
Practical 3
Program on class and objects
package AreaPerimeter;

import java.util.*;

class RectangleNew
{
float length, breadth;
void setValue(float l, float b)
{
length = l;
breadth = b;
}
/ get area of rectangle
float findArea()
{
return (length * breadth);
}
/ Method to calculate the Perimeter of
Rectangle float findPerimeter()
{
return (2 * (length + breadth));
}
}

public class area_perimeterClasswithScanner {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);

System.out.println("Enter the Length of Rectangle:");


float Num1 = myObj.nextFloat(); // Numerical input
System.out.println("Enter the Breadth of
Rectangle:"); float Num2 = myObj.nextFloat();
/ Object of Rectangle class is created RectangleNew
objNew = new RectangleNew(); objNew.setValue(Num1,
Num2); System.out.println("Length = " +
objNew.length); System.out.println("Breadth = " +
objNew.breadth); System.out.println("Area of
rectangle: " +
objNew.findArea());

23 | P a g e
System.out.println("Perimeter of rectangle is : "+
objNew.findPerimeter());
myObj.close();

}
}

Conclusion: Studied classes and objects.

Programs on Constructor
Program 1 : Enter and print student data using parameterized constructor.
package studentDataUsingConstructor; //parameterized
constructor import java.io.*;

class StudentDetail
{
int roll,age;
String Name;
StudentDetail(int p, String q, int r)
{
roll = p;
Name=q;
age=r;
}
void ShowData()
{
System.out.println("Roll Number : "+roll);
System.out.println("Students Name : "+Name);
System.out.println("Hindi Marks : "+age);

}
}

public class StudentDataConstructor {

public static void main(String[] args) throws Exception {


/ TODO Auto-generated method stub
BufferedReader Br =new BufferedReader(new
InputStreamReader(System.in));
String read,Name;
int RollNumber,Age;
System.out.println("Enter Class Roll Number : ");
read=Br.readLine();

24 | P a g e
RollNumber = Integer.parseInt(read);
System.out.println("Enter Name of the Student : ");
Name=Br.readLine();
System.out.println("Enter Age of the student : ");
read=Br.readLine();
Age=Integer.parseInt(read);
StudentDetail std= new StudentDetail(RollNumber,Name,Age);
System.out.println("Details of the Student Entered are :");
std.ShowData();
Br.close();

Program 2 : Program to calculate area and perimeter of rectangle using


parameterized constructor.
package AreaPerimeter;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

//Or

//import java.io. * ;

class RectangleShape

int perimeter, area, length,

breadth; // Parameterized constructor

//Parameterized constructor is a constructor with specified


number of parameters.

RectangleShape(int l, int b)

length = l;

25 | P a g e
breadth = b;

void getArea()

area = length * breadth;

System.out.println("Area of rectangle : " + area);

void getPerimeter()

perimeter = 2*(length + breadth);

System.out.println("Perimeter of rectangle : " + perimeter);

public class AreaUsingConstructor {

public static void main(String[] args) throws Exception {

BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

int length, breadth;

System.out.println("Please enter length : ");

String strLength = br.readLine(); length =

Integer.parseInt(strLength);

System.out.println("Please enter breadth : ");

String strBreadth = br.readLine(); breadth =

Integer.parseInt(strBreadth);

26 | P a g e
RectangleShape rs = new RectangleShape(length, breadth);

rs.getArea();

rs.getPerimeter();

br.close();

Conclusion:
Studied use of constructor.

Studied use of parameterized constructor.

27 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name :

Experiment : Inheritance

Title of Experiment : Programs on Single , Multiple and Hierarchical Inheritance

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

28 | P a g e
Practical 4
Inheritance

Program 1:Single Inheritance

class A {

void msgA(){

System.out.println(“I am in Class A");

class B extends A {

void msgB(){

System.out.println(“I am in Class B");

Public Static void main(String args[]){

A objA=new A();

objA.msgA();

B objB=new B();

objB.msgA();

objB.msgB();

Program 2:Multilevel Inheritance

class A{

void msgA(){

System.out.println("Hello");

29 | P a g e
}

class B extends A {

void msgB(){

System.out.println("Welcome");

class C extends B{

void msgC(){

System.out.println(“Students");

Public Static void main(String args[]){

A objA=new A();

objA.msgA();

B objB=new B();

objB.msgA();

objB.msgB();

C objC=new C();

objC.msgA();

objB.msgB();

objC.msgC();

Program 3:Hierarchical Inheritance

class A{

void msgA(){

30 | P a g e
System.out.println("Hello");

class B extends A {

void msgB(){

System.out.println("Welcome");

class C extends A{

void msgC(){

System.out.println(“Students");

Public Static void main(String args[]){

A objA=new A();

objA.msgA();

B objB=new B();

objB.msgA();

objB.msgB();

C objC=new C();

objC.msgA();

objC.msgC();

Conclusion : Studied three types of Inheritances


31 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Encapsulation(OOPs Concepts)

Title of Experiment : Program on Encapsulation in Java

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

32 | P a g e
Practical 5
Encapsulation
Aim : To implement Encapsulation for Employee data

package TestEncapsulation;

class Employee {
private String name;
private String idNum;
private int age;

public String getName() { //getter


return name;
}
public int getAge() { //getter
return age;
}
public String getIdNum() { //getter
return idNum;
}
public void setName(String newName) {
//setter name = newName;
}
public void setAge( int newAge) {
//setter age = newAge;
}
public void setIdNum( String newId) {
//setter idNum = newId;
}
}

public class RunEncapsulation {


public static void main(String[] args) {
Employee emp = new Employee(); //instance of class or object
emp.setName("James");
emp.setAge(20);
emp.setIdNum("A12343");
System.out.println("Name : " + emp.getName() + "\nAge : "
+emp.getAge()+ "\nID : " +emp.getIdNum());
}
}

Conclusion : Studied encapsulation.

33 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Polymorphism

Title of Experiment : Programs on Method Overloading ,Method Overriding , Run time and
Compile time Polymorphism

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

34 | P a g e
Practical 6
Polymorphism
Program 1:

//Method Overloading and Compile Time Polymorphism

package CompilePolymorphism;

public class Addition {


void sum(int a, int b)
{
int c = a+b;
System.out.println("Addition of two numbers :" +
c); }
void sum(int a, int b, int e)
{
int c = a+b+e;
System.out.println("Addition of three numbers :" +c);
}
public static void main(String[] args)
{
Addition obj = new Addition();
obj.sum ( 30,90);
obj.sum(45, 80, 22);
}
}

Program 2: RuntimePolymorphism using upcasting

package RuntimePolymorphismTest;

class Hillstations{ hism


void location(){
System.out.print("Location :");
}
void famousfor(){
System.out.print("Famous for:");
}
}

class Manali extends Hillstations {


void location(){
System.out.println("Manali is in Himachal Pradesh");
}

35 | P a g e
void famousfor(){
System.out.println("It is Famous for Hadimba Temple and
adventure sports");
}
}

class Mussoorie extends Hillstations {


void location(){
System.out.println("Mussoorie is in Uttarakhand");
}
void famousfor(){
System.out.println("It is Famous for education institutions");
}
}

class Gulmarg extends Hillstations {


void location(){
System.out.println("Gulmarg is in J&amp;K");
}
void famousfor(){
System.out.println("It is Famous for skiing");
}
}

public class RuntimePolymorphism {

public static void main(String[] args) {


/ TODO Auto-generated method stub
Hillstations A = new Hillstations();

Hillstations M = new Manali(); //upcasting


Hillstations Mu = new Mussoorie(); //upcasting

Hillstations G = new Gulmarg(); //upcasting

A.location();
M.location();
A.famousfor();
M.famousfor();

A.location();
Mu.location();
A.famousfor();
Mu.famousfor();

36 | P a g e
A.location();
G.location();
A.famousfor();
G.famousfor();
}
}

Program 3 : Runtime polymorphism using upcasting and @override annotation

package RuntimePolymorphismTest;

//method overriding in java Base Class using


@override class Parent1 {
void show()
{
System.out.println("Parent's show()");
}
}

//Inherited class
class Child1 extends Parent1 {
/ This method overrides show() of Parent
@Override
void show()
{
System.out.println("Child's show()");
}
}

public class RuntimePolymorphism2 {

public static void main(String[] args) {


/ If a Parent type reference refers to a Parent object,
then Parent's show method is called
Parent1 obj1 = new
Parent1(); obj1.show();

/ If a Parent type reference refers to a Child object


Child's show() is called. This is called RUN TIME POLYMORPHISM.
Parent1 obj2 = new
Child1();//upcasting obj2.show();

}
}
Conclusion: Studied concept of Polymorphism i.e. run time and compile time polymorphism.

37 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Assertion &Abstraction

Title of Experiment : Programs on Assert class , abstract class and interface

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

38 | P a g e
Practical 7
Assertion and Abstration
Aim : To use Assertion in Java
Step 1 : Type below Program in Notepad

import java.util.Scanner;

class AssertionExample{
public static void main( String args[] ){

Scanner scanner = new Scanner( System.in );


System.out.print("Enter ur age ");

int value = scanner.nextInt();


assert value >=18 : " Voter is Not Eligible";
//assert value >=18;

System.out.println(value + " Voter is Eligible");


}
}

Step 2 : Save Program with AssertionExample.java in the same folder used by java compiler
or JDK. Select type of file as all files.

Step 3 : Open Command prompt.(path for java is already set by installation).

Step 4 : Write command : javac AssertionExample.java

if everything is right JVM will create AssertionExample.class file.

Step 5 : Run Command: java –ea AssertionExample

Output 1 :

Enter ur age :35

35 Voter is eligible

Output 2 :

Enter ur age :15

39 | P a g e
Aim : To do abstraction using 1) abstract class 2) interface

1) Using abstract class

Example 1 :
package AbstractClassTest1;

abstract class Vehicle {


int no_of_tyres;
abstract void start();
}

class Car extends Vehicle{


void start() {
System.out.println("Car Starts with Key");
}
}

class Scooter extends Vehicle{


void start() {
System.out.println("Scooter Starts with Switch or Kick");
}
}

public class AbstractClassVehicle {

public static void main(String[] args) {


/ TODO Auto-generated method
stub Car C = new Car();
Scooter S = new Scooter();
C.start();
S.start();
}
}

Example 2 :
package AbstractClassTest1;

abstract class Bank {

40 | P a g e
int Rate; //data abstraction
abstract int getInterestRate();//control abstraction
}

//concrete class
class ICICI extends Bank {
int Rate=7;
int getInterestRate(){ //method overriding
System.out.println("ICICI rate 7%");
return 7;
}
}

class HDFC extends Bank{


int Rate=6;
int getInterestRate(){
System.out.println("HDFC rate 6%");
return 6;
}
}

public class AbstractClassBank {

public static void main(String[] args) {


// TODO Auto-generated method stub
ICICI I = new ICICI(); // concrete class object
System.out.println("ICICI rate interest is :"
+I.getInterestRate());
System.out.println("ICICI rate interest is :" +I.Rate);
HDFC H = new HDFC();
System.out.println("HDFC rate interest is :"
+H.getInterestRate());
System.out.println("HDFC rate interest is :" +H.Rate);
}
}

2) Using interface.
package AbstractClassTest1;
interface I1{
public void show();
}

class Test implements I1{

41 | P a g e
public void show() {
System.out.println ("Interface test");
}
}

public class InterfaceTest {

public static void main(String[] args) {


/ TODO Auto-generated method
stub Test T = new Test();
T.show();
}
}

3) Multiple inheritance using interfaces

package AbstractClassTest1;

interface M1{
public void show1() ;
}

interface M2{
public void show2() ;
}

class MultiTest implements M1,M2 {


public void show1() {
System.out.println ("Interface M1 test");
}
public void show2() {
System.out.println ("Interface M2
test"); }
}

public class MultipleInheritanceTest {

public static void main(String[] args) {


/ TODO Auto-generated method stub
MultiTest MT = new MultiTest();

42 | P a g e
MT.show1();
MT.show2();
}
}

Conclusion :
Studied use of assert class
Studied use of abstract class
Studied use of interface.

43 | P a g e
Second year: Computer Engineering

[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Arrays

Title of Experiment : Programs on Anonymous Arrays, Sorting of 1D Arrays, 2D Array Matrix


Transpose & Matrix Addition & Multiplication

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

44 | P a g e
Practical 8
Arrays
Program 1: Write a program to calculate total of 1D array elements
using Anonymous Array
//Anonymous Array 1D
package ArraysPackage;

public class AnonymousArray1 {

public static void main(String[] args)


{ //anonymous int array : new int[] { 1, 2, 3,
4};
//anonymous String array : new String[] {"one", "two", "three"};
//anonymous char array : new char[] {'a', 'b', 'c');

//calling method with anonymous array argument


System.out.println("first total of numbers: " + sum(new
int[]{1, 2, 3, 4}));
System.out.println("second total of numbers: " +
sum(new int[]{1, 2, 3, 4, 5, 6}));
sum2(new int[]{1, 2, 3, 4});
sum2(new int[]{1, 2, 3, 4, 5, 6});
}

//method which takes an array as argument


public static int sum(int[] numbers){
int total = 0;
for(int i: numbers){
total = total + i;
}
return total;
}

public static void sum2(int[] a)


{
int total = 0;

/ using for-each
loop for (int i : a)
total = total + i;

System.out.println("The sum is:" + total);


}
}

45 | P a g e
Program 2: Write a program to calculate total of 2D array elements
using Anonymous Array
//Anonymous Array 2D
package ArraysPackage;

public class AnonymousArray2D {

public static void main(String[] args) {


//anonymous int array : new int[][] {{ 1, 2, 3,
4} , //{2,5,8,4},{3,6,9,4}};
//anonymous String new String[][] { {"Java", "JSP",
"Servlet", //"Spring"}, {"MySQL", "Oracle"} };
//anonymous char array : new char[] {{'a', 'b', 'c'},{'s','e','t'}};
//calling method with anonymous array argument
System.out.println("first total of numbers: " + sum(new int[][] {{ 10,
20, 30},{20,50},{30,60,90}}));
sum2(new int[][] {{10,20,30},
{40,50}}); }

//method which takes an array as argument


public static int sum(int[][] numbers){
int total = 0;
for(int II[]:numbers){
for(int I:II)
total = total + I;
}
return total;
}

public static void sum2(int[][] numbers)


{ int total = 0;
for(int i=0;i < numbers.length;i++){
for(int j=0;j < numbers[i].length;j++) {
total = total + numbers[i][j];
}
}
System.out.println("total of numbers is " + total);
}
}

Program 3 : Find the element with maximum value and minimum value from
the 1D array.

package ArraysPackage;

46 | P a g e
public class ArrayMaxMin {

public static void main(String[] args) {


int[] arr1 = {12, 23, 3, 45, 65, 2,32};
int max=arr1[0];
int min=arr1[0];
for (int i=1;i<arr1.length;i++) {
if (arr1[i]>max) {
max=arr1[i];
}
if (arr1[i]<min){
min=arr1[i];
}
}
System.out.println("Max. of Array is "+ max + " & Min of
Array is " + min);
}

Program 4A : Arrange elements in ascending array using sorting


method and for loop.Use scanner class for input elements in array.

package ArraysPackage;
import java.util.Scanner;
public class ArrayWithScanner {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);


System.out.println("Enter the Number to element is Array:");
int Num = myObj.nextInt();// Numerical input
int[] arrS = new int[Num];
System.out.println("Enter the Array elements :");
//sorting logic
for (int i = 0; i < arrS.length; i++)
{
arrS[i] = myObj.nextInt();
}
int tmp = 0;
for (int i = 0; i < arrS.length; i++)
{
for (int j = i + 1; j < arrS.length; j++)
{

47 | P a g e
if (arrS[i] > arrS[j])
{
tmp = arrS[i];
arrS[i] = arrS[j];
arrS[j] = tmp;
}
}
//prints the sorted element of the array
System.out.println(arrS[i]); }

}
}

Program 4B : Arrange elements in ascending array using arrays.sort()


method.

package ArraysPackage;
import java.util.Arrays;

public class AscendingArray {

public static void main(String[] args) {


//defining an array of integer type
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67,
34}; //invoking sort() method of the Arrays class
Arrays.sort(array);
System.out.println("Elements of array sorted in ascending
order: ");
//prints array using the for loop
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
}

Program 5 : Write a program to find Transpose of Matrix

package ArraysPackage;

public class MatrixTranspose {

public static void main(String[] args) { int[][]


matrixT = new int[4][4]; int[][] matrix4 = { { 3,
2, 1, 7 },

48 | P a g e
{9,11,5,4}, { 6,
0, 13, 17 },
{ 7, 21, 14, 15 } };
System.out.println("Entered Array is");
for (int i = 0; i < matrix4.length; i++) {
for (int j = 0; j < matrix4[i].length; j++) {
System.out.print( matrix4[i][j] + "\t");
}
System.out.println();
}

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


for (int j = 0; j < matrix4[i].length; j++)
{ matrixT[j][i]=matrix4[i][j];
}
}
System.out.println("Transposed Array is");
for (int i = 0; i < matrixT.length; i++) {
for (int j = 0; j < matrixT[i].length; j++) {
System.out.print( matrixT[i][j] + "\t");
}
System.out.println();
}
}
}

Program 6 : Write a program to add 2 Matrices (2D array).

package ArraysPackage;

public class MatrixAddition {

public static void main(String[] args)


{ int[][] C = new int[4][4]; int[]
[] A = { { 6, 2, 7, 9 },
{3,1,12,8},
{5,6,3,7},
{9,4,-4,-5}};
int[][] B = { { 3, 2, 1, 7 },
{9,11,5,4}, { 6,
0, 13, 17 },
{ 7, 21, 14, 15 } };
System.out.println("Entered Array A is");
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[i].length; j++) {
System.out.print( A[i][j] + "\t");

49 | P a g e
}
System.out.println();
}
System.out.println("Entered Array B is");
for (int i = 0; i < B.length; i++) {
for (int j = 0; j < B[i].length; j++) {
System.out.print( B[i][j] + "\t");
}
System.out.println();
}

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


for (int j = 0; j < A.length; j++) {
C[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("Added matrix C is");
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < C[i].length; j++) {
System.out.print( C[i][j] + "\t");
}
System.out.println();
}

Program 7 : Write a program to Multiply 2 Matrices (2D array).

package ArraysPackage;

public class MatrixMultiplication {

public static void main(String[] args)


{ //creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two


matrices int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
50 | P a g e
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}

Program 8A: Write a program to copy a 1D array

package ArraysPackage;

public class CopyArray1 {

public static void main(String[] args) {


/ Input array a[]
int a[] = { 1, 8, 3 };

/ Create an array b[] of same size as


a[] int b[] = new int[a.length];

/ Copying elements of a[] to b[]


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

/ Changing b[] to verify that b[] is different from


a[] b[0]++;

/ Display message only


System.out.println("Contents of a[] ");

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


System.out.print(a[i] + " ");

// Display message only


System.out.println("\n\nContents of b[] ");

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


System.out.print(b[i] + " ");
}
}

51 | P a g e
Program 8B : Write a program to copy a 1D array using
Arrays.copyof() method.

/*
public static int[] copyOf(int[] original, int
newLength) Parameters: Original array
Length of the array to get copied.
*/

package ArraysPackage;

import java.util.Arrays;

public class CopyArray4 {

public static void main(String[] args) {


/ Custom input array
int a[] = { 1, 8, 3 };

/ Create an array b[] of same size as a[] Copy elements of a[] to


b[] int b[] = Arrays.copyOf(a, 3);

/ Change b[] to verify that b[] is different from a[]


b[0]++;

System.out.println("Contents of a[] ");

// Iterating over array. a[]


for (int i = 0; i < a.length; i++)
{ System.out.print(a[i] + " ");
}

System.out.println("\n\nContents of b[] ");


// Iterating over array b[]
for (int i = 0; i < b.length; i++)
{ System.out.print(b[i] + " ");
}

}
}

Conclusion : Studied Arrays class and also to use 1D Array and 2D arrays.

52 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Strings

Title of Experiment : Programs on Strings class, Stringsbuffer & StringBuilder Class

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

53 | P a g e
Practical 9
Strings
Program 1 : To check string is palindrome or not.
package StringPrograms;

public class PalindromeString {

static void isPalindrome(String str1 ) {

StringBuffer s1 = new StringBuffer(str1.toLowerCase());


StringBuffer s2 = new StringBuffer(str1.toLowerCase());
System.out.println(s1);
s1.reverse();
System.out.println(s1);
if (s2.compareTo(s1)==0) {
System.out.println(s2 + " string is Palindrome");
}
else {
System.out.println(s2 + " string is not
Palindrome");
}
}

public static void main(String[] args) {


/ TODO Auto-generated method stub
isPalindrome("Keep");
isPalindrome("Redivider");
}

54 | P a g e
Program 2 : To check string is an anagram or not.

package StringPrograms;
import java.util.Arrays;

public class Anagram {


static void isAnagram(String str1, String str2)
{ String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s",
""); boolean status = true;
if (s1.length() != s2.length()) {
status = false;
}
else {
char[] ArrayS1 =
s1.toLowerCase().toCharArray(); //convert to
lowercase
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
//arrange letters in alphabetical order
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2); //compare
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
}
else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
public static void main(String[] args) {
/ TODO Auto-generated method stub
isAnagram("Listen", "Silent");
isAnagram("Advice", "Advise");
isAnagram("Triangle", "Integral");
}
}

55 | P a g e
Program 3 : To use StringBuffer
package StringPrograms;

public class StringBufferTest {

public static void main(String[] args) {


/ TODO Auto-generated method stub
StringBuffer sb1=new StringBuffer("Hello
"); sb1.append("Java");
//now original string is changed
System.out.println(sb1);//prints Hello Java

StringBuffer sb2=new StringBuffer("Hello ");


sb2.insert(1,"Java");//now original string is changed
System.out.println(sb2);//prints HJavaello

StringBuffer sb3=new StringBuffer("Hello ");


sb3.replace(1,3,"Java");
System.out.println(sb3);//prints HJavalo

StringBuffer sb4=new StringBuffer("Hello ");


sb4.delete(1,3);
System.out.println(sb4);//prints Hlo

StringBuffer sb5=new StringBuffer("Watumull Institute");


sb5.reverse();
System.out.println(sb5);//prints olleH

StringBuffer sb=new StringBuffer();


System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70

56 | P a g e
Program 4 : To use StringBuilder
package StringPrograms;

public class StringBuilderTest {

public static void main(String[] args) {


/ TODO Auto-generated method stub
StringBuilder sb1=new StringBuilder("Hello ");
sb1.append("Java");
//now original string is changed
System.out.println(sb1);//prints Hello Java

StringBuilder sb2=new StringBuilder("Hello ");


sb2.insert(1,"Java");//now original string is changed
System.out.println(sb2);//prints HJavaello

StringBuilder sb3=new StringBuilder("Hello ");


sb3.replace(1,3,"Java");
System.out.println(sb3);//prints HJavalo

StringBuilder sb4=new StringBuilder("Hello ");


sb4.delete(1,3);
System.out.println(sb4);//prints Hlo

StringBuilder sb5=new StringBuilder("Hello");


sb5.reverse();
System.out.println(sb5);//prints olleH

StringBuilder sb=new StringBuilder();


System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

Conclusion :

Studied Basic use of String class ,StringBuffer and String Builder class

57 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : AWT & swing

Title of Experiment : GUI using AWT (Association & Inheritance) & swing (Association & Inheritance).

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

58 | P a g e
Practical 10
AWT/ Swing Practical

Program 1: AWT using Inheritance


import java.awt.*; // importing Java AWT class

/ extending Frame class to our class AWTExample1

public class AWTExample1 extends Frame {

/ initializing using constructor

AWTExample1() {

Button b = new Button("Click Me!!"); // creating a button


b.setBounds(30,100,80,30); // setting button position on screen
add(b); // adding button into frame

setSize(300,300); // frame size 300 width and 300 height

setTitle("This is our basic AWT example");

// setting the title of Frame

setLayout(null); // no layout manager

setVisible(true);

// now frame will be visible, by default it is not visible

public static void main(String args[]) {

AWTExample1 f = new AWTExample1();

/ creating instance of Frame class

59 | P a g e
Program 2 :AWT using Association
import java.awt.*; // importing Java AWT class

class AWTExample2 {

/ class AWTExample2 directly creates instance of Frame class

/ initializing using constructor

AWTExample2() {
Frame f = new Frame(); // creating a Frame

Label l = new Label("Employee id:"); // creating a Label

Button b = new Button("Submit"); // creating a Button

TextField t = new TextField(); // creating a TextField

l.setBounds(20, 80, 80, 30); // setting position of above com


ponents in the frame

t.setBounds(20, 100, 80, 30);

b.setBounds(100, 100, 80, 30);

f.add(b); // adding components into frame

f.add(l);

f.add(t);

/ frame size 300 width and 300

height f.setSize(400,300);

f.setTitle("Employee info"); // setting the title of frame


f.setLayout(null); // no layout

f.setVisible(true); // setting visibility of frame

60 | P a g e
public static void main(String args[]) {

AWTExample2 awt_obj = new AWTExample2();

// creating instance of Frame class

Program 3 :Swing using Inheritance


import javax.swing.*;

public class Simple2 extends JFrame{//inheriting JFrame

JFrame f;

Simple2(){

JButton b=new JButton("click");//create button

b.setBounds(130,100,100, 40);

add(b);//adding button on frame

setSize(400,500);

setLayout(null);

setVisible(true);

public static void main(String[] args) {

new Simple2();

61 | P a g e
Program 4 :Swing by Asociation
import javax.swing.*;

public class Simple {

JFrame f;

Simple(){

f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton

b.setBounds(130,100,100, 40);

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height

f.setLayout(null);//using no layout managers

f.setVisible(true);//making the frame visible

public static void main(String[] args) {

new Simple();

Conclusion :Studied GUI implementation using AWT and swing in Java

62 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Applets

Title of Experiment : WAP to use applets in Browser

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

63 | P a g e
Practical 11
Applets
import java.applet.*;

import java.awt.*;

public class param extends Applet {

String str;

public void init() {

str=getParameter("pname");

if (str == null)

str = "Welcome to Watumull";

str = "Hello " + str;

public void paint(Graphics g) {

g.drawString(str, 200, 200);

HTML Code
<html>

<applet code=param.class height=300 width=300>

<param Name="pname" value="Welcome to Watumull">

</applet>

</html

Conclusion : Created applet and HTML code for running the applet in browser.

64 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Exception Handling

Title of Experiment : WAP for Exception Handling using tyr..catch ,try..catch..finally blocks & throw ,throws

keywords

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

65 | P a g e
Practical 12
Exception Handling
Java try...catch block
The try-catch block is used to handle exceptions in Java.

The syntax of try...catch block:

try {

// code

catch(Exception e) {

// code

Place the code that might generate an exception inside the try block. Every try block is
followed by a catch block.When an exception occurs, it is caught by the catch block. The catch
block cannot be used without the try block.

Java finally block


In Java, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The syntax of block is:

try {

//code

catch (ExceptionType1 e1) {

/ catch block

finally {

/ finally block always executes

66 | P a g e
}

Program 1 :Exception Handling using try..catch..finally block

class Main { public static void main(String[] args) {

/ code that generates

exception try {

int divideByZero = 5 / 0;

catch (ArithmeticException e)

{ System.out.println("ArithmeticException => " +

e.getMessage());

finally {

System.out.println("This is the finally block");

Output :
ArithmeticException => / by zero

This is the finally block

Java throw and throws keyword

The Java throw keyword is used to explicitly throw a single exception.When we throw an
exception, the flow of the program moves from the try block to the catch block.

67 | P a g e
The throws keyword is used to declare the type of exceptions that might occur within the
method. It is used in the method declaration.

Program 2 : Exception Handling using throw keyword


class Main { public static void divideByZero() {

/ throw an exception throw new

ArithmeticException("Trying to divide by 0");

public static void main(String[] args) {

divideByZero();

Output :
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0

at Main.divideByZero(Main.java:5)

at Main.main(Main.java:9)

Program 3 : Program Using throws


public class Main {

static void checkAge(int age) throws ArithmeticException {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18


years old.");

68 | P a g e
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 MyClass.checkAge(MyClass.java:4)
at MyClass.main(MyClass.java:12)

Conclusion : Studied inbuilt Exception Handling using try..catch , try..catch..finally blocks


and throw and throws keywords.

69 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : User Defined Exception

Title of Experiment : To write a program for user defined exceptions.

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

70 | P a g e
Practical 13

Program 1 :User defined exception


/* MyException should extend Exception class */

class MyException extends Exception{

String str1;

/* Constructor of custom exception class ,copy the message that we are


passing while throwing the exception to a string and then displaying
that string along with the message. */

MyException(String str2) {

str1=str2;

public String toString(){

return ("MyException Occurred: "+str1) ;

class Example1{ public static void main(String args[]){

try{

System.out.println("Starting of try block");

/ I'm throwing the custom exception using throw

throw new MyException("This is My error Message");

catch(MyException exp)

{ System.out.println("Catch Block")

; System.out.println(exp) ;

71 | P a g e
}

Output:

Starting of try block Catch Block MyException Occurred:

This is My error Message

Conclusion : Studied user defined Exception handling.

72 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : JDBC

Title of Experiment : Program for connecting MySQL database to Java program using JDBC

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

73 | P a g e
Practical 14
JDBC
Aim : To Crate Login Database using MySQL and create connection in Java JDBC.

Database Setup

MySQL Statements
• Make sure that you have installed the MySQL server on your machine.

• First create a database with the following SQL statement:

create database StudentDB;

• Create a LoginTB table in the above-created database with the following SQL statement:

CREATE TABLE LoginTB ( Login_Level int NOT NULL, LName varchar(50) NOT
NULL, Password varchar(15));

• Insert a record in the above table with the following SQL statement.

INSERT INTO LoginTB (Login_Level, LMame, Password) VALUES (1,


‘Admin', ‘Admin@1234');

• Insert a record in the above table with the following SQL statement.

INSERT INTO LoginTB (Login_Level, LMame, Password) VALUES (2,


'Ramesh', 'Ramesh@1234');

Java Program
import java.sql.*;

class MysqlCon{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(

74 | P a g e
"jdbc:mysql://localhost:3306/LoginDB","root",”");

//here LoginDB is database name, root is username and

password Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from LoginTB");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString


(3));

con.close();

}catch(Exception e){

System.out.println(e);

Conclusion : Created JDBC Connection .Read data from MySQL Database successfully.

75 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : Multithreading.

Title of Experiment : Program for Multithreading concept.

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

76 | P a g e
77 | P a g e
Practical 15
Program on MultiThreading

// Java code for thread creation by extending the Thread class

class MultithreadingDemo extends Thread {


public void run()
{
try {
/ Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
/ Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

Output
Thread 15
is running
Thread 14
is running
Thread 16
is running
Thread 12
is running
Thread 11
is running
Thread 13
is running
Thread 18
is running
Thread 17
is running
Conclusion : Studied Multithreading .
78 | P a g e
Second year: Computer Engineering
[Skill Lab : OOPs with Java]

Experiment

Name : __________________________________________________________

Experiment : GUI Application

Title of Experiment : GUI Application for Login using swing and JDBC.

W.I.E.E.C.T
Experiment/Assignment

Concept 02

Execution/Performance 04

Viva 04

Total 10

Date of Submission: __________________

Signature of faculty: __________________

Sr.No Course Outcome


1 To apply fundamental programming constructs.
2 To illustrate the concept of packages, classes and objects.
3 To elaborate the concept of strings, arrays and vectors.
4 To implement the concept of inheritance and interfaces.
5 To implement the concept of exception handling and multithreading.
6 To develop GUI based application.

79 | P a g e
Practical 16
Program : GUI Application for Login Panel using swing ,AWT and JDBC

Panel : using Java NetBeans

Code :

package loginform;

/* @author SVKADAM */

//import java.sql.Connection;

//import java.sql.DriverManager;

//import java.sql.ResultSet;

//import java.sql.SQLException;

//import java.sql.Statement;

//or

import java.sql.*;

80 | P a g e
import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JOptionPane;

public class LoginDemo extends javax.swing.JFrame {

/ Creates new form LoginDemo

public LoginDemo() {

initComponents();

/* This method is called from within the constructor to initialize the


form.

WARNING: Do NOT modify this code. The content of this method is always
regenerated by the Form Editor. */

@SuppressWarnings("unchecked")

/ <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

LblUserName = new javax.swing.JLabel();

LblPassword = new javax.swing.JLabel();

TxtUserName = new javax.swing.JTextField();

TxtPassword = new javax.swing.JPasswordField();

BtnLogin = new javax.swing.JButton(); BtnReset =

new javax.swing.JButton();

BtnExit = new javax.swing.JButton();

81 | P a g e
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

getContentPane().setLayout(null);

LblUserName.setBackground(new java.awt.Color(0, 204, 255));

LblUserName.setFont(new java.awt.Font("Consolas", 1, 14));

LblUserName.setText("User Name");

getContentPane().add(LblUserName);

LblUserName.setBounds(28, 27, 72, 17);

LblPassword.setBackground(new java.awt.Color(51, 153, 255));

LblPassword.setFont(new java.awt.Font("Consolas", 1, 14));

LblPassword.setText("Password");

getContentPane().add(LblPassword); LblPassword.setBounds(28,

68, 64, 17); TxtUserName.setBackground(new java.awt.Color(0,

204, 255)); TxtUserName.setFont(new

java.awt.Font("Consolas", 1, 14));

TxtUserName.addActionListener(new
java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

TxtUserNameActionPerformed(evt);

});

getContentPane().add(TxtUserName);

TxtUserName.setBounds(158, 24, 119, 23);

82 | P a g e
TxtPassword.setBackground(new java.awt.Color(0, 204, 255));

TxtPassword.setFont(new java.awt.Font("Consolas", 1, 14

getContentPane().add(TxtPassword);

TxtPassword.setBounds(158, 65, 119, 23);

BtnLogin.setBackground(new java.awt.Color(0, 153, 255));

BtnLogin.setFont(new java.awt.Font("Consolas", 1, 18));

BtnLogin.setText("Login");

BtnLogin.setToolTipText("");

BtnLogin.addActionListener(new java.awt.event.ActionListener()

{ public void actionPerformed(java.awt.event.ActionEvent evt) {

BtnLoginActionPerformed(evt);

});

getContentPane().add(BtnLogin); BtnLogin.setBounds(26,

106, 83, 31); BtnReset.setBackground(new

java.awt.Color(0, 153, 255)); BtnReset.setFont(new

java.awt.Font("Consolas", 1, 18));

BtnReset.setText("Reset");

BtnReset.addActionListener(new java.awt.event.ActionListener()

{ public void actionPerformed(java.awt.event.ActionEvent evt) {

BtnResetActionPerformed(evt);

});

getContentPane().add(BtnReset);

BtnReset.setBounds(115, 106, 83, 31);

83 | P a g e
BtnExit.setBackground(new java.awt.Color(0, 153, 255));

BtnExit.setFont(new java.awt.Font("Consolas", 1, 18));

BtnExit.setText("Exit");

BtnExit.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

BtnExitActionPerformed(evt);

});

getContentPane().add(BtnExit);

BtnExit.setBounds(204, 106, 73, 31);

pack();

}// </editor-fold>

private void BtnLoginActionPerformed(java.awt.event.ActionEvent evt) {

String DB_URL = "jdbc:mysql://localhost:3306/employee";

String DB_DRV = "com.mysql.jdbc.Driver";

String DB_USER = "root";

String DB_PASSWD = "";

String UName =

TxtUserName.getText(); String PWD =

TxtPassword.getText(); Connection

connection = null; Statement

statement = null; ResultSet

resultSet1 = null; ResultSet

resultSet2 = null; try{

84 | P a g e
connection=DriverManager.getConnection (DB_URL,DB_USER,DB_PASSWD);

statement=connection.createStatement();

resultSet1=statement.executeQuery("SELECT * FROM logintb");

while(resultSet1.next()){

System.out.printf("%s %s %d",

resultSet1.getString(1),

resultSet1.getString(2),

resultSet1.getInt(3));

System.out.println("\n");

String sql1 = "Select * from logintb where UserName=? and PWD=?";

PreparedStatement pst = connection.prepareStatement(sql1);

pst.setString(1,UName);

pst.setString(2,PWD);

resultSet2 =pst.executeQuery();

while(resultSet2.next()){

System.out.printf("%s %s %d",

resultSet2.getString(1),

resultSet2.getString(2),

resultSet2.getInt(3));

System.out.println("\n");

if (resultSet2.getString(1).equals(UName) &&
resultSet2.getString(2).equals(PWD)){

System.out.println("Welcome");

85 | P a g e
}

else{

System.out.println("Wromg User Name or Password");

}catch(SQLException e)

{ JOptionPane.showMessageDialog(null,
e);

finally{

try {

resultSet1.close();

statement.close();

connection.close();

} catch (SQLException ex) {

//basic code without JDBC

/ if (UName.equals("Admin") && PWD.equals("test")){

/ System.out.println("Welcome");

/ }

private void BtnResetActionPerformed(java.awt.event.ActionEvent evt) {

/ TODO add your handling code

here: TxtUserName.setText(null);

86 | P a g e
TxtPassword.setText(null);

private void BtnExitActionPerformed(java.awt.event.ActionEvent evt) {

/ TODO add your handling code

here: System.exit(0);

/* @param args the command line arguments */

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel


setting //code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay


with the default look and feel. */

try {

for (javax.swing.UIManager.LookAndFeelInfo info :


javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

} catch (ClassNotFoundException ex) {

87 | P a g e
java.util.logging.Logger.getLogger(LoginDemo.class.getName()).log(java .util.logging.Level.SEVERE,

null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(LoginDemo.class.getName()).log(java .util.logging.Level.SEVERE,

null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(LoginDemo.class.getName()).log(java .util.logging.Level.SEVERE,

null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(LoginDemo.class.getName()).log(java .util.logging.Level.SEVERE,

null, ex);

//</editor-fold>

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new LoginDemo().setVisible(true);

});

/ Variables declaration - do not modify

private javax.swing.JButton BtnExit;

88 | P a g e
private javax.swing.JButton BtnLogin;

private javax.swing.JButton BtnReset;

private javax.swing.JLabel LblPassword;

private javax.swing.JLabel LblUserName;

private javax.swing.JPasswordField TxtPassword;

private javax.swing.JTextField TxtUserName;

// End of variables declaration

Database Setup

MySQL Statements
• Make sure that you have installed the MySQL server on your machine.

• First create a database with the following SQL statement:

create database StudentDB;

• Create a LoginTB table in the above-created database with the following SQL statement:

CREATE TABLE LoginTB ( Login_Level int NOT NULL, LName varchar(50) NOT
NULL, Password varchar(15));

• Insert a record in the above table with the following SQL statement.

INSERT INTO LoginTB (Login_Level, LMame, Password) VALUES (1,


‘Admin', ‘Admin@1234');

• Insert a record in the above table with the following SQL statement.

INSERT INTO LoginTB (Login_Level, LMame, Password) VALUES (2,


'Ramesh', 'Ramesh@1234');

Conclusion : Created GUI Application for Login using swing and JDBC.

89 | P a g e

You might also like