Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Java Lab Manual 2021-22

Uploaded by

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

Java Lab Manual 2021-22

Uploaded by

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

KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

JAVA PROGRAMMING LAB - MANUAL

Exercise - 1 (Basics)
a). Write a JAVA program to display default value of all primitive data type of JAVA

class DefaultValues
{
static int i;
static float f;
static short s;
static byte by;
static long l;
static double d;
static char c;
static boolean b;
public static void main(String args[])
{
System.out.println("Integer Category");
System.out.println(" Integer = "+i);
System.out.println(" Short = "+s);
System.out.println(" Long = "+l);
System.out.println(" Byte = "+by);
System.out.println("Real values Category");
System.out.println(" Float = "+f);
System.out.println(" Double = "+d);
System.out.println("Character Category");
System.out.println(" Character = "+c);
System.out.println("Boolean Category");
System.out.println(" B = "+b);
} }

OUTPUT:
Integer Category
Integer = 0
Short = 0
Long = 0
Byte = 0
Real values Category
Float = 0.0
Double = 0.0
Character Category
Character =
Boolean Category
B = false

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 1


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

b). Write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.

import java.lang.*;
import java.util.*;

class rootdemo
{
public static void main(String args[])
{
int a,b,c,d;
double r1,r2;
System.out.println("Enter a,b,c values in ax^2+bx+c:");
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=(b*b)-(4*a*c);
if(d>0)
{
System.out.println("The roots are real and unequal");
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
System.out.println("The Roots are::" +r1 + " " +r2);
}
if(d==0)
{
System.out.println("The roots are real and equal");
r1=r2=(-b)/(2*a);
System.out.println("The Roots are::" +r1 +" " +r2);
}
if(d<0)
{
System.out.println(" No Roots");
}
}
}
OUTPUT:
java Roots 1 2 1
Roots are real and equal
Root1 = -1.0
Root2 = -1.0

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 2


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

c). Five Bikers Compete in a race such that they drive at a constant speed which may or
may not be the same as the other. To qualify the race, the speed of a racer must be more
than the average speed of all 5 racers. Take as input the speed of each racer and print
back the speed of qualifying racers.

import java.lang.*;
import java.util.*;

class race
{
public static void main(String args[])
{
double s1=65.5, s2=75.5, s3=52.8, s4=50.2, s5=65.1, avg;
avg=(s1+s2+s3+s4+s5)/5;
System.out.println("Average speed is::" +avg);
if(s1>avg)
System.out.println("s1 Qualified");
if(s2>avg)
System.out.println("s2 Qualified");
if(s3>avg)
System.out.println("s3 Qualified");
if(s4>avg)
System.out.println("s4 Qualified");
if(s5>avg)
System.out.println("s5 Qualified");
}}
OUTPUT
E:\KK>java race
Average speed is::61.82000000000001
s1 Qualified
s2 Qualified
s5 Qualified

d) Write a case study on public static void main (250 words)

The public keyword is an access specifier, which allows the programmer to control
the visibility of class members. When a class member is preceded by public, then
that member may be accessed by code outside the class in which it is declared. (The opposite
of public is private, which prevents a member from being used by code defined outside of its
class.)

In this case, main( ) must be declared as public, since it must be called by code outside of its
class when the program is started. The keyword static allows main( ) to be called without
having to instantiate a particular instance of the class. This is necessary since main( ) is called
by the Java interpreter before any objects are made. The keyword voidsimply tells the
compiler that main( ) does not return a value. As you will see, methods may also return
values.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 3


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

As stated, main( ) is the method called when a Java application begins. Keep in mind that
Java is case-sensitive. Thus, Main is different from main. It is important to understand that
the Java compiler will compile classes that do not contain a main( ) method. But the Java
interpreter has no way to run these classes. So, if you had typed Maininstead of main, the
compiler would still compile your program. However, the Java interpreter would report an
error because it would be unable to find the main( ) method.

Any information that you need to pass to a method is received by variables specified within
the set of parentheses that follow the name of the method. These variables
are calledparameters. If there are no parameters required for a given method, you still need to
include the empty parentheses. Inmain( ), there is only one parameter, but a complicated
one.String args[ ] declares a parameter named args, which is an array of instances of the
class String. (Arrays are collections of similar objects.) Objects of type String store character
strings. In this case, args receives any command-line arguments present when the program is
executed.

