Oops Manual - Final - 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

LABORATORY MANUAL

OBJECT ORIENTED PROGRAMMING &


METHODOLOGY LAB

B. TECH.
(II YEAR – ODD SEM)

COLLEGE OF ENGINEERING
ROORKEE
(Affiliated to Veer Madho Singh Bhandari Uttarakhand Technical University,
Dehradun)
Approved by AICTE & MHRD, Govt of India, Accredited by NAAC
Roorkee-Haridwar Road (NH-58),
Post Box No. 27, Vardhmanpuram,
Roorkee- 247667 District. Haridwar (Uttarakhand)
www.coer.ac.in
COLLEGE OF ENGINEERING ROORKEE

Vision
"To impart education in Engineering with training, skill upgradation and research in
futuristic technologies and niche areas."

Mission
M1: To develop the professionals having basic and advanced competencies so that they can
serve the Society & Industry, and face the global challenges.

M2: To impart education based on latest knowledge, with analytical and experimental skills,
through advanced methods of training, research and strong Institute-Industry interface.

M3: To help create innovative and entrepreneurial professional.

M4: To inculcate strong moral values for a disciplined professional growth.


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Vision
To promote innovation-centric education and perform research in Computer Science and
Engineering in pace with industrial development.

Mission
M1: To provide a learning environment that helps students to enhance problem solving skills
at par with global standards.

M2: To establish Industry-Institute Interaction to make students ready for the industrial
environment.

M3: To provide exposure to students to the latest tools and technologies in the area of computer
hardware and software.

M4: To promote research-based projects/activities in the emerging areas.

M5: To foster the science of creativity and educating ownership for sustainable & scalable
ventures.

M6: To pass on the requisite moral characteristics and infuse discipline amongst the students
to make them attain consistent elevation in their professional life.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1: To equip the students with skills and latest updated so that they can work and contribute
to the continuously changing landscape of IT Industry.

PEO2: To provide research-oriented education with knowledge of state-of-art analytical and


experimental tools to enable students to pursue higher studies in institutions of repute in India
and abroad

PEO3: To inculcate culture of professionalism, ethical conduct, team work with good
communication skills to enable the students to be successful in their career and enable them to
launch start-ups in their chosen field.

PROGRAMME SPECIFIC OUTCOME (PSOs)

PSO1: Students will have the ability to apply software engineering principles to design, build,
test, and deliver solutions for Software Industry

PSO2: The students will be able to use programming, database, networking and web
development concepts for developing solutions for real-life problems.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Program Outcomes
Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
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.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling 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.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
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.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
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 multidisciplinary 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.
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the
starting time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to
the lab with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
• Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
• Laboratory Record updated up to the last session experiments and other
utensils (if any) needed in the lab.
• Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the
computer system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high-end branded systems,
which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode
during the lab sessions. Misuse of the equipment, misbehaviors with the staff
and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go
out; if anybody found loitering outside the lab / class without permission during
working hours will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she
leaves the lab after completing the task (experiment) in all aspects. He/she must
ensure the system / seat is kept properly.
Sub Code BEEP 305

Sub Name Object Oriented Programming & Methodology Lab

Bloom’s
COURSEOUTCOMES
Level
BL-2
CO1 Write basic programs using Java compiler.
BL-3
CO2 Implement using packages, inheritance and interface in Java program.
BL-3
CO3 Build connection with database using Java Database Connectivity.
Create the Graphical User Interface using Swings, Applets, Interface and BL-6
CO4 Package.
BL-3
CO5 Implement various sorting techniques using Java.

CO-PO Matrix

Course
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Outcome

CO1 1
CO2 1 2 1
CO3 1
CO4 2 2 2 1 1 1 1
CO5 1
Avg 2 1.3 1.6 1 1 1 1

Cos PSO1 PSO2

CO1 1
CO2 1 2
CO3 2
CO4 2 2
CO5 2
Avg
1.5 1.8
Study and Evaluation Scheme

Course Course
Teaching Scheme Credits Assigned
Code Name
BEEP 305 Object Oriented Theory Practical Tutorial Theory Practical Tutorial Total
Programming
-- 02 -- -- 01 -- 01
& Methodology
(50
Lab Marks)

