Oops Manual - Final - 1
Oops Manual - Final - 1
Oops Manual - Final - 1
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.
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.
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
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.
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.
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:
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
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)
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
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
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.
SOURCE CODE:
import java.util.Scanner;
public class grade {
OUTPUT:
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;
// 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
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
OUTPUT:
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:
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 {
// 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:
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;
// 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;
OUTPUT:
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;
}
OUTPUT:
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:
SOURCE CODE:
// Class 1
// Helper classes
class Outer {
// Class 2
// Simple nested inner class
class Inner {
// Print statement
System.out.println("In a nested class method");
}
}
}
// Class 2
// Main class
class Main {
OUTPUT:
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.
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;
package package_one;
import package_one.ClassTwo;
import package_name.ClassOne;
Output:
SOURCE CODE:
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
OUTPUT:
Parent's show()
Child's show()
Experiment No. 9
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.
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.
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
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.
Syntax :
SOURCE CODE:
// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// derived class
class MountainBike extends Bicycle {
// driver class
class Test {
public static void main(String args[])
{
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.
Database Setup
Make sure that you have installed the MySQL server on your machine.
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');
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;
/**
* 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);
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);
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;
/**
* 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);
}
}
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;
/**
* 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);
st.setString(1, pstr);
st.setString(2, name);
st.executeUpdate();
JOptionPane.showMessageDialog(btnSearch, "Password has been
successfully changed");
}
});
btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 29));
btnSearch.setBackground(new Color(240, 240, 240));
btnSearch.setBounds(438, 127, 170, 59);
contentPane.add(btnSearch);
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).
SOURCE CODE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
OUTPUT:
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;
OUTPUT:
Title : To write a java program to run applet for drawing various shapes.
SOURCE CODE:
OUTPUT:
Experiment No. 15
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.
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
//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:
OUTPUT:
Experiment No. 17
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.
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;
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
printArray(arr);
}
}
OUTPUT:
5 6 11 12 13
Experiment No. 18
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;
System.out.println("Given Array");
printArray(arr);
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
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};
}
}
OUTPUT: