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

Java Programming

This document provides details about a Java programming lab session conducted by Ms. Zameer Fatima for student Aakash Garg. It includes information about experiments performed on various Java programming concepts between August 26, 2020 to November 25, 2020. A total of 43 experiments were conducted covering topics like basic Java concepts, arrays, classes, inheritance, interfaces, exceptions and file handling.

Uploaded by

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

Java Programming

This document provides details about a Java programming lab session conducted by Ms. Zameer Fatima for student Aakash Garg. It includes information about experiments performed on various Java programming concepts between August 26, 2020 to November 25, 2020. A total of 43 experiments were conducted covering topics like basic Java concepts, arrays, classes, inheritance, interfaces, exceptions and file handling.

Uploaded by

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

Java Programming Lab

ETCS-357

Faculty Name: Ms. Zameer Fatima Student Name: Aakash Garg

Roll No: 20414802718

Semester/Group: 5C8

Maharaja Agrasen Institute of Technology, PSP area, Sector- 22,


Rohini, New Delhi – 110085
Affiliated to Guru Gobind Singh Indraprastha University New
Delhi
Practical Record:

S.No Experiment Name Date Of Date Of Marks Signature


Performance Checking
1 Write a program to print “Hello 26/08/2020 02/09/2020
World” on the screen.

2 Write a program to convert 26/08/2020 02/09/2020


character to string using
toString() and valueOf()
method.
3 Write a program to convert 26/08/2020 02/09/2020
string to characters.

4 Write a program to convert 26/08/2020 02/09/2020


character array to string.

5 Write a program to find ASCII 26/08/2020 02/09/2020


code of a character.

6 Write a program to display first 26/08/2020 02/09/2020


n prime numbers.

7 Write a program to check 02/09/2020 09/09/2020


vowel or consonant using
Switch case.

8 Write a program to check 02/09/2020 09/09/2020


whether the input year is leap
or not.

9 Write a program that accepts 02/09/2020 09/09/2020


two doubles as its command
line arguments. Multiply these
together and display the
product.

10 Write a program that accepts 02/09/2020 09/09/2020


one command line argument,
display the line reporting if
number is even or odd.
11 Write a program to that 02/09/2020 09/09/2020
accepts radius of a circle as its
command line argument and
display the area.

12 Write a program to display first 02/09/2020 09/09/2020


n prime arguments taking ‘n’ as
a command line argument.

13 Write a program to find the 09/09/2020 16/09/2020


array index or position where
sum of numbers preceding the
index is equal to the sum of
numbers succeeding the index.

14 Write a program that creates 09/09/2020 16/09/2020


and initializes a four element
array. Calculate and display the
average of its values.

15 Write a program that creates a 09/09/2020 16/09/2020


2-D array with int values. The
first element should be an
array containing 32. The
second element should be
array containing 500 and 300.
The third element should be an
array containing 39, 45 and
600. Declare, initialize, allocate
the array and display its
elements.

16 Write a program to sort an 09/09/2020 16/09/2020


array.

17 Write a program to implement 09/09/2020 16/09/2020


stack and queue concept.

18 Using the concept of method 09/09/2020 16/09/2020


overloading, write method for
calculating the area of triangle,
circle and rectangle.
19 Write a program that creates a 16/09/2020 23/09/2020
class circle with instance
variables for the center and
radius. Initialize and display its
values.

20 Write a program to have a 16/09/2020 23/09/2020


constructor in class circle in
Experiment-19 to initialize its
variables.

21 Write a program to show 16/09/2020 23/09/2020


constructor overloading in
Experiment-20.

22 Write a program to display the 16/09/2020 23/09/2020


use of ‘this’ keyword.

23 Write a program to count the 16/09/2020 23/09/2020


number of instances created
for the class.

24 Write a program that describes 16/09/2020 23/09/2020


a class person. It should have
instance variables to record
name, age and salary. Create a
person object. Set and display
its instance variables.

25 Write a program that 23/09/2020 03/11/2020


implements method overriding.

26 Write a program to illustrate 23/09/2020 03/11/2020


simple inheritance.

27 Write a program to illustrate 23/09/2020 03/11/2020


multilevel inheritance.

28 Write a program illustrating all 23/09/2020 03/11/2020


uses of super keyword.

29 Write a java package to show 03/11/2020 18/11/2020


dynamic polymorphism and
interfaces.
30 Write a program that creates 03/11/2020 18/11/2020
an abstract class shape. Let
triangle and rectangle inherit
shape. Add necessary
functions.
31 Write a program that creates 03/11/2020 18/11/2020
interface and implements it.

32 Write a program to illustrate 03/11/2020 18/11/2020


interface inheritance.

33 Write an application that 18/11/2020 25/11/2020


shows how to create a user-
defined exception.

34 Create a customized exception 18/11/2020 25/11/2020


and also make use of all the 5
exception keywords.

35 Write an Applet that displays 18/11/2020 25/11/2020


“Hello World” (Background
color-black, text color-blue and
your name in the status
window).
36 Develop an analog clock using 18/11/2020 25/11/2020
applet.

37 Write a java program to show 25/11/2020


multithreaded producer and
consumer application.

38 Write an application that 25/11/2020


executes two threads. One
thread displays “An” every
1000 milliseconds and other
displays “B” every 3000
milliseconds. Create the
threads by extending the
Thread class.

39 Write a program that illustrates 25/11/2020


mouseevents. The background
color changes when the mouse
is entered, clicked, pressed,
released or exited.
40 Write a program that displays 25/11/2020
your name whenever the
mouse is clicked.

41 Write a program that read from 25/11/2020


a file and write to file.

42 Convert the content of a given 25/11/2020


file into the uppercase content
of the same file.

43 JDBC (Database connectivity 25/11/2020


with MS-Access)
ETCS-357 26th August, 2020

Lab-1

Topics Covered:

• Basic Concepts of Java


• Installing Java and setting Runtime Environment.
• Compiling and Executing Code

Basic Concepts of Java:


Java is a programming language and computing platform first released by Sun Microsystems in
1995. There are lots of applications and websites that will not work unless you have Java
installed, and more are created every day. Java is fast, secure, and reliable. From laptops to
datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is
everywhere.

Java is −