List of Programs (as per UTU):


1. To write a Java program to print HELLO INDIA.
2. To write a java program that takes in command line arguments as input and print the
number of arguments.
3. To write a java program find the division of student.
4. To write a program implements the concept of inheritance.
5. To write a java program method overloading.
6. To write a java program for method over riding.
7. To write a java program exception handling.
8. To write a java program to run applet for drawing various shapes.
9. To write a java program to design a login using JFrame.
10.To write a java program to validate the logging details of user using JDBC concept.
11.To write a Java program Insertion sort.
12.To write a Java program merge sort.
13.To write a Java program first n prime number.
LIST OF PROGRAMS

Subject: Object Oriented Programming & Methodology Lab Code: BEEP-305

Sno Name of Experiment CO Mapping


1 To write a java program that takes in command line arguments as input and CO1
print the number of arguments.
2 To write a java program find the division of student. CO1
3 To write a Java program first n prime number CO1
4 Write a java program to find the Fibonacci series using recursive and non- CO1
recursive functions
5 Write a java program for Method overloading and Constructor overloading CO2
6 Write a java program to display the employee details using Scanner class CO2
7 A) Write a java program to create inner classes CO2
B) Write a java program to create user defined package
8 To write a java program for method over riding CO2
9 To write a java program exception handling CO2
10 To write a program implements the concept of inheritance CO2
11 To write a java program to validate the logging details of user using JDBC CO3
concept
12 Write a java program to connect to a database using JDBC and insert 34 CO3
values into it.

13 Write a java program to connect to a database using JDBC and delete 36 CO3
values from it
14 To write a java program to run applet for drawing various shapes. CO4
15 To write a java program to design a login using Jframe CO4
16 Write a java program that works as a simple calculator. Use a Grid Layout CO4
to arrange Buttons for digits and for the + - * %operations. Add a text field
to display the result
17 To write a Java program Insertion sort CO5
18 To write a Java program merge sort CO5
19 To write a Java program of bubble sort CO5
Experiment No. 1

Title: To write a java program that takes in command line arguments as input and
print the number of arguments

Java Command Line Arguments


The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an input.So, it provides a convenient way to check the behaviour of the program for
the different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.

SOURCE CODE:

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

for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}

OUTPUT:
compile by > javac A.java
run by > java A COER ROORKEE 1 3 abc

COER
ROORKEE
1
3
abc
Experiment No. 2

Title: To write a java program find the division of student.

Java Program to find the grade of a student, given the percentage of students we have to
print the grade of a student based on the following grade slab.

If Percentage >= 90, Excellent: Grade A


If 80 =< Percentage < 90, Very Good: Grade B
If 70= < Percentage < 80, Good: Grade C
If 60 =< Percentage <70, Satisfactory: Grade D
If 50= <Percentage <60, Work Hard: Grade E
If 40= <Percentage <50, Just Passed: Grade F
Else Failed!

SOURCE CODE:

import java.util.Scanner;
public class grade {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);


System.out.println("Enter percentage marks");
double percentage = scan.nextDouble();

if(percentage >= 90){


System.out.println("Excellent: Grade A");
}else if(percentage < 90 && percentage >= 80){
System.out.println("Very Good: Grade B");
}else if(percentage < 80 && percentage >= 70){
System.out.println("Good: Grade C");
}else if(percentage < 70 && percentage >= 60){
System.out.println("Satisfactory: Grade D");
}else if(percentage < 60 && percentage >= 50){
System.out.println("Work Hard: Grade E");
}else if(percentage < 50 && percentage >= 40){
System.out.println("Just Passed: Grade F");
}else {
System.out.println("Failed!");
}
}

OUTPUT:

Enter percentage marks


67
Satisfactory: Grade D
Experiment No. 3

Title: To write a Java program to find first n prime numbers

SOURCE CODE:

