20vv1a1263 Java Record
20vv1a1263 Java Record
TECHNOLOGICAL UNIVERSITY
UNIVERSITY COLLEGE OF
ENGINEERING VIZIANAGARAM
Department of
INFORMATION TECHNOLOGY
Certificate
Certified that this is a Bonafide Record of practical work done by
Date:
Index
24
14 Write a java program for abstract class
to find areas of different shapes.
Write a JAVA program give example for
26
“super” keyword
15
Write a JAVA program to implement Interface.
28
What kind of Inheritance can be achieve
16
Write a JAVA program that describes
30
exception handling mechanism
17
Write a JAVA program Illustrating Multiple
32
catch clause
18
Write a JAVA program that implements
34
Runtime polymorphism
19
Write a JAVA program for creation of
35
Illustrating throw
20
Write a JAVA program for creation of
36
Illustrating finally
21
Write a JAVA program for creation of Java 37
Built-in Exceptions
22
Write a JAVA program for creation of User 39
Defined Exception
23
35
36
37
38
39
40
41
42
43
44
45
46
JAVA
PROGRAMMING
LAB
RECORD
BY 20VV1A1263,
2-1 B. TECH IT. (R20)
1
EXERCISE –1:(Basics)
A)AIM: Write a JAVA program to display default value of all primitive data type of JAVA
DESCRIPTION:
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java
1.Primitive data types - The primitive data types include boolean, char, byte, short,int,
long, float and double.
2.Non-primitive data types - The non-primitive data types include Classes, Interfaces, and
Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These
are the most basic data types available in Java language.
PROGRAM:
class primitive
{
static String s;
static int i;
static float f;
static double d;
static long l;
static boolean b;
public static void main(String[] args)
{
System.out.println("DEFAULT VALUES OF : ");
System.out.println("strings is : "+s);
System.out.println("integers is : "+i);
System.out.println("float is : "+f);
System.out.println("double is : "+d);
System.out.println("long is : "+l);
System.out.println("booleans is : "+b);
}
}
2
OUTPUT:
3
B)AIM: 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
DESCRIPTION:
• The standard form of a quadratic equation is:ax2 + bx + c = 0.
• Here, a, b, and c are real numbers and a can't be equal to 0.
• We can calculate the root of a quadratic by using the formula:x = (-b ± √(b2-4ac)) /
(2a)
• The ± sign indicates that there will be two roots:root1 = (-b + √(b2-4ac)) /
(2a)root1 = (-b - √(b2-4ac)) / (2a)
• The term b2-4ac is known as the determinant of a quadratic equation.
• It specifies the nature of roots.
• That is,
• •if determinant > 0, roots are real and different
• •if determinant == 0, roots are real and equal
• •if determinant < 0, roots are complex complex and different.
PROGRAM:
java.util.*;
class Nature
{
int d,a,b,c;
Nature(int x,int y,int z){
a = x;
b =import y;
c = z;
}
void disc(){
d = (int)Math.pow(b,2)-4*a*c;
}
void roots(){
if(d<0){
System.out.println("Roots are Imaginary.");
}
else{
if (d>0){
System.out.println("Roots are Real and Distinct.");
System.out.println("Roots are: "+(-b+Math.sqrt(d))/(2*a)+" "+(-b-
Math.sqrt(d))/(2*a));
}
else{
System.out.println("Roots are Real and Equal.");
System.out.println("Roots are: "+(-b+Math.sqrt(d))/(2*a)+" "+(-b-
Math.sqrt(d))/(2*a));
4
}
}
}
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
OUTPUT:
5
C)AIM: Five Bikers Compete in a race such thatthey 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 racer
DESCRIPTION:
• Given 5 Bike racers.
• Taking input from users from the users, we have to caluculate average speed which
can be done by summing all the speeds / total number of bike racers participated
which is :Sum of all Speeds / 5
• after caluculating the average speed, we have to compare each racer wether a
given racer is greater than the average or not and print their name as qualifying
racers which can be achieved by a simple for loop and if-else block
PROGRAM:
import java.util.*;
class racers{
int[] a = new int[5];
double avg;
Scanner s = new Scanner(System.in);
void input(){
for(int i = 1;i<=5;i++){
System.out.print("Input speed of racer "+i+": ");
a[i-1] = s.nextInt();
}
}
void avgs(){
int sum = 0;
for(int i=0;i<5;i++){
sum += a[i];
}
avg = sum/a.length;
for(int i =1;i<=5;i++)
{
if(a[i-1]>avg){
System.out.println("racer no "+i+" speed is: "+a[i-1]);
}
}
}
6
{
racers r = new racers();
r.input();
System.out.println("The list of Qualifying Racers are: ");
r.avgs();
}
}
OUTPUT:
7
EXERCISE –2:(Operations, Expressions, Control-flow,
Strings)
A)AIM: Write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
DESCRIPTION:
• Given a sorted array arr[] of n elements, write a function to search a given
element x in arr[].
• A simple approach is to do a linear search.
• The time complexity of the above algorithm is O(n).
• Another approach to perform the same task is using Binary Search.
• Binary Search: Search a sorted array by repeatedly dividing the search interval in
half. Begin with an interval covering the whole array. If the value of the search key
is less than the item in the middle of the interval, narrow the interval to the lower
half.
• Otherwise, narrow it to the upper half. Repeatedly check until the value is found or
the interval is empty.
• The idea of binary search is to use the information that the array is sorted and
reduce the time complexity to O(Log n).
• We basically ignore half of the elements just after one comparison.
• 1.Compare x with the middle element.
• 2.If x matches with the middle element, we return the mid index.
• 3.Else If x is greater than the mid element, then x can only lie in the right half
subarray after the mid element.
• So we recur for the right half.4.Else (x is smaller) recur for the left half.
PROGRAM:
class BinarySearch
8
{
void Binarysearch(int[] a,int s,int e,int k)
{
int mid;
while(s<=e)
{
mid = (s+e)/2;
if(a[mid]<k)
{
s=mid+1;
}
else if(a[mid]>k)
{
e = mid-1;
}
else
{
System.out.println("\nElement is Found at Index: "+mid);
return;
}
}
if(s>e)
{
System.out.println("\nElement is not Found");
}
OUTPUT:
9
10
B)AIM: Write a JAVA program to sort a given list of elements using bubble sort.
DESCRIPTION:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
PROGRAM:
class BubbleSort
{
void bubbleSort(int[] a)
{
int n = a.length;
int t = 0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(a[i]>a[j])
{
t = a[i];a[i]=a[j];a[j]=t;
}
}
}
}
public static void main(String[] args)
{
int a[] = {11,21,45,67,34,43,10,3,2,14};
System.out.println("");
b.bubbleSort(a);
11
}
}
OUTPUT:
12
C)AIM: Write a JAVA program to sort a given list of elements using merge sort
DESCRIPTION:
• Merge sort is the algorithm which follows divide and conquer approach.
• Consider an array A of n number of elements.
• The algorithm processes the elements in 3 steps.
• 1.If A Contains 0 or 1 elements then it is already sorted, otherwise, Divide A into
two sub-array of equal number of elements.
• 2.Conquer means sort the two sub-arrays recursively using the merge sort.
• 3.Combine the sub-arrays to form a single final sorted array maintaining the
ordering of the array.
• The main idea behind merge sort is that, the short list takes less time to be sorted
PROGRAM:
class MergeSort
{
void merge(int arr[],int l,int mid,int r)
{
int i,j,k;
int n1 = mid-l+1;
int n2 = r-mid;
int[] a = new int[n1];int[] b = new int[n2];
for(i=0;i<n1;i++)
{
a[i]=arr[l+i];
}
for(i=0;i<n2;i++)
{
b[i]=arr[mid+1+i];
}
i=0;j=0;k=l;
while(i<n1 && j<n2)
{
if(a[i] < b[j])
{
arr[k]=a[i];
k++;i++;
}
else
{
arr[k]=b[j];
k++;j++;
}
}
while(i<n1)
13
{
arr[k]=a[i];
k++;i++;
}
while(j<n2)
{
arr[k]=b[j];
k++;j++;
}
}
void Mergesort(int arr[],int l,int r)
{
if(l<r)
{
int mid = (l+r)/2;
Mergesort(arr,l,mid);
Mergesort(arr,mid+1,r);
merge(arr,l,mid,r);
}
}
public static void main(String[] args)
{
int[] a = {12,21,34,5,67,80,8,43,32,11};
int l=0;int r=a.length-1;
MergeSort m = new MergeSort();
System.out.print("The Un Sorted Array is: ");
for(int p=0;p<a.length;p++){
System.out.print(a[p]+" ");
}
System.out.println("");
m.Mergesort(a, l, r);
System.out.print("The Sorted Array is: ");
for(int p=0;p<a.length;p++){
System.out.print(a[p]+" ");
}
}
OUTPUT:
14
D)AIM: Write a JAVA program using String Buffer to delete, remove character.
DESCRIPTION:
import java.io.*;
class StrBuffer
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("This is a un deleted string.");
System.out.print("Original String: ");
System.out.println(s);
s.delete(9,12);
System.out.print("AFter Deletion String: ");
System.out.println(s);
}
}
OUTPUT:
15
EXERCISE –3:(Class, Objects)
DESCRIPTION:
• Class in Java
• A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
• A class in Java can contain:
•Fields
•Methods
•Constructors
•Blocks
•Nested class and interface
• Method in JavaIn Java, a method is like a function which is used to expose the
behavior of an object.Advantage of Method
•Code Reusability
•Code Optimization.
•
PROGRAM:
public class ClassMethods
{
static String s="Hello!";
void print_(){
System.out.println(s);
}
void add(int a,int b){
System.out.println("The Sum of Two numbers is: "+a+b);
}
public static void main(String[] args){
ClassMethods c = new ClassMethods();
c.print_();
c.add(8,0);
}
}
OUTPUT:
16
B)AIM: Write a JAVA program to implement constructor
DESCRIPTION:
• In Java, a constructor is a block of codes similar to the method. It is called when
an instance of the class is created.
• At the time of calling constructor, memory for the object is allocatedin the memory.
It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one constructor is
called. It calls a default constructor if there is no constructor available in the class.
• In such case, Java compiler provides a default constructor by default.
• There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
• Note: It is called constructor because it constructs the values at the time of object
creation.It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
•
PROGRAM:
class Constructors
{
// default constructor
Constructors()
{
System.out.println("Default Constructor");
}
// parametricized constructor
Constructors(float f,int i)
{
System.out.println("Parametricized Constructor");
}
public static void main(String[] args){
Constructors c = new Constructors();
Constructors c1 = new Constructors(8.97f,3);
}
}
OUTPUT:
17
EXERCISE –4:(Methods)
DESCRIPTION:
• In Java, a constructor is just like a method but without return type.
• It can also be overloaded like Java methods.
• Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists.
• They are arranged in a way that each constructor performs a different task.
• They are differentiated by the compiler by the number of parameters in the list and
their types
PROGRAM:
class ConsOver{
// default constructor
ConsOver(){
System.out.println("Constructor 1");
}
// parametricized constructors
// Overloading the constructor
ConsOver(int i,int j)
{
System.out.println("Constructor 2");
}
ConsOver(float f, int j){
System.out.println("Constructor 3");
}
ConsOver(float f, float j){
System.out.println("Constructor 4");
}
ConsOver(float f, int j, String s){
System.out.println("Constructor 5");
}
public static void main(String[] args){
ConsOver c = new ConsOver();
ConsOver c1 = new ConsOver(1,2);
ConsOver c2 = new ConsOver(2.3f,9);
ConsOver c3 = new ConsOver(7.2f,4.3f);
ConsOver c4 = new ConsOver(8.2f,6,"kishore");
}
}
OUTPUT:
18
19
B)AIM: Write a JAVA program implement method overloading.
DESCRIPTION:
• If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
• If we have to perform only one operation, having same name of the methods
increases thereadability of the program.
• Suppose we have to perform addition of the given numbers but there can be any
number of arguments, if we write the method such as a(int,int) for two parameters,
and b(int,int,int)for three parameters then it may be difficult for we as well as other
programmers to understand the behavior of the method because its name differs.
• So, we perform method overloading to figure out the program quick.
•
PROGRAM:
class MethodOver
{
void method()
{
System.out.println("method 1");
}
void method(float f)
{
System.out.println("method 2");
}
void method(String s)
{
System.out.println("method 3");
}
}
}
OUTPUT:
20
EXERCISE –5:(Inheritance)
DESCRIPTION:
• Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object.
• It is an important part of OOPs (Object Oriented programming system).
• The idea behind inheritance in Java is that we can create new classes that are built
upon existing classes.
• When we inherit from an existing class, we can reuse methods and fields of the
parent class.
• Moreover, we can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
childrelationship.Why use inheritance in java
•For Method Overriding (so runtime polymorphism can be achieved).
•For Code Reusability. Types of inheritance in javaOn the basis of class, there can
be three types of inheritance in java: single, multilevel and hierarchical.Single
Inheritance ExampleWhen a class inherits another class, it is known as a single
inheritance
PROGRAM:
class singleinheri{
public static void main(String args[]){
students st = new students();
System.out.println("MARKS OF STUDENT:");
System.out.println("Maths: "+st.m);
System.out.println("Chemistry: "+st.c);
System.out.println("Physics: "+st.p);
System.out.println("English: "+st.e);
System.out.println("Sanskrit: "+st.s);
}
}
class marks{
int m = 75;
int c = 59;
int p = 60;
int e = 77;
int s = 98;
}
class students extends marks{
//inherits all variables of class marks
}
OUTPUT:
21
22
B)AIM: Write a JAVA program to implement multi level Inheritance.
DESCRIPTION:
• When a class extends a class, which extends anther class then this is called
multilevel inheritance.
• For example class C extends class B and class B extends class A then this typeof
inheritance is known as multilevel inheritance.
• Multilevel inheritance there is a concept of grand parent class.
• If we take the example of this diagram, then class C inherits class B and class B
inherits class A which means B is a parent class of C and A is a parent class of B.
• So in this case class C is implicitly inheriting the properties and methods of class A
along with class B that’s what is called multilevel inheritance
•
PROGRAM:
public class mullvlinh {
public static void main(String[] args){
intrest cal = new intrest();
System.out.println("Intrest Amount to be paid is: "+cal.in);
}
}
class deposit{
static float bal = 70000f;
}
class inrate extends deposit{
static float i = 7.23f;
}
class intrest extends inrate{
static float in = (bal*i)/100;
}
OUTPUT:
23
C)AIM: Write a java program for abstract class to find areas of different shapes
DESCRIPTION:
• A class which is declared as abstract is known as an abstract class.
• It can have abstract and non-abstract methods. It needs to be extended and its
method implemented.
• It cannot be instantiated.
• Points to Remember
•An abstract class must be declared with an abstract keyword.
•It can have abstract and non-abstract methods.
•It cannot be instantiated.
•It can have constructors and static methods also.
•It can have final methods which will force the subclass not to change the body of
the method.
•
PROGRAM:
import java.util.*;
public class abstareas {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
extension sh = new extension();
sh.circle(s.nextInt());
sh.rectangle(s.nextInt(),s.nextInt());
sh.square(s.nextInt());
}
}
24
OUTPUT:
25
EXERCISE –6: (Inheritance -Continued)
A)AIM: Write a JAVA program give example for “super” keyword
DESCRIPTION:
• The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
• Whenever we create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
• Usage of Java super Keyword:
1.super can be used to refer immediate parent class instance variable.
2.super can be used to invoke immediate parent class method.
3.super() can be used to invoke immediate parent class constructo
•
PROGRAM:
class sup {
String s = "This is Super Class's Variable.";
void ntg(){
System.out.println("This is Super Class's method.");
}
sup(){
System.out.println("This is Super Class's Constructor.");
}
}
class Sub extends sup{
String s = "This is Sub Class's Variable.";
void ntg(){
System.out.println(super.s);
System.out.println("This is Sub Class's method.");
super.ntg();
}
Sub(){
System.out.println("This is Sub Class's Constructor.");
}
}
class superkey{
public static void main(String[] args){
Sub i = new Sub();
System.out.println(i.s);
i.ntg();
}
}
26
OUTPUT:
27
B)AIM: Write a JAVA program to implement Interface. What kind of Inheritance can be
achieve.
DESCRIPTION:
• An interface in Java is a blueprint of a class.
• It has static constants and abstract methods.
• The interface in Java is a mechanism to achieve abstraction.
• There can be only abstract methods in the Java interface, not method body.
• It is used to achieve abstraction and multiple inheritance in Java.In other words, we
can say that interfaces can have abstract methods and variables.
• It cannot have a method body.
• Java Interface also represents the IS-A relationship.It cannot be instantiated just
like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
PROGRAM:
interface Vehicle
{
void ChangeGear(int a);void SpeedUp(int b);void ApplyBrakes(int c);
}
28
}
class Interfaces
{
public static void main(String[] args)
{
Bicycle b = new Bicycle();
b.ChangeGear(3);b.SpeedUp(2);b.ApplyBrakes(2);
OUTPUT:
29
EXERCISE –7:(Exception)
DESCRIPTION:
• The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
• What is Exception in Java
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the program.
• It is an object which is thrown at runtime.
• What is Exception HandlingException :
• Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException.
•
PROGRAM:
import java.util.*;
class ExceptionHandling
{
a = s.nextInt();
b = s.nextInt();
30
System.out.println("The Division of Numbers is: "+a/b);
}
}
}
OUTPUT:
31
b)AIM: Write a JAVA program Illustrating Multiple catch clause
DESCRIPTION:
• In Java, a single try block can have multiple catch blocks. When statements in a
single try block generate multiple exceptions, we require multiple catch blocks to
handle different types of exceptions. This mechanism is called multi-catch block in
java.
• Each catch block is capable of catching a different exception.That is each catch
block mustcontain a different exception handler.
• Java multi-catch block acts as a case in a switch statement.In the above syntax, if
the exception object (ExceptionType1) is thrown by try block, the first catch block
will catch the exception object thrown and the remaining catch block will be
skipped.
• In case, exception object thrown does not match with the first catch block, the
second catch block will check, and so on.
• At a time only one exception occurs and at a time only one catch block is used.
• All catch blocks must be arranged in such a way that exception must come from the
first subclass and then superclass.
PROGRAM:
public class MultipleCatch
{ public static void main(String args[])
{
int[] arr = new int[]{0,1,3,9,10};
try
{
System.out.println("Dividing Two No's: "+arr[1]/arr[0]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception Occured.");
try
{
System.out.println("Accesing element in the array: "+arr[4]);
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("Array Index Out of Bound Exception Occured.");
}
}
32
System.out.println("No Abnormal Termination Occured.");
}
}
OUTPUT:
33
EXERCISE –8:(Runtime Polymorphism
a)AIM: Write a JAVA program that implements Runtime polymorphism
DESCRIPTION:
• Runtime Polymorphism in JavaRuntime polymorphism or Dynamic Method
Dispatch is a process in which a call to an overridden method is resolved at runtime
rather than compile-time.
• In this process, an overridden method is called through the reference variable of a
superclass.
• The determination of the method to be called is based on the object being referred
to by the reference variable.
• UpcastingIf the reference variable of Parent class refers to the object of Child class,
it is known as upcasting.
•
PROGRAM:
class RuntimePoly extends Base
{
void method()
{
System.out.println("Runtime Polymorphism");
}
public static void main(String[] args)
{
Base b = new RuntimePoly();
b.method();
}
}
class Base
{
void method()
{
System.out.println("Base");
}
}
OUTPUT:
34
EXERCISE –9:(User defined Exception)
a)AIM: Write a JAVA program for creation of Illustrating throw
DESCRIPTION:
• The throw keyword in Java is used to explicitly throw an exception from a method
or any block of code.
• We can throw either checked or unchecked exception. The throw keyword is mainly
used to throw custom exceptions.
• But this exception i.e, Instance must be of type Throwable or a subclass of
Throwable.
• . For example Exception is a sub-class of Throwable and user defined exceptions
typically extend Exception class.
• Unlike C++, data types such as int, char, floats or non-throwable classes cannot be
used as exceptions.
• The flow of execution of the program stops immediately after the throw statement is
executed and thenearest enclosing try block is checked to see if it has a catch
statement that matches the type of exception.
• If it finds a match, controlled is transferred to that statement otherwise next
enclosing try block is checked and so on.
• If no matching catch is found then the default exception handler will halt the
program.
PROGRAM:
class throwKeyWord
{ public static void main(String[] args)
{
try
{
throw new StringIndexOutOfBoundsException("Accesing Out of Index of array.");
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("Exception Occured : "+e);
}
}
}
OUTPUT:
35
b)AIM: Write a JAVA program for creation of Illustrating finally block.
DESCRIPTION:
• The finally block in java is used to put important codes such as clean up code e.g.
closing the file or closing the connection. The finally block executes whether
exception rise or not and whether exception handled or not.
• A finally contains all the crucial statements regardless of the exception occurs or
not.
• There are 3 possible cases where finally block can be used:
• Case 1: When an exception does not rise.
• Case 2: When the exception rises and handled by the catch block.
• Case 3: When exception rise and not handled by the catch blocks..
•
PROGRAM:
import java.io.FileNotFoundException;
class finallyKeyWord
{
public static void main(String[] args)
{
try
{
System.out.println("Inside try block.");
throw new FileNotFoundException("File Does't Exist.");
}
catch (FileNotFoundException e)
{
System.out.println("Inside catch block.");
System.out.println("Exception: "+e);
}
finally
{
System.out.println("I always execute.");
}
}
}
OUTPUT:
36
c)AIM: Write a JAVA program for creation of Java Built-in Exceptions
DESCRIPTION:
• 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.Examples of Built-in Exception:
• 1.Arithmetic exception : It is thrown when an exceptional condition has occurred in
an arithmetic operation.
• 2.ArrayIndexOutOfBounds Exception : 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.
• 3.ClassNotFoundException : This Exception is raised when we try to access a class
whose definition is not found.
• 4.FileNotFoundException : This Exception is raised when a file is not accessible or
does not open.
• 5.IOException : It is thrown when an input-output operation failed or interrupted.
• 6.InterruptedException : It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
• 7.NoSuchMethodException : It is thrown when accessing a method which is not
found.
• 8.NullPointerException : This exception is raised when referring to the members of
anull object. Null represents nothing.
• 9.NumberFormatException : This exception is raised when a method could not
convert a string into a numeric format.
• 10.StringIndexOutOfBoundsException : It is thrown by String class methods to
indicate that an index is either negative than the size of the string.
• 11.IllegalArgumentException : The Exception occurs explicitly either by the
programmer or by API developer to indicate that a method has been invoked with
Illegal Argument.
• 12.IllegalThreadStateException :
• The above exception rises explicitly either by programmer or by API developer to
indicate that a method has been invoked at wrong time.
• 13.AssertionError : The above exception rises explicitly by the programmer or by
API developer to indicate that assert statement fails.
•
PROGRAM:
import java.io.IOException;
class BuiltInException
{
public static void main(String[] args)
{
try
{
37
throw new IOException("IO Exception Occured.");
}
catch(IOException i)
{
System.out.println("Exception: "+i);
}
}
}
OUTPUT:
38
d)AIM: Write a JAVA program for creation of User Defined Exception
DESCRIPTION:
• If we are creating your own Exception that is known as custom exception or user-
defined exception.
• Java custom exceptions are used to customize the exception according to user need.
• By the help of custom exception, we can have your own exception and message.
• We do thisby extending our custom exception class with java Exception class and
throwing explicitly when needed.
•
PROGRAM:
39
EXERCISE –10:(Threads)
a)AIM: 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
DESCRIPTION:
PROGRAM:
class RT1 implements Runnable
{
public void run()
{
for(int i=0;i<8;i++)
{
try
40
{
System.out.println("Good Morning");
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted");
}
}
}
}
41
System.out.println("Thread is Interrupted");
}
}
}
}
class RunnableThreads
{
public static void main(String[] args)
{
Thread t1 = new Thread(new RT1());
Thread t2 = new Thread(new RT2());
Thread t3 = new Thread(new RT3());
t1.start();t2.start();t3.start();
}
}
OUTPUT:
42
b)AIM: Write a program illustrating isAlive and join .
DESCRIPTION:
PROGRAM:
class Thread1 extends Thread
{
public void run()
{
for(int i = 0; i < 8; i++)
{
System.out.println(i);
}
}
}
class AJ
{
public static void main(String[] args)
{
Thread1 t = new Thread1();
t.start();
System.out.println("t is alive: " + t.isAlive());
try
{
t.join();
}
catch(InterruptedException e)
{}
System.out.println("t is alive: " + t.isAlive());
}
}
OUTPUT:
43
44
c)AIM: Write a Program illustrating Daemon Threads
DESCRIPTION:
• Daemon thread in java is a service provider thread that provides services to the
user thread.
• Its life depend on the mercy of user threads i.e. when all the user threads dies,
JVMterminates this thread automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
• You can see all the detail by typing the jconsole in the command prompt.
• The jconsole tool provides information about the loaded classes, memory usage,
running threads etc.
• Points to remember for Daemon Thread in Java
•It provides services to user threads for background supporting tasks. It has no role
in life than to serve user threads.
•Its life depends on user threads.
•It is a low priority thread.
PROGRAM:
class Daemon extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println(this+" is a daemon thread.");
}
else
{
System.out.println(this+" is a user thread.");
}
}
public static void main(String[] args)
{
Daemon d = new Daemon();
Daemon d1 = new Daemon();
d.setDaemon(true);
d.start();
d1.start();
}
}
OUTPUT:
45
EXERCISE–11:(Threads continuity)
a)AIM: Write a JAVA program Producer Consumer Problem.
DESCRIPTION:
• 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.
•
PROGRAM:
class Producer extends Thread
{
StringBuffer sb = new StringBuffer();
public void run()
{
synchronized(sb)
{
for(int i=0;i<=10;i++)
{
sb.append(i+" : ");
System.out.println("Appending");
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{}
}
sb.notify();
}
}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
46
public void run()
{
synchronized(prod.sb)
{
try
{
prod.sb.wait();
}
catch(InterruptedException e)
{}
System.out.println("Data is: "+prod.sb);
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Producer p = new Producer();
Consumer c = new Consumer(p);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t2.start();
t1.start();
}
}
OUTPUT:
47
EXERCISE –12:(Packages)
a)AIM: Write a JAVA program illustrate class path.
DESCRIPTION:
PROGRAM:
public class EX_12_A {
public static void main(String[] args) {
String path = System.getProperty("java.class.path");
System.out.println("Class Path: " + path);
}
}
OUTPUT:
48
c)AIM: Write a JAVA program that import and use the defined your package in the
previous Problem.
PROGRAM:
package STR;
import java.util.*;
interface strings
{
void reverseString();
}
class Str implements strings
{
public void reverseString()
{
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.print("Enter String: ");
sb.append(sc.nextLine());
sb.reverse();
System.out.println();
System.out.print("Reversed String: "+sb);
}
}
public class StrRev extends Str
{
public static void main(String[] args)
{
}
}
import STR.StrRev;
public class string {
public static void main(String[] args)
{
StrRev s = new StrRev();
s.reverseString();
System.out.println();
}
}
OUTPUT:
49
EXERCISE –13:(Applet)
a)AIM: Write a JAVA program to paint like paint brush in applet.
DESCRIPTION:
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
OUTPUT:
50
51
b)AIM: Write a JAVA program to display analogyclock using Applet.
DESCRIPTION:
Analog clock can be created by using the Math class.
PROGRAM:
import java.applet.Applet;
import java.awt.*;
import java.util.*;
/*<applet code="analogClock" width=500 height=500></applet>*/
52
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;
g.setColor(Color.red);
g.drawLine(400, 200, 400 + x, 200 - y);
g.setColor(Color.blue);
g.drawLine(400, 200, 400 + x, 200 - y);
g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}
OUTPUT:
53
54
c)AIM: Write a JAVA program to create different shapes and fill colours using Applet.
DESCRIPTION:
• Following example demonstrates how to create an applet which will have fill
color in Various shapes using setColor(), fillRect() methods of Graphics class to fill
color in a shape.
•
PROGRAM:
import java.applet.Applet;
import java.awt.*;
/*<applet code='Shapes' width=500 height=500></applet>*/
public class Shapes extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0,0,100,150);
g.setColor(Color.blue);
g.fillRect(10,250,300,40);
g.setColor(Color.red);
g.drawOval(75,90,250,300);
g.fillOval(200,250,100,100);
g.draw3DRect(300, 150, 195, 195,false);
}
}
OUTPUT:
55
EXERCISE –14:(Event Handling)
a)AIM: Write a JAVA program that display the x and y positionof the cursor movement
using Mouse.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*<applet code='cursorPosition' width=300 height=300></applet>*/
public class cursorPosition extends Applet implements MouseMotionListener
{
int x,y;
String msg="";
public void init()
{
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
public void mouseMoved(MouseEvent m)
{
x=m.getX();y=m.getY();
msg = "Mouse Moved "+x+","+y;
repaint();
}
public void mouseDragged(MouseEvent m)
{
x = m.getX();
y = m.getY();
msg = "Mouse Dragged " + x + "," + y;
repaint();
}
}
OUTPUT:
56
b)AIM: Write a JAVA program that identifies key-up key-down event user entering text in
a Applet.
DESCRIPTION:
• Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing
is a part of Oracle’s Java foundation classes . Java Swing is an API for providing
graphical user interfaceelements to Java Programs.Swing was created to provide
more powerful and flexible components than Java AWT (Abstract Window Toolkit).
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*<applet code='keyEvent' width=300 height=300></applet>*/
public class keyEvent extends Applet implements KeyListener
{
int x=20,y=30;
String msg = "";
public void init()
{
addKeyListener(this);
//requestFocus();
}
public void keyPressed(KeyEvent k)
{
showStatus("Key Pressed");
msg = "Key Pressed";
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Released");
msg = "Key Released";
repaint();
}
public void keyTyped(KeyEvent k)
{
showStatus("Key Typed");
msg = "Key Typed";
repaint();
}
public void paint(Graphics g)
{
57
g.drawString(msg,x,y);
}
}
OUTPUT:
58