Exercise - 2 (Operations, Expressions, Control-flow, Strings)


a). Write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
} }
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
} }

OUTPUT
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 4
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

E:\KK>java race
Element is found at index: 2

b). Write a JAVA program to sort for an element in a given list of elements using
bubble sort

import java.lang.*;
import java.util.*;
class bubblesort
{
static public void main(String args[])
{
int i,j,temp;
int a[]=new int[5];
System.out.println("Enter elements to array:");
Scanner sc=new Scanner(System.in);
for(i=0;i<5;i++)
a[i]=sc.nextInt();
System.out.println("The elements in the array is:");
for(i=0;i<5;i++)
System.out.println(+a[i]);
for(i=0;i<4;i++)
{
for(j=1;j<(4-i);j++)
{
if(a[j-1]>a[j])
{
temp=a[j-1];
a[j-1]=a[j];
a[j]=temp;
}}}
System.out.print("After Sorting::");
for(i=0;i<5;i++)
System.out.println(+a[i]);
}}
OUTPUT:
Enter Elements to the array: 3 60 35 2 45 320 5
The Elements in the array is: 3 60 35 2 45 320 5
After Sorting: 2 3 5 35 45 60 320
(c). Write a JAVA program to sort for an element in a given list of elements using merge
sort.
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 5


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

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


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{ if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
} k++; }
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;

// Sort first and second halves


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

merge(arr, l, m, r);
}}
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 6


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

int arr[] = {12, 11, 13, 5, 6, 7};


int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}
OUTPUT:
Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

Exercise - 3 (Class, Objects)


a). Write a JAVA program to implement class mechanism. – Create a class, methods
and invoke them inside main method.
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
void displayLightStatus() {

System.out.println("Light on? " + isOn);


}}
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(), l2 = new Lamp();
l1.turnOn();
l2.turnOff();
l1.displayLightStatus();
l2.displayLightStatus();
}
}
OUTPUT:

Light on? true


Light on? False

b). Write a JAVA program to implement constructor.


import java.io.*;
class Geek

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 7


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

{
int num;
String name;
Geek()
{
System.out.println("Constructor called");
}}

class GFG
{
public static void main (String[] args)
{
Geek geek1 = new Geek();
System.out.println(geek1.name);
System.out.println(geek1.num);
}}

OUTPUT :
Constructor called
null
0

Exercise - 4 (Methods)
a). Write a JAVA program to implement constructor overloading.
class StudentData
{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getStuName() {
return stuName;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 8


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
public static void main(String args[])
{
StudentData myobj = new StudentData();
System.out.println("Student Name is: "+myobj.getStuName());
System.out.println("Student Age is: "+myobj.getStuAge());
System.out.println("Student ID is: "+myobj.getStuID());
StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
System.out.println("Student Name is: "+myobj2.getStuName());
System.out.println("Student Age is: "+myobj2.getStuAge());
System.out.println("Student ID is: "+myobj2.getStuID());
}}

OUTPUT:
Student Name is: New Student
Student Age is: 18
Student ID is: 100
Student Name is: Chaitanya
Student Age is: 25
Student ID is: 555

b). Write a JAVA program implement method overloading.


class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

OUTPUT: 22 33

Exercise - 5 (Inheritance)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 9


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

a). Write a JAVA program to implement Single Inheritance


class SingleInheritance{
static int num1=10;
static int num2=5;
}
class MainInheritance extends SingleInheritance{
public static void main(String[] args){
int num3=2;
int result=num1+num2+num3;
System.out.println("Result of child class is "+result);
}}
OUTPUT
Result of child class is 17

b). Write a JAVA program to implement multi level Inheritance


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
OUTPUT:
weeping...
barking...
eating...

c). Write a java program for abstract class to find areas of different shapes
import java.util.Scanner;