class primeprint
{
//function to check if a given number is prime
static boolean isPrime(int n){
//since 0 and 1 is not prime return false.
if(n==1||n==0) return false;

//Run a loop from 2 to n-1


for(int i=2; i<=n/2; i++){
// if the number is divisible by i, then n is not a prime number.
if(n%i==0)return false;
}
//otherwise, n is prime number.
return true;
}

// Driver code
public static void main (String[] args)
{
int N = 100;
//check for every number from 1 to N
for(int i=1; i<=N; i++){
//check if current number is prime
if(isPrime(i)) {
System.out.print(i + " ");
}
}

}
}

OUTPUT:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
2 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 3 5 7 11 13 17 19
23 29 31 37 41 43 47 53 59 61
Experiment No. 4

Title: Write a java program to find the Fibonacci series using recursive and non-
recursive functions

In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2,
3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.

There are two ways to write the Fibonacci series program in java:
1. Fibonacci Series without using recursion
2. Fibonacci Series using recursion

1. Fibonacci Series in Java without using recursion:

SOURCE CODE:

class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed


{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

OUTPUT:

Compile by: javac FibonacciExample1.java


Run by: java FibonacciExample1
0 1 1 2 3 5 8 13 21 34
2. Fibonacci series program in java using recursion.

class FibonacciExample2{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}

OUTPUT:

Compile by: javac FibonacciExample2.java


Run by: java FibonacciExample2
0 1 1 2 3 5 8 13 21 34
Experiment No. 5

Title: Write a java program for Method overloading and Constructor overloading.

Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of input
parameters or both. Overloading is related to compile-time (or static) polymorphism.

SOURCE CODE:

class Sum {

// Overloaded sum(). This sum takes two int parameters


public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double parameters


public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

OUTPUT:

30
60
31.0
Constructor Overloading:

In addition to overloading methods, we can also overload constructors in java. Overloaded


constructor is called based upon the parameters specified when new is executed.

When do we need Constructor Overloading?

Sometimes there is a need of initializing an object in different ways. This can be done
using constructor overloading.

SOURCE CODE:

class Box
{
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box()
{
width = height = depth = 0;
}

// constructor used when cube is created


Box(double len)
{
width = height = depth = len;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

// Driver code
class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}

OUTPUT:

Volume of mybox1 is 3000.0


Volume of mybox2 is 0.0
Volume of mycube is 343.0
Experiment No. 6

Title: Write a java program to display the employee details using Scanner class

SOURCE CODE:

import java.util.Scanner;
class Employee1
{
int id;
String name;
String desig;
float salary;
}

public class Employee {


public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("How many employees? ");
int n = sc.nextInt();
Employee1 emp[] = new Employee1[n];
for (int i = 0; i < n; i++) {
emp[i] = new Employee1();
System.out.println("Enter " + (i + 1) + " Employee data :");
System.out.print("Enter employee id :");
emp[i].id = sc.nextInt();
System.out.print("Enter employee name :");
emp[i].name = sc.next();
System.out.print("Enter employee designation :");
emp[i].desig = sc.next();
System.out.print("Enter employee salary :");
emp[i].salary = sc.nextFloat();
}
System.out.println("\n\n**** All Employee Details are :****\n");
for (int i = 0; i < n; i++) {
System.out.println("Employee id, Name, Designation and Salary :" + emp[0].id + "
" + emp[i].name + " " + emp[i].desig + " " +emp[i].salary);
}
}
}

OUTPUT:

How many employees? 2


Enter 1 Employee data :
Enter employee id :123
Enter employee name :Sandhya
Enter employee designation :AP
Enter employee salary :1222222
Enter 2 Employee data :
Enter employee id :12345
Enter employee name :Samant
Enter employee designation :AP
Enter employee salary :1234567

*** All Employee Details are :***

Employee id, Name, Designation and Salary :123 Sandhya AP 1222222.0


Employee id, Name, Designation and Salary :123 Samant AP 1234567.0
Experiment No. 7

Title: A. Write a java program to create inner classes

In Java, inner class refers to the class that is declared inside class or interface which were
mainly introduced, to sum up, same logically relatable classes as Java is purely object-
oriented so bringing it closer to the real world. Now geeks you must be wondering why they
were introduced?

There are certain advantages associated with inner classes are as follows:

1. Making code clean and readable.


2. Private methods of the outer class can be accessed, so bringing a new dimension and
making it closer to the real world.
3. Optimizing the code module.

Types of Inner Classes


1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes

SOURCE CODE:

// Class 1
// Helper classes
class Outer {

// Class 2
// Simple nested inner class
class Inner {

// show() method of inner class


public void show()
{

// Print statement
System.out.println("In a nested class method");
}
}
}

// Class 2
// Main class
class Main {

// Main driver method


public static void main(String[] args)
{

// Note how inner class object is created inside


// main()
Outer.Inner in = new Outer().new Inner();

// Calling show() method over above object created


in.show();
}
}

OUTPUT:

In a nested class method


B. Write a java program to create user defined package

Packages:
Packages in Java are a mechanism to encapsulate a group of classes, interfaces, and sub-
packages. In Java, it is used for making search/locating and usage of classes, interface,
enumerations, and annotations easier. It can be considered as data encapsulation also. In
other words, we can say a package is a container of a group of related classes where some
of the classes are accessible are exposed, and others are kept for internal purposes.

Types of Packages

Built-in packages: The already defined package like java.io.*, java. lang.* etc., are known
as built-in packages.

User-defined packages: As the name propose, user-defined packages in Java are essentially
packages that are defined by the programmer. Whenever we want to add a class to the
package, we have to mention the package name and the “package” keyword at the top of the
program.

User-defined packages are those packages that are designed or created by the developer to
categorize classes and packages. They are much similar to the built-in that java offers. It can
be imported into other classes and used the same as we use built-in packages. But If we omit
the package statement, the class names are put into the default package, which has no name.

To create a package, we’re supposed to use the package keyword.

Syntax: package package-name;

Steps to create User-defined Packages


Step 1: Creating a package in java class. The format is very simple and easy. Just write a
package by following its name.

package example1;
Step 2: Include class in java package, But remember that class only have one package
declaration.

package example1;

class gfg {
public static void main(Strings[] args){
-------function--------
}
}
Step 3: Now the user-defined package is successfully created, we can import it into other
packages and use functions it
SOURCE CODE:

package package_name;

public class ClassOne {


public void methodClassOne() {
System.out.println("Hello there its ClassOne");
}
}

package package_one;

public class ClassTwo {


public void methodClassTwo(){
System.out.println("Hello there i am ClassTwo");
}
}

import package_one.ClassTwo;
import package_name.ClassOne;

public class Testing {


public static void main(String[] args){
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
a.methodClassTwo();
b.methodClassOne();
}
}

Output:

Hello there i am ClassTwo


Hello there its ClassOne
Experiment No. 8

Title: To write a java program for method over riding

Overriding is a feature that allows a subclass or child class to provide a specific


implementation of a method that is already provided by one of its super-classes or parent
classes. When a method in a subclass has the same name, same parameters or signature, and
same return type(or sub-type) as a method in its super-class, then the method in the subclass
is said to override the method in the super-class.

SOURCE CODE:

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

class Child extends Parent {


// This method overrides show() of Parent
@Override
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();

// If a Parent type reference refers


// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}

OUTPUT:

Parent's show()
Child's show()
Experiment No. 9

Title: To write a java program exception handling

Exception Handling in Java is one of the effective means to handle the runtime errors so
that the regular flow of the application can be preserved. Java Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.

Exception is an unwanted or unexpected event, which occurs during the execution of a


program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains
information about the exception, such as the name and description of the exception and the
state of the program when the exception occurred.

Major reasons why an exception Occurs


1. Invalid user input
2. Device failure
3. Loss of network connection
4. Physical limitations (out of disk memory)
5. Code errors
6. Opening an unavailable file

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out
of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion,
etc. Errors are usually beyond the control of the programmer, and we should not try to handle
errors.

• Error: An Error indicates a serious problem that a reasonable application should


not try to catch.
• Exception: Exception indicates conditions that a reasonable application might
try to catch.
Types of Exceptions:
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types

PROGRAM:

import java.io.*;

class exception {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}

OUTPUT:

/ by zero
Experiment No. 10

Title: To write a program implements the concept of inheritance

Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the


mechanism in java by which one class is allowed to inherit the features (fields and methods)
of another class.

Important terminology:

Super Class: The class whose features are inherited is known as superclass(or a base class
or a parent class).

Sub Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

How to use inheritance in Java


The keyword used for inheritance is extends.

Syntax :

class derived-class extends base-class


{
//methods and fields
}

SOURCE CODE:

// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}

// derived class
class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}

// driver class
class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());
}
}