1. Object Oriented − In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
2. Platform Independent − unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
3. Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
4. Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
5. Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
6. Portable − Being architecture-neutral and having no implementation dependent aspects
of the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.

Aakash Garg 20414802718


ETCS-357 26th August, 2020

7. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
8. Multithreaded − With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
9. Interpreted − Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
10. High Performance − with the use of Just-In-Time compilers, Java enables high
performance.
11. Distributed − Java is designed for the distributed environment of the internet.
12. Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.

Installing and Setting Java Runtime Environment:


1. Download JDK installer.
2. Run the JDK installer
3. Go to Settings-> System -> Advanced-> Environment Variables
4. Add the location of bin folder of the JDK installation to the path variables in system
variables.

Compiling and Executing Java Code:


1. Open Command Prompt.
2. Compile by command: javac <filename>.java
3. After successful compilation run the program by command: java <filename>

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Lab – 1 : List Of Experiments :

• Write a program to print “Hello World” on the screen.


• Write a program to convert character to string using toString() and
valueOf() method.
• Write a program to convert string to characters.
• Write a program to convert character array to string.
• Write a program to find ASCII code of a character.
• Write a program to display first n prime numbers.

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Experiment-1

Aim: Write a program to print “Hello World” on the screen.

Code:
public class JavaApplication1 {

public static void main(String[] args) {

System.out.println("Hello World!");

Output:

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Experiment-2

Aim: Write a program to convert character to string using toString() and


valueOf() method.

Code:
public class JavaApplication2 {

public static void main(String[] args) {

char ch = 'a';

String str = Character.toString(ch);

String str2 = String.valueOf(ch);

System.out.println(str);

System.out.println(str2);

Output:

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Experiment-3

Aim: Write a program to convert string to characters.

Code:
public class JavaApplication3{

public static void main(String args[]){

String s="hello";

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

char c = s.charAt(i);

System.out.println("char at "+i+" index is: "+c);

}}

Output:

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Experiment-4

Aim: Write a program to convert character array to string.

Code:
public class JavaApplication4 {

public static void main(String[] args) {

char[] ch = {'H', 'e', 'l', 'l','o'};

String str = new String(ch);

System.out.println(str);

Output:

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Experiment-5

Aim: Write a program to find ASCII code of a character.

Code:
public class JavaApplication5 {

public static void main(String[] args) {

char ch = 'P';

int ascii = ch;

System.out.println("The Character is: "+ch);

System.out.println("The ASCII value is: "+ascii);

Output:

Aakash Garg 20414802718


ETCS-357 26th August, 2020

Experiment-6

Aim: Write a program to display first n prime numbers.

Code:
import java.util.Scanner;

public class JavaApplication6 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Value of n");

int n = sc.nextInt();

System.out.println("First "+n+" prime numbers are: ");

int count = 0;

if(n>=1) {

count=1;

System.out.println("2");

for(int i=3;count<n;i++) {

boolean isPrime = true;

for(int j=2;j<i;j++) {

if(i%j == 0) {

isPrime = false;

break;

Aakash Garg 20414802718


ETCS-357 26th August, 2020

if(isPrime == true) {

count++;

System.out.println(i);

Output:

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Lab-2

Topics Covered:

• Data Types in Java


• Command Line Arguments in Java

Data Types in Java:


Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:

• Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
• Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

Java Command Line Arguments:


A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java
program is quite easy. They are stored as strings in the String array passed to main( ).

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Lab – 2 : List Of Experiments:

• Write a program to check vowel or consonant using Switch case.


• Write a program to check whether the input year is leap or not.
• Write a program that accepts two doubles as its command line arguments.
Multiply these together and display the product.
• Write a program that accepts one command line argument, display the line
reporting if number is even or odd.
• Write a program to that accepts radius of a circle as its command line
argument and display the area.
• Write a program to display first n prime arguments taking ‘n’ as a command
line argument.

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Experiment-7

Aim: Write a program to check vowel or consonant using Switch case.

Code:
import java.util.Scanner;

public class JavaApplication7 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the character");

char ch = sc.next().charAt(0);

switch(ch) {

case 'a': {

System.out.println("It is a vowel");

break;

case 'e' : {

System.out.println("It is a vowel");

break;

case 'i': {

System.out.println("It is a vowel");

break;

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

case 'o': {

System.out.println("It is a vowel");

break;

case 'u': {

System.out.println("It is a vowel");

break;

case 'A': {

System.out.println("It is a vowel");

break;

case 'E': {

System.out.println("It is a vowel");

break;

case 'I': {

System.out.println("It is a vowel");

break;

case 'O': {

System.out.println("It is a vowel");

break;

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

case 'U': {

System.out.println("It is a vowel");

break;

default: {

System.out.println("It is not a vowel");

Output:

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Experiment-8

Aim: Write a program to check whether the input year is leap or not.

Code:
import java.util.Scanner;

public class JavaApplication8 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the year");

int year = sc.nextInt();

if(year%4 == 0) {

System.out.println("It is a leap year");

else {

System.out.println("It is not a leap year.");

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Output:

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Experiment-9

Aim: Write a program that accepts two doubles as its command line arguments.
Multiply these together and display the product.

Code:
public class JavaApplication9 {

public static void main(String[] args) {

double d1 = Double.parseDouble(args[0]);

double d2 = Double.parseDouble(args[1]);

double d3 = d1*d2;

System.out.println("The product is "+d3);

Output:

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Experiment-10

Aim: Write a program that accepts one command line argument, display the line
reporting if number is even or odd.

Code:
public class JavaApplication10 {

public static void main(String[] args) {

int num = Integer.parseInt(args[0]);

if(num%2 == 0) {

System.out.println("The number is even.");

else {

System.out.println("The number is odd");

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Output:

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Experiment-11

Aim: Write a program to that accepts radius of a circle as its command line
argument and display the area.

Code:
public class JavaApplication11 {

public static void main(String[] args) {

float r = Float.parseFloat(args[0]);

System.out.println("The area of the circle is "+Math.PI*r*r);

Output:

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

Experiment-12

Aim: Write a program to display first n prime arguments taking ‘n’ as a


command line argument.

Code:
public class JavaApplication12 {

public static void main(String[] args) {

int n = Integer.parseInt(args[0]);

System.out.println("First "+n+" prime numbers are: ");

int count = 0;

if(n>=1) {

count=1;

System.out.println("2");

for(int i=3;count<n;i++) {

boolean isPrime = true;

for(int j=2;j<i;j++) {

if(i%j == 0) {

isPrime = false;

break;

if(isPrime == true) {

Aakash Garg 20414802718


ETCS-357 2nd September, 2020

count++;

System.out.println(i);

Output:

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Lab-3

Topics Covered:

• Collection Framework in Java


• Arrays in Java
• Implementation of Stack and Queue
• Method Overloading

Collection Framework in Java:


The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects. Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion. Java Collection means a single
unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Dequeue)
and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

Arrays in Java:
An array is a group of like-typed variables that are referred to by a common name. Arrays in
Java work differently than they do in C/C++. Following are some important point about Java
arrays.

• In Java all arrays are dynamically allocated.


• Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Stack and Queue:


Stack - It’s a linear data structure which follows FILO(First In Last Out) order. The only the
functions which can be performed in stack data structure are push, pop and access top.

1) push(Object element)
2) pop()
3) peek()
4) empty()

Queue - It’s a linear data structure which follows FIFO(First In First Out) order. The Queue
interface presents in the java.util package and extends the Collection interface. The only the
functions which can be performed in queue data structure are insert at rear, remove from
front, access front and access rear value.

1) add(Object element)
2) offer(Object element)
3) peek()
4) poll()
5) remove()

Method Overloading:
Method overloading is a concept that allows to declare multiple methods with same name but
different parameters in the same class. Method overloading is one of the ways through which
java supports polymorphism. Polymorphism is a concept of object oriented programming that
deals with multiple forms. We will cover polymorphism in separate topics later on. Method
overloading can be done by changing number of arguments or by changing the data type of
arguments. If two or more method have same name and same parameter list but differs in
return type cannot be overloaded.

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Lab – 3 : List Of Experiments :

• Write a program to find the array index or position where sum of numbers
preceding the index is equal to the sum of numbers succeeding the index.
• Write a program that creates and initializes a four element array. Calculate
and display the average of its values.
• Write a program that creates a 2-D array with int values. The first element
should be an array containing 32. The second element should be array
containing 500 and 300. The third element should be an array containing
39, 45 and 600. Declare, initialize, allocate the array and display its
elements.
• Write a program to sort an array.
• Write a program to implement stack and queue concept.
• Using the concept of method overloading, write method for calculating the
area of triangle, circle and rectangle.

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Experiment-13

Aim: Write a program to find the array index or position where sum of numbers
preceding the index is equal to the sum of numbers succeeding the index.

Code:
package javaapplication13;

import java.util.Scanner;

public class JavaApplication13 {

int equilibrium(int arr[], int n) {

int i, j;

int leftsum, rightsum;

for (i = 0; i < n; ++i) {

leftsum = 0;

for (j = 0; j < i; j++)

leftsum += arr[j];

rightsum = 0;

for (j = i + 1; j < n; j++)

rightsum += arr[j];

if (leftsum == rightsum)

return i;

return -1;

Aakash Garg 20414802718


ETCS-357 9th September, 2020

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

JavaApplication13 ob = new JavaApplication13();

System.out.println("Enter the number of elements");

int n = sc.nextInt();

int[] arr = new int[n];

for(int i=0;i<n;i++) {

arr[i] = sc.nextInt();

int arr_size = arr.length;

System.out.println(ob.equilibrium(arr, arr_size));

Output:

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Experiment-14

Aim: Write a program that creates and initializes a four element array. Calculate
and display the average of its values.

Code:
package javaapplication14;

import java.util.Scanner;

public class JavaApplication14 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the 4 elements");

int[] arr = new int[4];

float sum = 0;

for(int i=0;i<4;i++) {

arr[i] = sc.nextInt();

for(int i=0;i<4;i++) {

sum = sum + arr[i];

System.out.println("The Average of the 4 elements is: "+(sum/4));

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Output:

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Experiment-15

Aim: Write a program that creates a 2-D array with int values. The first element
should be an array containing 32. The second element should be array
containing 500 and 300. The third element should be an array containing 39, 45
and 600. Declare, initialize, allocate the array and display its elements.

Code:

package javaapplication15;

import java.util.Scanner;

public class JavaApplication15 {

Scanner sc = new Scanner(System.in);

public static void main(String[] args) {

int[][] arr = new int[3][3];

for(int i=-0;i<3;i++) {

for(int j=0;j<3;j++) {

arr[i][j] = 0;

arr[0][0] = 32;

arr[1][0] = 500;

arr[1][1] = 300;

arr[2][0] = 39;

arr[2][1] = 45;

Aakash Garg 20414802718


ETCS-357 9th September, 2020

arr[2][2] = 600;

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++){

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

System.out.println();

Output:

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Experiment-16

Aim: Write a program to sort an array.

Code:

package javaapplication16;

import java.util.Scanner;

public class JavaApplication16 {

void bubbleSort(int arr[])

int n = arr.length;

for (int i = 0; i < n-1; i++)

for (int j = 0; j < n-i-1; j++)

if (arr[j] > arr[j+1])

int temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of elments: ");

Aakash Garg 20414802718


ETCS-357 9th September, 2020

int n = sc.nextInt();

int[] arr = new int[n];

System.out.println("Enter the elements");

for(int i=0;i<n;i++) {

arr[i] = sc.nextInt();

JavaApplication16 ob = new JavaApplication16();

ob.bubbleSort(arr);

System.out.println("The sorted array is: ");

for(int i=0;i<n;i++){

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

Output:

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Experiment-17

Aim: Write a program to implement stack and queue concept.

Code for implementing Stack:

package javaapplication21;

import java.util.Stack;

public class JavaApplication21{

public static void main(String[] args)

Stack<String> stackOfFriends = new Stack<String>();

stackOfFriends.push("Aakash");

stackOfFriends.push("Harshit");

stackOfFriends.push("Rishab");

stackOfFriends.push("Sarthak");

System.out.println("Stack => " + stackOfFriends);

System.out.println();

String frndAtTop = stackOfFriends.peek();

System.out.println("Element at the top => " + frndAtTop);

frndAtTop = stackOfFriends.pop();

System.out.println("\nStack.pop() => " + frndAtTop);

System.out.println("New Stack => " + stackOfFriends);

Aakash Garg 20414802718


ETCS-357 9th September, 2020

System.out.println("\nThe size of Stack is => " + stackOfFriends.size());

if(stackOfFriends.empty())

System.out.println("Stack is Empty");

else

System.out.println("\nStack is not Empty");

System.out.println( "There are " + stackOfFriends.size() + " elements in the stack");

Output (Stack):

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Code for implementing Queue:

package javaapplication22;

import java.util.LinkedList;

public class JavaApplication22 {

private int maxSize;

private int[] queueArray;

private int front;

private int rear;

private int currentSize;

public JavaApplication22(int size){

this.maxSize = size;

this.queueArray = new int[size];

front = 0;

rear = -1;

currentSize = 0;

public void insert(int item){

if(isQueueFull()){

System.out.println("Queue is full!");

return;

if(rear == maxSize - 1){

rear = -1;

Aakash Garg 20414802718


ETCS-357 9th September, 2020

queueArray[++rear] = item;

currentSize++;

System.out.println("Added to queue: " + item);

public int remove(){

if(isQueueEmpty()){

throw new RuntimeException("Queue is empty.");

int temp = queueArray[front++];

if(front == maxSize){

front = 0;

currentSize--;

return temp;

public int peek(){

return queueArray[front];

public boolean isQueueFull(){

return (maxSize == currentSize);

public boolean isQueueEmpty(){

return (currentSize == 0);

Aakash Garg 20414802718


ETCS-357 9th September, 2020

public static void main(String[] args) {

JavaApplication22 queue = new JavaApplication22(10);

queue.insert(2);

queue.insert(3);

System.out.println("Item removed: " + queue.remove());

System.out.println("Item removed: " + queue.remove());

queue.insert(5);

System.out.println("Item removed: " + queue.remove());

Output (Queue) :

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Experiment-18

Aim: Using the concept of method overloading, write method for calculating the
area of triangle, circle and rectangle.

Code:

package javaapplication17;

import java.util.Scanner;

public class JavaApplication17 {

void area(float x,float y,float z) {

float s = (x+y+z)/2;

System.out.println("the area of the triangele is "+Math.pow(s*(s-x)*(s-y)*(s-z), 0.5)+" sq units");

void area(float x, float y) {

System.out.println("the area of the rectangle is "+x*y+" sq units");

void area(double x) {

double z = 3.14 * x * x;

System.out.println("the area of the circle is "+z+" sq units");

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

JavaApplication17 ob = new JavaApplication17();

Aakash Garg 20414802718


ETCS-357 9th September, 2020

System.out.print("1. Area of triangle\n2. Area of rectangle\n3. Area of circle\nEnter Choice");

int ch = sc.nextInt();

switch(ch) {

case 1: {

System.out.println("Enter the sides of triangle.");

float a = sc.nextFloat();

float b = sc.nextFloat();

float c = sc.nextFloat();

ob.area(a,b,c);

} break;

case 2: {

System.out.println("Enter the sides of rectangle:");

float a = sc.nextFloat();

float b = sc.nextFloat();

ob.area(a,b);

} break;

case 3: {

System.out.println("Enter the radius of circle:");

double r = sc.nextDouble();

ob.area(r);

} break;

default: System.out.println("Invalid Choice");

Aakash Garg 20414802718


ETCS-357 9th September, 2020

Output:

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Lab-4

Topics Covered:

• Classes and Objects


• Constructors
• Static

Classes and Objects:


A class is a user defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:

1. Modifiers: A class can be public or has default access.


2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass: The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. Interfaces: A comma-separated list of interfaces implemented by the class, if any,
proceeded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.

Object is a basic unit of Object Oriented Programming and represents the real life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of :

1. State: It is represented by attributes of an object. It also reflects the properties of an


object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Constructors:
Constructors are used to initialize the object’s state. Like methods, a constructor also contains
collection of statements (i.e. instructions) that are executed at time of Object creation. Each
time an object is created using new () keyword at least one constructor (it could be default
constructor) is invoked to assign initial values to the data members of the same class. A
constructor is invoked at the time of object or instance creation.

There are two type of constructor in Java:

1. No-argument constructor: A constructor that has no parameter is known as default


constructor. If we don’t define a constructor in a class, then compiler creates default
constructor (with no arguments) for the class.
2. Parameterized Constructor: A constructor that has parameters is known as
parameterized constructor. If we want to initialize fields of the class with your own
values, then use a parameterized constructor.

Static:
To create a static member (block, variable, method, nested class), precede its declaration with the
keyword static. When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Lab – 4 : List Of Experiments :

• Write a program that creates a class circle with instance variables for the
center and radius. Initialize and display its values.
• Write a program to have a constructor in class circle in Experiment-19 to
initialize its variables.
• Write a program to show constructor overloading in Experiment-20.
• Write a program to display the use of ‘this’ keyword.
• Write a program to count the number of instances created for the class.
• Write a program that describes a class person. It should have instance
variables to record name, age and salary. Create a person object. Set and
display its instance variables.

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Experiment-19

Aim: Write a program that creates a class circle with instance variables for the
center and radius. Initialize and display its values.

Code:

package javaapplication30;

import java.util.Scanner;

class Circle {

int x,y;

float radius;

public class JavaApplication30 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Circle c = new Circle();

System.out.println("Enter the coordinates of center of circle.");

c.x = sc.nextInt();

c.y = sc.nextInt();

System.out.println("Enter the radius.");

c.radius = sc.nextFloat();

System.out.println("The cordinates of center are: "+c.x+" "+c.y);

Aakash Garg 20414802718


ETCS 357 16th September, 2020

System.out.println("The radius is: "+c.radius);

Output:

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Experiment-20

Aim: Write a program to have a constructor in class circle in Experiment-19 to


initialize its variables.

Code:

package javaapplication30;

class Circle {

int x,y;

float radius;

Circle() {

x = 10;

y = 20;

radius = 7;

public class JavaApplication30 {

public static void main(String[] args) {

Circle c = new Circle();

System.out.println("The Center of circle is: "+c.x+" "+c.y);

System.out.println("The radius of circle is: "+c.radius);

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Output:

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Experiment-21

Aim: Write a program to show constructor overloading in Experiment-20.

Code:
package javaapplication30;

class Circle {

int x,y;

float radius;

Circle() {

x = 10;

y = 20;

radius = 7;

Circle(int a, int b, float c) {

x = a;

y = b;

radius = c;

public class JavaApplication30 {

public static void main(String[] args) {

Circle c1 = new Circle();

Circle c2 = new Circle(20,30,14);

Aakash Garg 20414802718


ETCS 357 16th September, 2020

System.out.println("For first object: ");

System.out.println("The Center of circle is: "+c1.x+" "+c1.y);

System.out.println("The radius of circle is: "+c1.radius);

System.out.println("For second object: ");

System.out.println("The Center of circle is: "+c2.x+" "+c2.y);

System.out.println("The radius of circle is: "+c2.radius);

Output:

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Experiment-22

Aim: Write a program to display the use of ‘this’ keyword.

Code:

package javaapplication30;

class ThisKeyword {

int x,y,z;

ThisKeyword() {

this.x = 10;

this.y = 20;

this.z = 30;

public class JavaApplication30 {

public static void main(String[] args) {

ThisKeyword t = new ThisKeyword();

System.out.println("The values are: "+t.x+" "+t.y+" "+t.z);

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Output:

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Experiment-23

Aim: Write a program to count the number of instances created for the class.

Code:
package javaapplication30;

class Count {

static int noOfObjects = 0;

int a;

noOfObjects +=1;

Count(int x) {

a = x;

public class JavaApplication30 {

public static void main(String[] args) {

Count c1 = new Count(5);

Count c2 = new Count(10);

Count c3 = new Count(20);

System.out.println("No of instances of class created: "+Count.noOfObjects);

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Output:

Aakash Garg 20414802718


ETCS 357 16th September, 2020

Experiment-24

Aim: Write a program that describes a class person. It should have instance
variables to record name, age and salary. Create a person object. Set and display
its instance variables.

Code:

package javaapplication30;

import java.util.Scanner;

class Person {

int age;

float salary;

String name;

public class JavaApplication30 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Person p = new Person();

System.out.println("Enter the name of person.");

p.name = sc.nextLine();

System.out.println("Enter the age of person.");

p.age = sc.nextInt();

System.out.println("Enter the salary of person.");

Aakash Garg 20414802718


ETCS 357 16th September, 2020

p.salary = sc.nextFloat();

System.out.println("Name: "+p.name+"\nAge: "+p.age+"\nSalary: "+p.salary);

Output:

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Lab-5

Topics Covered:

• Inheritance
• Method Overriding
• Super Keyword

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.

• Super Class: The class whose features are inherited is known as super class (or a base
class or a parent class).
• Sub Class: The class that inherits the other class is known as sub class (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.

Below are the different types of inheritance which is supported by Java.

• Single Inheritance: In single inheritance, subclasses inherit the features of one


superclass.
• Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the base class to other class.
• Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class.

Method Overriding:
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

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

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. Method overriding is one of the way by which java achieve Run
Time Polymorphism. The version of a method that is executed will be determined by the object
that is used to invoke it. If an object of a parent class is used to invoke the method, then the
version in the parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed. In other words, it is the type of the
object being referred to (not the type of the reference variable) that determines which version
of an overridden method will be executed.

Super Keyword:
The super keyword in java is a reference variable that is used to refer parent class objects. It is
majorly used in the following contexts:

• Use of super with variables: This scenario occurs when a derived class and base class has
same data members.
• Use of super with methods: This is used when we want to call parent class method. So
whenever parent and child classes have same named methods then to resolve
ambiguity we use super keyword.
• Use of super with constructors: super keyword can also be used to access the parent
class constructor. ‘’super’ can call both parametric as well as non-parametric
constructors depending upon the situation.

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Lab – 5 : List Of Experiments :

• Write a program that implements method overriding.


• Write a program to illustrate simple inheritance.
• Write a program to illustrate multilevel inheritance.
• Write a program illustrating all uses of super keyword.

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Experiment-25

Aim: Write a program that implements method overriding.

Code:

package javaapplication31;

class Parent {

void show() {

System.out.println("Parent's show()");

class Child extends Parent {

@Override

void show() {

System.out.println("Child's show()");

public class JavaApplication31 {

public static void main(String[] args) {

Parent obj1 = new Parent();

obj1.show();

Parent obj2 = new Child();

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

obj2.show();

Output:

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Experiment-26

Aim: Write a program to illustrate simple inheritance.

Code:

package javaapplication32;

class one {

public void print_one() {

System.out.println("Class One");

class two extends one

public void print_two() {

System.out.println("Class Two");

public class JavaApplication32 {

public static void main(String[] args) {

two obj = new obj();

obj.print_one();

obj.print_two();

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Output:

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Experiment-27

Aim: Write a program to illustrate multilevel inheritance.

Code:

package javaapplication33;

class one {

public void print_one() {

System.out.println("Class One");

class two extends one {

public void print_two() {

System.out.println("Class Two");

class three extends two {

public void print_three() {

System.out.println("Class Three");

public class JavaApplication33 {

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

public static void main(String[] args) {

three obj = new three();

obj.print_one();

obj.print_two();

obj.print_three();

Output:

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

Experiment-28

Aim: Write a program illustrating all uses of super keyword.

Code:

package javaapplication34;

class Vehicle {

int maxSpeed = 120;

void message() {

System.out.println("This is Vehicle class");

Vehicle() {

System.out.println("Constructor of Vehicle class");

class Car extends Vehicle {

int maxSpeed = 180;

void display() {

System.out.println("Maximum Speed: " + super.maxSpeed);

void message() {

System.out.println("This is Car class");

Aakash Garg 20414802718


ETCS 357 23rd September, 2020

void display2() {

message();

super.message();

Car() {

super();

System.out.println("Constructor of Car class");

public class JavaApplication34 {

public static void main(String[] args) {

Car obj = new Car();

obj.display();

obj.display2();

Output:

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Lab-6

Topics Covered:

• Java Package
• Java Abstraction
• Interfaces

Java Package:
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

java.lang − bundles the fundamental classes

java.io − classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.

Creating a Package

While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

classes, interfaces, enumerations, and annotation types that you want to include in the
package.

The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.

To compile the Java programs with package statements, we have to use -d option as shown
below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.

Java Abstraction:
Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces.

The abstract keyword is a non-access modifier, used for classes and methods:

Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).

Abstract method: can only be used in an abstract class, and it does not have a body. The body
is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods.

Interfaces:
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.

Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.

An interface is similar to a class in the following ways −

• An interface can contain any number of methods.


• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Lab – 6 : List Of Experiments :

• Write a program that creates an abstract class shape. Let triangle and
rectangle inherit shape. Add necessary functions.
• Write a java package to show dynamic polymorphism and interfaces.
• Write a program that creates interface and implements it.
• Write a program to illustrate interface inheritance.

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Experiment-29

Aim: Write a program that creates an abstract class shape. Let triangle and
rectangle inherit shape. Add necessary functions.

Code:
package javaapplication36;

import java.util.Scanner;

import java.lang.Math;

abstract class shape {

int color;

abstract void getSides();

abstract void perimeter();

class rectangle extends shape {

Scanner sc = new Scanner(System.in);

int length, breadth;

void getSides() {

System.out.println("Enter the length and breadth of rectangle.");

length = sc.nextInt();

breadth = sc.nextInt();

void perimeter() {

int ar = 2*(length+breadth);

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

System.out.println("Perimeter is " + ar);

class triangle extends shape {

Scanner sc = new Scanner(System.in);

int a,b,c;

void getSides() {

System.out.println("Enter the sides of triangle.");

a = sc.nextInt();

b = sc.nextInt();

c = sc.nextInt();

void perimeter() {

int ar = a+b+c;

System.out.println("Perimeter is "+ar);

public class JavaApplication36 {

public static void main(String[] args) {

rectangle r = new rectangle();

r.getSides();;

r.perimeter();

triangle t = new triangle();

t.getSides();

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

t.perimeter();

Output:

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Experiment-30

Aim: Write a java package to show dynamic polymorphism and interfaces.

Code:
package javaapplication37;

import java.util.*;

interface shape {

public void getSides();

public void area();

class rectangle implements shape {

int l , b;

Scanner sc = new Scanner(System.in);

public void getSides() {

System.out.println("Enter the sides of rectangle");

l = sc.nextInt();

b = sc.nextInt();

public void area() {

int ar = l*b;

System.out.println("The area is "+ar);

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

class triangle implements shape {

int b,h;

Scanner sc = new Scanner(System.in);

public void getSides() {

System.out.println("Enter the base and height");

b = sc.nextInt();

h = sc.nextInt();

public void area() {

int ar = b*h/2;

System.out.println("The area is "+ar);

class derived2 extends rectangle{

public void getSides() {

System.out.println("Inside derived class");

public class JavaApplication37 {

public static void main(String[] args) {

rectangle r = new rectangle();

triangle t = new triangle();

r.getSides();

r.area();

t.getSides();

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

t.area();

rectangle d = new derived2();

d.getSides();

Output:

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Experiment-31

Aim: Write a program that creates interface and implements it.

Code:
package javaapplication41;

import java.util.*;

interface shape {

public void getSides();

public void area();

class rectangle implements shape {

int l , b;

Scanner sc = new Scanner(System.in);

public void getSides() {

System.out.println("Enter the sides of rectangle");

l = sc.nextInt();

b = sc.nextInt();

public void area() {

int ar = l*b;

System.out.println("The area is "+ar);

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

class triangle implements shape {

int b,h;

Scanner sc = new Scanner(System.in);

public void getSides() {

System.out.println("Enter the base and height");

b = sc.nextInt();

h = sc.nextInt();

public void area() {

int ar = b*h/2;

System.out.println("The area is "+ar);

public class JavaApplication41 {

public static void main(String[] args) {

rectangle r = new rectangle();

triangle t = new triangle();

r.getSides();

r.area();

t.getSides();

t.area();

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Output:

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

Experiment-32

Aim: Write a program to illustrate interface inheritance.

Code:
package javaapplication42;

import java.util.*;

interface interfaceA {

void Name();

interface interfaceB extends interfaceA {

void Institute();

class class1 implements interfaceB {

public void Name() {

System.out.println("Inside NAme()");

public void Institute() {

System.out.println("Inside Institute()");

public class JavaApplication42 {

public static void main(String[] args) {

class1 c = new class1();

Aakash Garg 20414802718


ETCS-357 3rd November, 2020

c.Name();

c.Institute();

Output:

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Lab-7

Topics Covered:
• Exception Handling
• Applet

Exception Handling:
An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e. at run time, which disrupts the normal flow of the program’s instructions.

All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. NullPointerException is an example of such an exception. Another
branch, Error are used by the Java run-time system (JVM) to indicate errors having to do with
the run-time environment itself (JRE). StackOverflowError is an example of such an error.

Whenever inside a method, if an exception has occurred, the method creates an Object known
as Exception Object and hands it off to the run-time system (JVM). The exception object
contains name and description of the exception, and current state of the program where
exception has occurred. Creating the Exception Object and handling it to the run-time system is
called throwing an Exception.

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Briefly, here is how they work. Program statements that you think can raise exceptions are
contained within a try block. If an exception occurs within the try block, it is thrown. Your code
can catch this exception (using catch block) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system. To manually
throw an exception, use the keyword throw. Any exception that is thrown out of a method
must be specified as such by a throws clause. Any code that absolutely must be executed after
a try block completes is put in a finally block.

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Applet:
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server. Applets are used to make the web site more dynamic
and entertaining.

Important points:

• All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.


• Applets are not stand-alone programs. Instead, they run within either a web browser or
an applet viewer. JDK provides a standard applet viewer tool called applet viewer.
• In general, execution of an applet does not begin at main() method.
• Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().

Life cycle of an applet:

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Lab – 7 : List Of Experiments :

• Write an application that shows how to create a user-defined exception.


• Create a customized exception and also make use of all the 5 exception
keywords.
• Write an Applet that displays “Hello World” (Background color-black, text
color-blue and your name in the status window).
• Develop an analog clock using applet.

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Experiment-33

Aim: Write an application that shows how to create a user-defined exception.

Code:
package javaapplication2;

class myException extends Exception {

private int detail;

myException(int a) {

detail = a;

public String toString() {

return "myException[" + detail + "]";

public class JavaApplication2 {

static void commute(int a) throws myException {

System.out.println("called Compute["+a+"]");

if(a>10) {

throw new myException(a);

System.out.println("Normal Exit");

public static void main(String[] args) {

try {

Aakash Garg 20414802718


ETCS-357 18th November, 2020

commute(1);

commute(20);

catch(myException e) {

System.out.println("Caught "+ e);

Output:

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Experiment-34

Aim: Create a customized exception and also make use of all the 5 exception
keywords.

Code:
package javaapplication2;

class myException extends Exception {

private int detail;

myException(int a) {

detail = a;

public String toString() {

return "myException[" + detail + "]";

public class JavaApplication2 {

static void commute(int a) throws myException {

System.out.println("called Compute["+a+"]");

if(a>10) {

throw new myException(a);

System.out.println("Normal Exit");

Aakash Garg 20414802718


ETCS-357 18th November, 2020

public static void main(String[] args) {

try {

commute(9);

commute(25);

catch(myException e) {

System.out.println("Caught "+ e);

finally {

System.out.println("Inside Finally");

Output:

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Experiment-35

Aim: Write an Applet that displays “Hello World” (Background color-black, text
color-blue and your name in the status window).

Code:
import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Color;

/*

<applet code="HelloWorld" width=200 height=60>

</applet>

*/

public class HelloWorld extends Applet {

public void init() {

setBackground(Color.BLACK);

@Override

public void paint(Graphics g) {

g.setColor(Color.BLUE);

g.drawString("Hello World", 20, 20);

showStatus("Aakash Garg");

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Output:

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Experiment-36

Aim: Develop an analog clock using applet.

Code:
import java.applet.Applet;

import java.awt.*;

import java.util.*;

/*

<applet code="analogClock" width="200" height="60">

</applet>

*/

public class analogClock extends Applet {

@Override

public void init()

this.setSize(new Dimension(800, 400));

setBackground(new Color(50, 50, 50));

new Thread() {

@Override

public void run()

while (true) {

repaint();

Aakash Garg 20414802718


ETCS-357 18th November, 2020

}.start();

@Override

public void paint(Graphics g)

Calendar time = Calendar.getInstance();

int hour = time.get(Calendar.HOUR_OF_DAY);

int minute = time.get(Calendar.MINUTE);

int second = time.get(Calendar.SECOND);

if (hour > 12) {

hour -= 12;

g.setColor(Color.white);

g.fillOval(300, 100, 200, 200);

g.setColor(Color.black);

g.drawString("12", 390, 120);

g.drawString("9", 310, 200);

g.drawString("6", 400, 290);

g.drawString("3", 480, 200);

double angle;

int x, y;

angle = Math.toRadians((15 - second) * 6);

x = (int)(Math.cos(angle) * 100);

Aakash Garg 20414802718


ETCS-357 18th November, 2020

y = (int)(Math.sin(angle) * 100);

g.setColor(Color.red);

g.drawLine(400, 200, 400 + x, 200 - y);

angle = Math.toRadians((15 - minute) * 6);

x = (int)(Math.cos(angle) * 80);

y = (int)(Math.sin(angle) * 80);

g.setColor(Color.blue);

g.drawLine(400, 200, 400 + x, 200 - y);

angle = Math.toRadians((15 - (hour * 5)) * 6);

x = (int)(Math.cos(angle) * 50);

y = (int)(Math.sin(angle) * 50);

g.setColor(Color.black);

g.drawLine(400, 200, 400 + x, 200 - y);

Aakash Garg 20414802718


ETCS-357 18th November, 2020

Output:

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Lab-8

Topics Covered:
• Multithreading

Multithreading:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.

Threads can be created by using two mechanisms:


1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class: User create a class that extends
the java.lang.Thread class. This class overrides the run() method available in the Thread class. A
thread begins its life inside run() method. User create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread
object.

Thread creation by implementing the Runnable Interface: User create a new class which
implements java.lang.Runnable interface and override run() method. Then user instantiate a
Thread object and call start() method on this object.

Thread Class vs. Runnable Interface:


1. If we extend the Thread class, the class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still
extend other base classes.
2. User can achieve basic functionality of a thread by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Lab – 8 : List Of Experiments :

• Write a java program to show multithreaded producer and consumer


application.
• Write an application that executes two threads. One thread displays
“An” every 1000 milliseconds and other displays “B” every 3000
milliseconds. Create the threads by extending the Thread class.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-37

Aim: Write a java program to show multithreaded producer and consumer


application.

Code:
package javaapplication2;

class CubbyHole {

private int contents;

private boolean available = false;

public synchronized int get() {

while (available == false) {

try {

wait();

} catch (InterruptedException e) {}

available = false;

notifyAll();

return contents;

public synchronized void put(int value) {

while (available == true) {

try {

wait();

Aakash Garg 20414802718


ETCS-357 25th November, 2020

} catch (InterruptedException e) { }

contents = value;

available = true;

notifyAll();

class Consumer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Consumer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

public void run() {

int value = 0;

for (int i = 0; i < 10; i++) {

value = cubbyhole.get();

System.out.println("Consumer #" + this.number + " got: " + value);

class Producer extends Thread {

private CubbyHole cubbyhole;

private int number;

Aakash Garg 20414802718


ETCS-357 25th November, 2020

public Producer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

public void run() {

for (int i = 0; i < 10; i++) {

cubbyhole.put(i);

System.out.println("Producer #" + this.number + " put: " + i);

try {

sleep((int)(Math.random() * 100));

} catch (InterruptedException e) { }

public class JavaApplication2 {

public static void main(String[] args) {

CubbyHole c = new CubbyHole();

Producer p1 = new Producer(c, 1);

Consumer c1 = new Consumer(c, 1);

p1.start();

c1.start();

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Output:

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-38

Aim: Write an application that executes two threads. One thread displays “An”
every 1000 milliseconds and other displays “B” every 3000 milliseconds. Create
the threads by extending the Thread class.

Code:
package javaapplication2;

class newThread extends Thread {

int time;

String name;

newThread(int myTime, String myName) {

time = myTime;

name = myName;

start();

public void run() {

try {

for(int i=0;i<5;i++) {

System.out.println(name);

Thread.sleep(time);

catch(InterruptedException e) {

System.out.println("Execution Interrupted");

Aakash Garg 20414802718


ETCS-357 25th November, 2020

public class JavaApplication2 {

public static void main(String[] args) {

newThread ob1 = new newThread(1000,"An");

newThread ob2 = new newThread(3000,"B");

try{

Thread.sleep(15000);

catch(InterruptedException e) {

System.out.println("Execution Interrupted");

Output:

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Lab-9

Topics Covered:
• AWT Components
• Event Handling

AWT Components:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java. Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS. The java.awt package provides classes for AWT api such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. The hierarchy of Java
AWT classes are given below.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Event Handling:
Event: Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page are the activities that
causes an event to happen.

Types of Event:

Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.

Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.

Event Handling: Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism has the code which is known as event
handler that is executed when an event occurs. Java Uses the Delegation Event Model to
handle the events. This model defines the standard mechanism to generate and handle the
events.

The Delegation Event Model has the following key participants namely:

Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to its handler. Java provide as with classes for source object.

Listener - It is also known as event handler.Listener is responsible for generating response to an


event. From java implementation point of view the listener is also an object. Listener waits until
it receives an event. Once the event is received, the listener processes the event and then
returns.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Lab – 9 : List Of Experiments :

• Write a program that illustrates how to process mouse click, enter, exit,
press and release events. The background color changes when the mouse is
entered, clicked, pressed, released or exited.
• Write a program that displays your name whenever the mouse is clicked.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-39

Aim: Write a program that illustrates how to process mouse click, enter, exit,
press and release events. The background color changes when the mouse is
entered, clicked, pressed, released or exited.

Code:
package javaapplication3;

import java.awt.*;

import java.awt.event.*;

public class JavaApplication3 extends Frame implements MouseListener

public JavaApplication3( )

addMouseListener(this);

setSize(300,300);

setVisible(true);

public void mousePressed(MouseEvent e)

setBackground(Color.red);

System.out.println("Mouse is Pressed");

public void mouseReleased(MouseEvent e)

Aakash Garg 20414802718


ETCS-357 25th November, 2020

setBackground(Color.blue);

System.out.println("Mouse is Released");

public void mouseClicked(MouseEvent e)

setBackground(Color.green);

System.out.println("Mouse is Clicked");

public void mouseEntered(MouseEvent e)

setBackground(Color.cyan);

System.out.println("Mouse is Entered");

public void mouseExited(MouseEvent e)

setBackground(Color.magenta);

System.out.println("Mouse is Exited");

public static void main(String args[])

new JavaApplication3();

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Output:

Exit Enter

Pressed Released

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-40

Aim: Write a program that displays your name whenever the mouse is clicked.

Code:
package javaapplication5;

import java.awt.*;

import java.awt.event.*;

public class JavaApplication5 extends Frame implements MouseListener{

Label l;

JavaApplication5(){

addMouseListener(this);

l=new Label();

l.setBounds(20,50,100,20);

add(l);

setSize(300,300);

setLayout(null);

setVisible(true);

public void mouseClicked(MouseEvent e) {

l.setText("Aakash Garg");

public void mouseEntered(MouseEvent e) {

Aakash Garg 20414802718


ETCS-357 25th November, 2020

public void mouseExited(MouseEvent e) {

public void mousePressed(MouseEvent e) {

public void mouseReleased(MouseEvent e) {

public static void main(String[] args) {

new JavaApplication5();

Output:

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Lab-10

Topics Covered:
• File Handling
• JDBC

File Handling:
Java FileWriter and FileReader classes are used to write and read data from text files (they
are Character Stream classes).

FileWriter is useful to create a file writing characters into it.

• This class inherits from the OutputStream class.


• The constructors of this class assume that the default character encoding and the
default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
• FileWriter is meant for writing streams of characters. For writing streams of raw bytes,
consider using a FileOutputStream.
• FileWriter creates the output file , if it is not present already.

FileReader is useful to read data in the form of characters from a ‘text’ file.

• This class inherit from the InputStreamReader Class.


• The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
• FileReader is meant for reading streams of characters. For reading streams of raw bytes,
consider using a FileInputStream.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

JDBC:
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX. JDBC stands for Java Database Connectivity, which is a
standard Java API for database-independent connectivity between the Java programming
language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

• Making a connection to a database.


• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as −

• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Lab – 10 : List Of Experiments :

• Write a program that read from a file and write to file.


• Convert the content of a given file into the uppercase content of the same
file.
• JDBC (Database connectivity with MS-Access)

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-41

Aim: Write a program that read from a file and write to file.

Code:
package javaapplication6;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.FileReader;

import java.io.IOException;

public class JavaApplication6 {

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

String str = "File handling in Java. Writing a character stream using fileWriter.";

FileWriter fw=new FileWriter("output.txt");

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

fw.write(str.charAt(i));

System.out.println("Writing successful");

fw.close();

int ch;

FileReader fr = new FileReader("output.txt");

while ((ch=fr.read())!=-1)

System.out.print((char)ch);

fr.close();

}}

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Output:

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-42

Aim: Write a program to convert the content of a given file into the uppercase
content of the same file.

Code:
package javaapplication6;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.FileReader;

import java.io.IOException;

public class JavaApplication6 {

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

int ch;

FileWriter fw=new FileWriter("output2.txt");

FileReader fr = new FileReader("output.txt");

while((ch=fr.read())!=-1) {

if(Character.isLowerCase(ch)) {

fw.write(Character.toUpperCase(ch));

else {

fw.write(ch);

Aakash Garg 20414802718


ETCS-357 25th November, 2020

fw.close();

fr.close();

FileReader r = new FileReader("output2.txt");

FileWriter w = new FileWriter("output.txt");

while ((ch=r.read())!=-1) {

w.write(ch);

w.close();

r.close();

FileReader f = new FileReader("output.txt");

while ((ch=f.read())!=-1)

System.out.print((char)ch);

f.close();

Output:

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Experiment-43

Aim: JDBC (Database connectivity with MS-Access)

Code:
package javaapplication8;

import java.sql.*;

public class JavaApplication8 {

public static void main(String[] args) {

try{

String database="student.mdb";

String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=" + database +


";DriverID=22;READONLY=true";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection(url);

Statement st=c.createStatement();

System.out.println(“Database Connected Successfully”);

ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){

System.out.println(rs.getString(1));

}catch(Exception ee){System.out.println(ee);}

Aakash Garg 20414802718


ETCS-357 25th November, 2020

Output:

Aakash Garg 20414802718

You might also like