abstract class calcArea {


abstract void findTriangle(double b, double h);
abstract void findRectangle(double l, double b);
abstract void findSquare(double s);
abstract void findCircle(double r);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 10


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

class findArea extends calcArea {

void findTriangle(double b, double h)


{
double area = (b*h)/2;
System.out.println("Area of Triangle: "+area);
}
void findRectangle(double l, double b)
{
double area = l*b;
System.out.println("Area of Rectangle: "+area);
}
void findSquare(double s)
{
double area = s*s;
System.out.println("Area of Square: "+area);
}
void findCircle(double r)
{
double area = 3.14*r*r;
System.out.println("Area of Circle: "+area);
}}
class area {
public static void main(String args[])
{
double l, b, h, r, s;
findArea area = new findArea();
Scanner get = new Scanner(System.in);
System.out.print("\nEnter Base & Vertical Height of Triangle: ");
b = get.nextDouble();
h = get.nextDouble();
area.findTriangle(b, h);
System.out.print("\nEnter Length & Breadth of Rectangle: ");
l = get.nextDouble();
b = get.nextDouble();
area.findRectangle(l, b);
System.out.print("\nEnter Side of a Square: ");
s = get.nextDouble();
area.findSquare(s);
System.out.print("\nEnter Radius of Circle: ");
r = get.nextDouble();
area.findCircle(r);
}}

OUTPUT:
Enter base & Vertical height of Triangle: 5 4
Area of Triangle: 10.0

Enter Length & Breadth of Rectangle: 3 4


Area of Rectangle: 12.0

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 11


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

Enter Side of a Square: 5


Area of Square: 25.0

Enter Radius of Circle: 2


Area of Circle: 12.56

Exercise - 6 (Inheritance - Continued)


a). Write a JAVA program give example for “super” keyword.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
} }
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

OUTPUT:
eating...
barking...

b). Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}

OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 12
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

drawing circle

Exercise - 7 (Exception)
a).Write a JAVA program that describes exception handling mechanism
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}

OUTPUT:
ArrayIndexOutOfBounds

b).Write a JAVA program Illustrating Multiple catch clauses


public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
}
catch(Exception e){System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}
Test it Now
OUTPUT:

task1 completed
rest of the code...

Exercise – 8 (Runtime Polymorphism)


a). Write a JAVA program that implements Runtime polymorphism

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 13


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}}
public class XYZ extends ABC{
public void myMethod(){
System.out.println("Overriding Method");
}
public static void main(String args[]){
ABC obj = new XYZ();
obj.myMethod();
}
}
OUTPUT:

Overriding Method

b). Write a Case study on run time polymorphism, inheritance that implements in above
problem

Here we will see types of polymorphism. There are two types of polymorphism in java:

1) Static Polymorphism also known as compile time polymorphism


2) Dynamic Polymorphism also known as runtime polymorphism

Compile time Polymorphism (or Static polymorphism)


Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same name, if
the parameters of methods are different in number, sequence and data types of parameters.
We have already discussed Method overloading here: If you didn’t read that guide, refer:
Method Overloading in Java

Example of static Polymorphism


Method overloading is one of the way java supports static polymorphism. Here we have two
definitions of the same method add() which add method would be called is determined by the
parameter list at the compile time. That is the reason this is also known as compile time
polymorphism.

class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 14


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

public class Demo


{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
OUTPUT:
30
60

Runtime Polymorphism (or Dynamic polymorphism)


It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which
a call to an overridden method is resolved at runtime, thats why it is called runtime
polymorphism. I have already discussed method overriding in detail in a separate tutorial,
refer it: Method Overriding in Java.

Example
In this example we have two classes ABC and XYZ. ABC is a parent class and XYZ is a
child class. The child class is overriding the method myMethod() of parent class. In this
example we have child class object assigned to the parent class reference so in order to
determine which method would be called, the type of the object would be determined at run-
time. It is the type of object that determines which version of the method would be called (not
the type of reference).

To understand the concept of overriding, you should have the basic knowledge of inheritance
in Java.

class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC{

public void myMethod(){


System.out.println("Overriding Method");
}
public static void main(String args[]){
ABC obj = new XYZ();
obj.myMethod();
}}
OUTPUT:
Overriding Method

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 15


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

When an overridden method is called through a reference of parent class, then type of the
object determines which method is to be executed. Thus, this determination is made at run
time.
Since both the classes, child class and parent class have the same method animalSound.
Which version of the method (child class or parent class) will be called is determined at
runtime by JVM.

Exercise – 9 (User defined Exception)


a). Write a JAVA program for creation of Illustrating throw
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
} }
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
} }}
OUTPUT:
Caught inside fun().
Caught in main.
b). Write a JAVA program for creation of Illustrating finally
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
} }
OUTPUT:
5
finally block is always executed
rest of the code...

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 16


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