OUTPUT:

No of gears are 3
speed of bicycle is 100
seat height is 25
Experiment No. 11

Title: To write a java program to validate the logging details of user using JDBC
concept

In this practical ,we will learn how to create a simple Login application using Java Swing
and we authenticate login user with a database using JDBC and MySQL.

Tools and Technologies used


1. JDK 1.8
2. MySQL Connector Java - 8.0.13
3. JDBC - 4.2
4. Eclipse IDE

What we'll build?


Below are functionalities we will build :
1. User login
2. User Logout
3. User Change Password

Database Setup
Make sure that you have installed the MySQL server on your machine.

create a database with the following SQL statement:


create database swing_demo;

create a student table in the above-created database with the following SQL
statement:
CREATE TABLE student
( id int NOT NULL,
name varchar(250) NOT NULL,
password varchar(250)
);

Insert a single record in the above table with the following SQL statement:
INSERT INTO student (id, name, password) VALUES (1, 'Ramesh', 'Ramesh@1234');

Create a Simple Java Project


Create a simple Java project in Eclipse IDE, name this project as "swing-registration-from-
example".

Connecting With Database


In order to connect our Java program with the MySQL database, we need to include MySQL
JDBC driver which is a JAR file, namely mysql-connector-java-8.0.13-bin.jar.
Develop User Login Form:

SOURCE CODE:

package com.javaguides.javaswing.login;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class UserLogin extends JFrame {

private static final long serialVersionUID = 1L;


private JTextField textField;
private JPasswordField passwordField;
private JButton btnNewButton;
private JLabel label;
private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserLogin frame = new UserLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public UserLogin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 190, 1014, 597);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel("Login");


lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 46));
lblNewLabel.setBounds(423, 13, 273, 93);
contentPane.add(lblNewLabel);

textField = new JTextField();


textField.setFont(new Font("Tahoma", Font.PLAIN, 32));
textField.setBounds(481, 170, 281, 68);
contentPane.add(textField);
textField.setColumns(10);

passwordField = new JPasswordField();


passwordField.setFont(new Font("Tahoma", Font.PLAIN, 32));
passwordField.setBounds(481, 286, 281, 68);
contentPane.add(passwordField);

JLabel lblUsername = new JLabel("Username");


lblUsername.setBackground(Color.BLACK);
lblUsername.setForeground(Color.BLACK);
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblUsername.setBounds(250, 166, 193, 52);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setForeground(Color.BLACK);
lblPassword.setBackground(Color.CYAN);
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblPassword.setBounds(250, 286, 193, 52);
contentPane.add(lblPassword);

btnNewButton = new JButton("Login");


btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 26));
btnNewButton.setBounds(545, 392, 162, 73);
btnNewButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


String userName = textField.getText();
String password = passwordField.getText();
try {
Connection connection = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo",
"root", "root");

PreparedStatement st = (PreparedStatement) connection


.prepareStatement("Select name, password from student where name=? and
password=?");

st.setString(1, userName);
st.setString(2, password);
ResultSet rs = st.executeQuery();
if (rs.next()) {
dispose();
UserHome ah = new UserHome(userName);
ah.setTitle("Welcome");
ah.setVisible(true);
JOptionPane.showMessageDialog(btnNewButton, "You have successfully
logged in");
} else {
JOptionPane.showMessageDialog(btnNewButton, "Wrong Username &
Password");
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
});

contentPane.add(btnNewButton);

label = new JLabel("");


label.setBounds(0, 0, 1008, 562);
contentPane.add(label);
}
}
Develop User Home Page:

package com.javaguides.javaswing.login;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