c). Write a JAVA program for creation of Java Built-in Exceptions


Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions. exceptions-in-java

Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.

Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size
of the string

Examples of Built-in Exception:

Arithmetic exception
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 17


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

System.out.println ("Result = " + c);


}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}}

OUTPUT:
Can't divide a number by 0

NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
OUTPUT:

NullPointerException..

StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}

OUTPUT:

StringIndexOutOfBoundsException

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 18


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

FileNotFound Exception

//Java program to demonstrate FileNotFoundException


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://file.txt");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
OUTPUT:

File does not exist

NumberFormat Exception

// Java program to demonstrate NumberFormatException


class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

OUTPUT:

Number format exception

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 19


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

ArrayIndexOutOfBounds Exception

// Java program to demonstrate ArrayIndexOutOfBoundException


class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
OUTPUT:

Array Index is Out Of Bounds

d).Write a JAVA program for creation of User Defined Exception

class TestCustomException1{

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}

public static void main(String args[]){


try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}
}

OUTPUT:
Exception occured: InvalidAgeException:not valid
rest of the code...

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 20


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

Exercise – 10 (Threads)
a). Write a JAVA program that creates threads by extending Thread class .First thread
display “Good Morning “every 1 sec, the second thread displays “Hello “every 2
seconds and the third display “Welcome” every 3 seconds ,(Repeat the same by
implementing Runnable)
import java.lang.*;
import java.util.*;
import java.awt.*;
class One implements Runnable
{
One()
{
new Thread(this,"one").start();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{}
}
public void run()
{
for(;;)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{}
System.out.println("GOOD MORNING");
}}}
class Two implements Runnable
{
Two()
{
new Thread(this,"two").start();
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{}
}
public void run()
{
for(;;)
{
try{
Thread.sleep(2000);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 21


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

catch(InterruptedException e)
{}
System.out.println("HELLO");
}}}
class Three implements Runnable
{
Three()
{
new Thread(this,"Three").start();
try{
Thread.sleep(3000);
}
catch(InterruptedException e)
{}
}
public void run()
{
for(;;)
{
try{
Thread.sleep(3000);
}
catch(InterruptedException e)
{}
System.out.println("WELCOME");
}}}
class MyThread{
public static void main(String args[])
{
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
}}
OUTPUT:
GOOD MORNING
GOOD MORNING
HELLO
GOOD MORNING
GOOD MORNING
HELLO
GOOD MORNING
WELCOME
GOOD MORNING
HELLO
GOOD MORNING
GOOD MORNING
WELCOME
HELLO
GOOD MORNING
GOOD MORNING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 22


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

b). Write a program illustrating isAlive and join ()


class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
OUTPUT:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
c). Write a Program illustrating Daemon Threads.

public class DaemonThread extends Thread{

public DaemonThread(){
setDaemon(true);
}
public void run(){
System.out.println("Is this thread Daemon? - "+isDaemon());
}
public static void main(String a[]){
DaemonThread dt = new DaemonThread();

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 23


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

// even you can set daemon constrain here also


// it is like dt.setDeamon(true)
dt.start();
}
}

OUTPUT
Is this thread Daemon? – true

Exercise - 11 (Threads continuity)


a).Write a JAVA program Producer Consumer Problem

public class ProducerConsumerTest {


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();
}
}
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();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 24


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

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;
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) { }
}
}}
OUTPUT:
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 25


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

b).Write a case study on thread Synchronization after solving the above producer
consumer problem
Producer-Consumer solution using threads in Java
In computing, the producer–consumer problem (also known as the bounded-buffer problem)
is a classic example of a multi-process synchronization problem. The problem describes two
processes, the producer and the consumer, which share a common, fixed-size buffer used as a
queue.
 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty.