public class UserHome extends JFrame {

private static final long serialVersionUID = 1 L;


private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserHome frame = new UserHome();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

public UserHome() {
}

/**
* Create the frame.
*/
public UserHome(String userSes) {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 190, 1014, 597);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Logout");
btnNewButton.setForeground(new Color(0, 0, 0));
btnNewButton.setBackground(UIManager.getColor("Button.disabledForeground"));
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 39));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a = JOptionPane.showConfirmDialog(btnNewButton, "Are you sure?");
// JOptionPane.setRootFrame(null);
if (a == JOptionPane.YES_OPTION) {
dispose();
UserLogin obj = new UserLogin();
obj.setTitle("Student-Login");
obj.setVisible(true);
}
dispose();
UserLogin obj = new UserLogin();

obj.setTitle("Student-Login");
obj.setVisible(true);

}
});
btnNewButton.setBounds(247, 118, 491, 114);
contentPane.add(btnNewButton);
JButton button = new JButton("Change-password\r\n");
button.setBackground(UIManager.getColor("Button.disabledForeground"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChangePassword bo = new ChangePassword(userSes);
bo.setTitle("Change Password");
bo.setVisible(true);

}
});
button.setFont(new Font("Tahoma", Font.PLAIN, 35));
button.setBounds(247, 320, 491, 114);
contentPane.add(button);
}
}

Develop Change Password Form:

package com.javaguides.javaswing.login;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class ChangePassword extends JFrame {

private static final long serialVersionUID = 1L;


private JPanel contentPane;
private JTextField textField;
private JLabel lblEnterNewPassword;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public ChangePassword(String name) {
setBounds(450, 360, 1024, 234);
setResizable(false);

contentPane = new JPanel();


contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

textField = new JTextField();


textField.setFont(new Font("Tahoma", Font.PLAIN, 34));
textField.setBounds(373, 35, 609, 67);
contentPane.add(textField);
textField.setColumns(10);

JButton btnSearch = new JButton("Enter");


btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String pstr = textField.getText();


try {
System.out.println("update password name " + name);
System.out.println("update password");

Connection con = (Connection)


DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo",
"root", "root");

PreparedStatement st = (PreparedStatement) con


.prepareStatement("Update student set password=? where name=?");

st.setString(1, pstr);
st.setString(2, name);
st.executeUpdate();
JOptionPane.showMessageDialog(btnSearch, "Password has been
successfully changed");

} catch (SQLException sqlException) {


sqlException.printStackTrace();
}

}
});
btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 29));
btnSearch.setBackground(new Color(240, 240, 240));
btnSearch.setBounds(438, 127, 170, 59);
contentPane.add(btnSearch);

lblEnterNewPassword = new JLabel("Enter New Password :");


lblEnterNewPassword.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblEnterNewPassword.setBounds(45, 37, 326, 67);
contentPane.add(lblEnterNewPassword);
}
}
Experiment No. 12

Title: Write a java program to connect to a database using JDBC and insert 34
values into it.
Java Database Connectivity is basically a standard API(application interface) between the
java programming language and various databases like Oracle, SQL, Postgress, SQL, etc.
It connects the front end(for interacting with the users ) with the backend( for storing
data).

Algorithm: Search/ Insert/ Delete/ Update in JDBC


In order to deal with JDBC standard 7 steps are supposed to be followed:

1. Import the database


2. Load and register drivers
3. Create a connection
4. Create a statement
5. Execute the query
6. Process the results
7. Close the connection