The next time the producer puts data into the buffer, it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be
awakened.
Recommended Reading- Multithreading in JAVA, Synchronized in JAVA , Inter-thread
Communication
Implementation of Producer Consumer Class
 A LinkedList list – to store list of jobs in queue.
 A Variable Capacity – to check for if the list is full or not
 A mechanism to control the insertion and extraction from this list so that we do not
insert into list if it is full or remove from it if it is empty.

Exercise – 12 (Packages)

a). Write a case study on including in class path in your os environment of your
package.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename


For example

javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 26


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

b). Write a JAVA program that import and use the defined your package in the
previous Problem
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

OUTPUT:
Hello

Exercise - 13 (Applet)
a).Write a JAVA program to paint like paint brush in applet.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "MouseDrag.class" width = 400 height = 300> </applet>
*/
public class MouseDrag extends Applet implements MouseMotionListener{

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 27


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

public void init(){


addMouseMotionListener(this);
setBackground(Color.red);
}

public void mouseDragged(MouseEvent me){


Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}

OUTPUT:

Compile: javac MouseDrag.java


Run : appletviewer MouseDrag.java

b) Write a JAVA program to display analog clock using Applet.


import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/*<applet code="DigitalClock.class" width="300" height="300"> </applet> */
public class DigitalClock extends Applet implements Runnable {

Thread t = null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init() {
setBackground( Color.green);
}
public void start() {
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 28
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

t = new Thread( this );


t.start();
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");


Date date = cal.getTime();
timeString = formatter.format( date );
repaint();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}
public void paint( Graphics g ) {
g.setColor( Color.blue );
g.drawString( timeString, 50, 50 );
}
}

OUTPUT:

c). Write a JAVA program to create different shapes and fill colors using Applet.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 29


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

import java.applet.*;
import java.awt.*;
/*<applet code="Shapes.class" width="300" height="300"> </applet> */
public class Shapes extends Applet {
int x = 300, y = 100, r = 50;
public void paint(Graphics g) {
g.drawLine(30,300,200,10);
g.drawOval(x-r,y-r,100,100);
g.drawRect(400,50,200,100);
}
}
OUTPUT:

Exercise - 14 (Event Handling)


Write a JAVA program that display the x and y position of the cursor movement using
Mouse.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MouseCursorXYLabel extends JFrame
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
displayJFrame();
}
});
}
static void displayJFrame()
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setTitle("Mouse Cursor with Label");

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 30


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

jFrame.setPreferredSize(new Dimension(400, 300));


jFrame.pack();
jFrame.setLocationRelativeTo(null);
final AlsXYMouseLabelComponent alsXYMouseLabel = new
AlsXYMouseLabelComponent();
JLayeredPane layeredPane = jFrame.getRootPane().getLayeredPane();
layeredPane.add(alsXYMouseLabel, JLayeredPane.DRAG_LAYER);
alsXYMouseLabel.setBounds(0, 0, jFrame.getWidth(), jFrame.getHeight());
jFrame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent me)
{
alsXYMouseLabel.x = me.getX();
alsXYMouseLabel.y = me.getY();
alsXYMouseLabel.repaint();
}
});
jFrame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
jFrame.setVisible(true);
} }
class AlsXYMouseLabelComponent extends JComponent
{
public int x;
public int y;
public AlsXYMouseLabelComponent() {
this.setBackground(Color.blue);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
String s = x + ", " + y;
g.setColor(Color.red);
g.drawString(s, x, y);
}}
OUTPUT:

Additional Programs

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 31


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

1. Write a Java program to multiply two given matrices?

public class MatrixMultiplicationExample


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


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

//multiplying and printing multiplication of 2 matrices


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

Compile by: javac MatrixMultiplicationExample.java

Run by: java MatrixMultiplicationExample

666
12 12 12
18 18 18

2. Write a java program on frame icon

package com.zetcode;
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class FrameIconEx extends JFrame
{
public FrameIconEx()
{

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 32


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

initUI();
}
private void initUI()
{
ImageIcon webIcon = new ImageIcon("web.png");
setIconImage(webIcon.getImage());
setTitle("Icon");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
FrameIconEx ex = new FrameIconEx();
ex.setVisible(true);
});
}
}

3. Fibonacci Series using recursion in java

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
}
}

VIVA QUESTIONS:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 33


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

1.What do you mean by Platform Independence?