SOURCE CODE:

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/my_db";
static final String USER = "test";
static final String PASS = "test123";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();) {
String sql = "CREATE TABLE Regis " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" sal INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
// Execute a query
System.out.println("Start Insertion");
String sql = "INSERT INTO Regis VALUES (1, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (2, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (3, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(4, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (5, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (6, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (7, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(8, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (9, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (10, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (11, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(12, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (13, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (14, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (15, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(16, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (17, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (18, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (19, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(20, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (21, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (22, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (23, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(24, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (25, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (26, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (27, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(28, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (29, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (30, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (31, 'CCC', 'RKE', 54321)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(32, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (33, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (34, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(35, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (36, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (37, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES(38, 'DDD', 'XYZ', 5432)";
stmt.executeUpdate(sql);
String sql = "INSERT INTO Regis VALUES (39, 'AAA', 'DDN', 1234567)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Regis VALUES (40, 'BBB', 'DLH', 123456)";
stmt.executeUpdate(sql);
System.out.println("Insertion completed");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

OUTPUT:

Created table in given database...


Start Insertion
Insertion completed
Experiment No. 13

Write a java program to connect to a database using JDBC and delete 36 value from it

SOURCE CODE:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/ my_db ";
static final String USER = "test";
static final String PASS = "test123";
static final String QUERY = "SELECT id, first, last, sal FROM Regis";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
String sql = "DELETE FROM Regis " +
"WHERE id = 36";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Sal: " + rs.getInt("sal"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

OUTPUT:

ID: 1, Sal: 1234567, First: AAA, Last: DDN


ID: 2, Sal: 123456, First: BBB, Last: DLH
ID: 3, Sal: 54321, First: CCC, Last: RKE
.
.
.
ID: 35, Sal: 5432,First: DDD,Last:XYZ
.
.
.
ID: 37, Sal: 123456,First: BBB,Last:DLH
ID: 38, Sal: 5432,First: DDD,Last:XYZ
ID: 39, Sal: 1234567,First:AAA,Last:DDN
ID: 40, Sal: 123456,First: BBB,Last:DLH
Experiment No. 14

Title : To write a java program to run applet for drawing various shapes.

SOURCE CODE:

import java.awt.*; // Importing awt package


import java.applet.*; // Importing applet package

public class Shapes extends Applet


{
public void paint(Graphics g)
{
g.setFont(new Font("Cambria", Font.BOLD,15));
g.drawString("Different Shapes", 15, 15);
g.drawLine(10,20,50,60);
g.drawRect(10,70,40,40);
g.setColor(Color.RED);
g.fillOval(60,20,30,90);
g.fillArc(60,135,80,40,180,180);
g.fillRoundRect(20,120,60,30,5,5);
}
}

OUTPUT:
Experiment No. 15

Title: To write a java program to design a login using JFrame

In Java, a form for entering authentication credentials to access the restricted page is referred
to as a Login form. A login form contains only two fields, i.e., username and password. Each
user should have a unique username that can be an email, phone number, or any custom
username.

After submitting the login form, the underlying code of the form checks whether the
credentials are authentic or not to allow the user to access the restricted page. If the users
provide unauthentic credentials, they will not be able to forward the login form.

Steps to create login form:

In order to create a login form in Java, we have to follow the following steps:

1. Create a class that uses the JFrame and ActionListener to design the login form and
perform the action.
2. Create user interface components using swings and awt and add them to the panel.
3. Override the actionPerformed() method that will call on the button click.
4. In this method, we will verify the user entered credentials.
5. Create a new page using JFrame and navigate the user to it if the credentials are
authentic.
6. Else show an error message to the user.

SOURCE CODE:

LoginFormDemo.java

//import required classes and packages


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Exception;

//create CreateLoginForm class to create login form


//class extends JFrame to create a window where our component add
//class implements ActionListener to perform an action on button click
class CreateLoginForm extends JFrame implements ActionListener
{
//initialize button, panel, label, and text field
JButton b1;
JPanel newPanel;
JLabel userLabel, passLabel;
final JTextField textField1, textField2;
//calling constructor
CreateLoginForm()
{

//create label for username


userLabel = new JLabel();
userLabel.setText("Username"); //set label value for textField1

//create text field to get username from the user


textField1 = new JTextField(15); //set length of the text

//create label for password


passLabel = new JLabel();
passLabel.setText("Password"); //set label value for textField2

//create text field to get password from the user


textField2 = new JPasswordField(15); //set length for the password

//create submit button


b1 = new JButton("SUBMIT"); //set label to button

//create panel to put form elements


newPanel = new JPanel(new GridLayout(3, 1));
newPanel.add(userLabel); //set username label to panel
newPanel.add(textField1); //set text field to panel
newPanel.add(passLabel); //set password label to panel
newPanel.add(textField2); //set text field to panel
newPanel.add(b1); //set button to panel

//set border to panel


add(newPanel, BorderLayout.CENTER);

//perform action on button click


b1.addActionListener(this); //add action listener to button
setTitle("LOGIN FORM"); //set title to the login form
}

//define abstract method actionPerformed() which will be called on button click


public void actionPerformed(ActionEvent ae) //pass action listener as a parameter
{
String userValue = textField1.getText(); //get user entered username from the
textField1
String passValue = textField2.getText(); //get user entered pasword from the
textField2

//check whether the credentials are authentic or not


if (userValue.equals("test1@gmail.com") && passValue.equals("test")) { //if
authentic, navigate user to a new page
//create instance of the NewPage
NewPage page = new NewPage();

//make page visible to the user


page.setVisible(true);

//create a welcome label and set it to the new page


JLabel wel_label = new JLabel("Welcome: "+userValue);
page.getContentPane().add(wel_label);
}
else{
//show error message
System.out.println("Please enter valid username and password");
}
}
}
//create the main class
class LoginFormDemo
{
//main() method start
public static void main(String arg[])
{
try
{
//create instance of the CreateLoginForm
CreateLoginForm form = new CreateLoginForm();
form.setSize(300,100); //set size of the frame
form.setVisible(true); //make form visible to the user
}
catch(Exception e)
{
//handle exception
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
NewPage.java

//import required classes and packages


import javax.swing.*;
import java.awt.*;

//create NewPage class to create a new page on which user will navigate
class NewPage extends JFrame
{
//constructor
NewPage()
{
setDefaultCloseOperation(javax.swing.
WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
setSize(400, 200);
}
}

OUTPUT:

Now, when we run the LoginFormDemo.java class, a panel will be open having the label, text
fields, and button. We enter the credentials and hit on the submit button. If the credentials are
authentic, the login form will navigate us to the welcome page as described below:
Experiment No. 16

Title: Write a java 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.

SOURCE CODE:

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
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("");
}
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("");
}
}
}

OUTPUT:
Experiment No. 17

Title: To write a Java program Insertion sort

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing
cards in your hands. The array is virtually split into a sorted and an unsorted part. Values
from the unsorted part are picked and placed at the correct position in the sorted part.

Characteristics of Insertion Sort:


1. This algorithm is one of the simplest algorithm with simple implementation
2. Basically, Insertion sort is efficient for small data values
3. Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already
partially sorted.

SOURCE CODE:

class InsertionSort {
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

/* A utility function to print array of size n*/


static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };

InsertionSort ob = new InsertionSort();


ob.sort(arr);

printArray(arr);
}
}