Platform Independence you can run and compile program in one platform and can execute in any
other platform.
2.What is JIT Compiler?
Just-In-Time(JIT) compiler is used to improve the performance. JIT compiles parts of the byte code
that have similar functionality at the same time
3.What all memory areas are allocated by JVM?
Heap, Stack, Program Counter Register and Native Method Stack
4.What is the base class of all classes?
java.lang.Object
5.What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().
6.Use of finalize() method in java?
finalize() method is used to free the allocated resource.
7.List two java ID Es?
1.Eclipse, 2.Net beans and 3.IntelliJ
8.What are java buzzwords?
Java buzzwords explain the important features of java. They are Simple,Secured, Portable,
architecture neutral, high performance, dynamic, robust,interpreted etc.
9.Is byte code is similar to .obj file in C?
Yes, both are machine understandable codes No, .obj file directly understood by machine, byte code
requires JVM.
10.What are length and length( ) in Java?
Both gives number of char/elements, length is variable defined in Array class,length( ) is method
defined in String class.

VIVA QUESTIONS:
1.What is object cloning?
The object cloning is used to create the exact copy of an object.
2.When parseInt() method can be used?
This method is used to get the primitive data type of a certain String.
3.java.util.regex consists of which classes?
java.util.regex consists of three classes − Pattern class, Matcher class and PatternSyntaxException
class.
4.Which package is used for pattern matching with regular expressions?
java.util.regex package is used for this purpose.
5.Define immutable object?
An immutable object can‟t be changed once it is created.
6.Explain Set Interface?
It is a collection of element which cannot contain duplicate elements. The Set interface contains only
methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
7.What is function overloading?
If a class has multiple functions by same name but different parameters, it is known as Method
Overloading.
8.What is function overriding?
If a subclass provides a specific implementation of a method that is already provided by its parent
class, it is known as Method Overriding.
9.What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep()
method, it returns to the waiting state.
10.What are Wrapper classes?
These are classes that allow primitive types to be accessed as objects. Example: Integer, Character,
Double, Boolean etc.

VIVA QUESTIONS:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 34


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

1.What is an applet? How does applet differ from applications?


What is an applet? How does applet differ from applications? - A program that a Java enabled
browser can download and run is an Applet.
2.What are the attributes of Applet tags? Explain the purposes?
What are the attributes of Applet tags? - height: Defines height of applet, width: Defines width of
applet.
3.How will you initialize an Applet?
Write my initialization code in the applets init method or applet constructor.
4.What is the sequence for calling the methods by AWT for applets?
When an applet begins, the AWT calls the following methods, in this sequence:
►init()
►start()
►paint()
When an applet is terminated, the following sequence of method calls takes place :
►stop()
►destroy()
5.What is AppletStub Interface?
The applet stub interface provides the means by which an applet and the browser communicate. Your
code will not typically implement this interface.
6.What is the base class for all swing components?
JComponent (except top-level containers)
7.How will you communicate between two Applets?
All the applets on a given page share the same AppletContext. We obtain this applet context as
follows:
AppletContext ac = getAppletContext();
AppletContext provides applets with methods such as getApplet(name), getApplets(),
getAudioClip(url), getImage(url), showDocument(url) and showStatus(status).
8.What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation.
9.What is the meaning of immutable in terms of String?
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been
created, its value can't be changed.

VIVA QUESTIONS:
1.What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked
exceptions.
2.What is difference between Checked Exception and Unchecked Exception? i). Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.
ii). Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-
time.
3.What is the base class for Error and Exception?
Throwable.
4.What is finally block?
finally block is a block that is always executed
5.Can finally block be used without catch?
Yes, by try block. finally must be followed by either try or catch.
6.Is there any case when finally will not be executed?
finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal
error that causes the process to abort)
7.What is exception propagation ?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 35


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

Forwarding the exception object to the invoking method is known as exception propagation.
8.What is nested class?
A class which is declared inside another class is known as nested class. There are 4 types of nested
class member inner class, local inner class, annonymous inner class and static nested class.
9.What is nested interface ?
Any interface i.e. declared inside the interface or class, is known as nested interface. It is static by
default.
10.Can an Interface have a class?
Yes, they are static implicitely.

VIVA QUESTIONS
1)What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
oThreads share the same address space.
oThread is lightweight.
oCost of communication between process is low.
2)What is thread?
A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of
execution because each thread runs in a separate stack frame.
3)What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
4)What does join() method?
The join() method waits for a thread to die. In other words, it causes the currently running threads to
stop executing until the thread it joins with completes its task.
5)Is it possible to start a thread twice?
No, there is no possibility to start a thread twice. If we does, it throws an exception.
6)Can we call the run() method instead of start()?
yes, but it will not work as a thread rather it will work as a normal object so there will not be context-
switching between the threads.
7)What about the daemon threads?
The daemon threads are basically the low priority threads that provides the background support to the
user threads. It provides services to the user threads.
8)Can we make the user thread as daemon thread if thread is started?
No, if you do so, it will throw IllegalThreadStateException
9)What is shutdown hook?
The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can
use it perform clean up resource.
10)When should we interrupt a thread?
We should interrupt a thread if we want to break out the sleep or wait state of a thread.

VIVA QUESTIONS:
1.What is GUI?
GUI stands for Graphical User Interface.
-GUI allows uses to click, drag, select graphical objects such as icons, images, buttons etc.
-GUI suppresses entering text using a command line.
-Examples of GUI operating systems are Windows, Mac, Linux.
-GUI is user friendly and increases the speed of work by the end users.
-A novice can understand the functionalities of certain application through GUI.
2.What is the difference between HashSet and TreeSet?
HashSet maintains no order whereas TreeSet maintains ascending order.
3)What is the difference between Set and Map?
Set contains values only whereas Map contains key and values both.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 36


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

4)What is the difference between HashSet and HashMap?


HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated
but HashMap need to convert into Set to be iterated.
5)What is the difference between HashMap and TreeMap?
HashMap maintains no order but TreeMap maintains ascending order.
6)What is the difference between Collection and Collections?
Collection is an interface whereas Collections is a class. Collection interface provides normal
functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize
collection elements.
7)What is the advantage of generic collection?
If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.
8)What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value is known as hash-collision. Two different entries will be
kept in a single hash bucket to avoid the collision.
9)What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
10)What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

VIVA QUESTIONS:
1.What is abstraction?
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
Abstraction lets you focus on what the object does instead of how it does it.
2.What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and data into a single
unit.
3.What is abstract class?
A class that is declared as abstract is known as abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.
4.Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
5.Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final method.
6.Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
7.What is interface?
Interface is a blueprint of a class that have static constants and abstract methods.It can be used to
achieve fully abstraction and multiple inheritance.
8.Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract keywords can't be
used together.
9.Can an Interface be final?
No, because its implementation is provided by another class.
10.What is marker interface?
An interface that have no data member and method is known as a marker interface.For example
Serializable, Cloneable etc.

VIVA QUESTIONS:
1.polymorphism is a feature that allows
2.polymorphism is expressed by the phrases one interface methods.
3.Method override is the basis .
4.Java implements using dynamic method dispatch.
5.A super class reference variable can refer to a object.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 37


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

6.The type of object being referred to determines which version of an method.


7.Override methods allows java to support
8.Method override occurs only when the names and the type signature of the two methods are
9.When a method in the subclass has the same name and type as the method in the super class then the
method in the subclass is said to the method in the super class.
10.Difference between overloading and overriding is

VIVA QUESTIONS
1.MOUSE_CLICKED events occurs when
2.MOUSE_DRAGGED events occurs when
3.events occur when mouse enters a component.
4. events occur when the mouse exists a component
5.MOUSE_MOVED event occurs when
6.MOUSE_PRESSED even occurs when
7.The events occur when mouse was released.
8.The event occurs when mouse wheel is moved.
9.An event source is
10.A is an object that describes the state change in a source

VIVA QUESTIONS
1. is a package in which Hashtable class is available
2.split is a method used for
3.capacity of hashtable can be determined by
4. method is used to insert record in to hash table
5. method is used to know the number of entries in hash table
6.alternative to hashtable is
7. is used to remove all entries of hash table
8. Hash table can be enumerated using
9.Scanner class is present in package
10.Buffered Reader is available in package

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Page 38

You might also like