OUTPUT:

5 6 11 12 13
Experiment No. 18

Title: To write a Java program merge sort

Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge () function is
used for merging two halves. The merge(arr, l, m, r) is key process that assumes that
arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.

SOURCE CODE:

class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int [n1];
int R[] = new int [n2];

/*Copy data to temp arrays*/


for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarray array


int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy remaining elements of L[] if any */


while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy remaining elements of R[] if any */


while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

// Main function that sorts arr[l..r] using


// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;

// Sort first and second halves


sort(arr, l, m);
sort(arr , m+1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

/* A utility function to print array of size n */


static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};

System.out.println("Given Array");
printArray(arr);

MergeSort ob = new MergeSort();


ob.sort(arr, 0, arr.length-1);

System.out.println("\nSorted array");
printArray(arr);
}
}

OUTPUT:

Given Array
12 11 13 5 6 7

Sorted array
5 6 7 11 12 13
Experiment No. 18

Title: To write a Java program bubble sort

Bubble Sort: In bubble sort algorithm, array is traversed from first element to last element.
Here, current element is compared with the next element. If current element is greater than the
next element, it is swapped.

SOURCE CODE:
public class BubbleSortExample {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}

}
}

}
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");


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

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");


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

}
}
OUTPUT:

Array Before Bubble Sort


3 60 35 2 45 320 5

Array After Bubble Sort


2 3 5 35 45 60 320

You might also like