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

JPR Assignments 1-2-3

The document outlines a Java programming course with assignments covering topics such as basic syntax, inheritance, exception handling, and multithreading. It includes questions and answers on Java features, data types, operators, type casting, and object-oriented programming concepts. Additionally, it provides example programs for various tasks like calculating areas, checking prime numbers, and managing class structures.

Uploaded by

Chinmay Aher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

JPR Assignments 1-2-3

The document outlines a Java programming course with assignments covering topics such as basic syntax, inheritance, exception handling, and multithreading. It includes questions and answers on Java features, data types, operators, type casting, and object-oriented programming concepts. Additionally, it provides example programs for various tasks like calculating areas, checking prime numbers, and managing class structures.

Uploaded by

Chinmay Aher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Subject: Java Programming [314317]

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 1 of 42


Assignments
Chapter
Name of chapter
No.
1 Basic Syntactical constructs in Java

2 Inheritance, Interface and Package

3 Exception Handling, and Multithreading

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 2 of 42


Q.N. 1. BASIC SYNTACTICAL CONSTRUCTS IN JAVA
Q.1 List any eight features of Java.
Ans. Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic
2 Write all primitive data types available in Java with their storage Sizes in bytes.
Ans Data Size
Type
Byte 1 Byte
Short 2 Byte
Int 4 Byte
Long 8 Byte
Double 8 Byte
Float 4 Byte
Char 2 Byte
boolean 1 Bit
3 Explain the concept of platform independence and portability with respect to Java language.
(Note: Any other relevant diagram shall be considered).

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 3 of 42


Java is a platform independent language. This is possible because when a java program is compiled,
an intermediate code called the byte code is obtained rather than the machine code. Byte code is a
highly optimized set of instructions designed to be executed by the JVM which is the interpreter for
the byte code. Byte code is not a machine specific code. Byte code is a universal code and can be
moved anywhere to any platform. Therefore java is portable, as it can be carried to any platform.
JVM is a virtual machine which exists inside the computer memory and is a simulated computer
within a computer which does all the functions of a computer. Only the JVM needs to be
implemented for each platform. Although the details of
the JVM will defer from platform to platform, all interpret the same byte code.

4 Describe instance Of and dot (.) operators in Java with suitableexample.


Instance of operator:
The java instance of operator is used to test whether the object is aninstance of the specified type
(class or subclass or interface).
The instance of in java is also known as type comparison operator because it compares the instance
with type. It returns either true or false. If we apply the instance of operator with any variable that has
null value, it returns false.
Example
class Simple1{
public static void main(String args[]){ Simple1 s=new Simple1();
System.out.println(sinstanceofSimple1);//true
}
}

dot (.) operator:


The dot operator, also known as separator or period used to separate a variable or method from a
reference variable. Only static variables or methods can be accessed using class name. Code that is
outside the object's class must use an object reference or expression, followed by the dot (.) operator,
followed by a simple field name.
Example
this.name=”john”; where name is a instance variable referenced by„this‟ keyword
c.getdata(); where getdata() is a method invoked on object „c‟.
5 Define Class and Object.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 4 of 42


Class: A class is a user defined data type which groups datamembers and its associated functions
together.
Object: It 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.
6 Define a class circle having data members pi and radius.Initialize and display values of data
members also calculate area of circle and display it.
class abc
{
float pi,radius; abc(float p, float r)

{
pi=p; radius=r;

void area()
{
float ar=pi*radius*radius; System.out.println("Area="+ar);

void display()
{
System.out.println("Pi="+pi); System.out.println("Radius="+radius);

}}

class area
{
public static void main(String args[])
{
abc a=new abc(3.14f,5.0f);
a.display();
a.area();
}
}
7 Define type casting. Explain its types with syntax and example.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 5 of 42


1. The process of converting one data type to another is calledcasting or type casting.
2. If the two types are compatible, then java will perform theconversion automatically.
3. It is possible to assign an int value to long variable.
4. However, if the two types of variables are not compatible, thetype conversions are not implicitly
allowed, hence the need for type casting.

There are two types of conversion:


1. Implicit type-casting:
2. Explicit type-casting:

1. Implicit type-casting:
Implicit type-casting performed by the compiler automatically; ifthere will be no loss of precision.
Example:
int i = 3;double f;
f = i;
output:
f = 3.0
Widening Conversion:
The rule is to promote the smaller type to bigger type to preventloss of precision, known as
Widening Conversion.

2. Explicit type-casting:
 Explicit type-casting performed via a type-casting operator in the prefix form of (new-type)
operand.
 Type-casting forces an explicit conversion of type of a value. Type casting is an operation
which takes one operand, operates on it and returns an equivalent value in the specified type.
Syntax:
newValue = (typecast)value;

Example:

double f = 3.5;
int i;
i = (int)f; // it cast double value 3.5 to int 3.
Narrowing Casting: Explicit type cast is requires to Narrowingconversion to inform the compiler
that you are aware of the possible loss of precision.
8 State any four relational operators and their use.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
9 Explain any two logical operator in java with example.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 6 of 42


Logical Operators: Logical operators are used when we want toform compound conditions by
combining two or more relations. Java has three logical operators as shown in table:

Operator Meaning
&& LogicalAND
|| LogicalOR
! LogicalNOT

Program demonstrating logical Operators

public class Test


{
public static void main(String args[])
{
boolean a = true; boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}

Output:
a && b = falsea || b = true

!(a && b) = true


10 Write a program to find greater number among two numbers usingconditional operator.
class greater
{
public static void main(String args[])
{
int a,b;
int bignum;a=100; b=150;
bignum=(a>b?a:b); //conditional operator System.out.println("Greater number
between "+a+ " and "+b +" is ="+bignum);
}
}
Output:
E:\java\bin>javac greater.javaE:\java\bin>java greater
Greater number between 100 and 150 is = 150
11 Explain following terms related to Java features.
i) Object Oriented ii) Complied and interpreted.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 7 of 42


i) Object Oriented:
 Almost everything in java is in the form of object.
 All program codes and data reside within objects and classes.
 Similar to other OOP languages java also has basic OOP properties such as encapsulation,
polymorphism, data abstraction, inheritanceetc.
 Java comes with an extensive set of classes (default) in packages.

ii) Compiled and Interpreted:


 Java is a two staged system. It combines both approaches.
 First java compiler translates source code into byte code instruction.Byte codes are not
machine instructions.
 In the second stage java interpreter generates machine code that canbe directly executed by
machine. Thus java is both compile and interpreted language.
12 Write a program to check whether the given number is prime or not.
Code:

class PrimeExample
{
public static void main(String args[])
{
int i,m=0,flag=0;
int n=7;//it is the number to be checked m=n/2;

if(n==0||n==1)
{
System.out.println(n+" is not prime number");
}
else
{
for(i=2;i<=m;i++)
{
if(n%i==0)
{
System.out.println(n+" is not prime number"); flag=1;
break;
}
}
if(flag==0)
{
System.out.println(n+" is prime number");
}

}//end of else
}}

Output:
7 is prime number
13 Write a program to calculating area and perimeter of rectangle.
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 8 of 42
import java.io.*;
import java.lang.*;

class rect
{
public static void main(String args[]) throws Exception
{
DataInputStream dr=new DataInputStream(System.in);
int l,w;
System.out.println(“Enter length and width:”);
l=Integer.parseInt(dr.readLine());
w=Integer.parseInt(dr.readLine());
int a=l*w;
System.out.println(“Area is=”+a);
int p=2(l+w);
System.out.println(“Area is=”+p);
}
}
14 Explain type casting with suitable example.
In Java, type conversion is performed automatically when the type of the expression on the right hand
side of an assignment operation can be safely promoted to the type of the variable on the left hand
side of the assignment. Assigning a value of one type to a variable of another type is known as Type
Casting.

Every expression has a type that is determined by the components of theexpression.

Example: double x;

int y=2;
float z=2.2f;

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 9 of 42


x=y+z;
The expression to the right of the “=“ operator is solved first and the result is stored in x. The int
value is automatically promoted to the higher data type float (float has a larger range than int) and
then, the expression is evaluated. The resulting expression is of float data type. This value is then
assigned to x,which is a double (larger range than float) and therefore, the result is a double.

Java automatically promotes values to a higher data type, to prevent any loss of information.

Example: int x=5.5/2


In above expression the right evaluates to a decimal value and the expression on left is an integer and
cannot hold a fraction. Compiler will give you following error.

“Incompatible type for declaration, Explicit vast needed to convert double toint.”

This is because data can be lost when it is converted from a higher data typeto a lower data type. The
compiler requires that you typecast the assignment.
Solution: int x=(int)5.5/2;
15 Write a program to print sum of even numbers from 1 to 20.
public class sum_of_even
{
public static void main(String[] args)
{
int sum=0;
for (int i=0; i<=20;i=i+2)
{
sum = sum+i;
}
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Sum of even numbers: 110
16 Write a program to find reverse of a number.
public class ReverseNumberExample1
{
public static void main(String[] args)
{
int number = 987654, reverse =0;

while(number !=0)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10;
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 10 of 42


System.out.printtln(“The reverse of the given number is: “ + reverse);

}}
17 Develop a program to create a class „Book‟ having data members author, title and price.
Derive a class 'Booklnfo' having data member 'stock position‟ and method to initialize and
display the information for three objects.
class Book
{
String author, title, publisher;
Book(String a, String t, String p)
{
author = a;
title = t;
publisher = p;
}
}
class BookInfo extends Book
{
float price;
int stock_position;
BookInfo(String a, String t, String p, float amt, int s)
{
super(a, t, p); price = amt;
stock_position = s;
}
void show()
{
System.out.println("Book Details:");
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
System.out.println("Price: " + price);
System.out.println("Stock Available: " + stock_position);
}
}
class Exp6_1
{
public static void main(String[] args)
{
BookInfo ob1 = new BookInfo("Herbert Schildt", "Complete Reference", "ABC Publication",

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 11 of 42


359.50F,10);
BookInfo ob2 = new BookInfo("Ulman", "system programming", "XYZ Publication", 359.50F, 20);
BookInfo ob3 = new BookInfo("Pressman", "Software Engg", "Pearson Publication", 879.50F, 15);
ob1.show();
ob2.show();
ob3.show();
}
}
OUTPUT
Book Details:
Title: Complete Reference
Author: Herbert Schildt
Publisher: ABC
Publication Price: 2359.5
Stock Available: 10
Book Details:
Title: system programming
Author: Ulman
Publisher: XYZ
Publication Price: 359.5
Stock Available: 20
Book Details:
Title: Software Engg
Author: Pressman
Publisher: Pearson
Publication Price: 879.5
Stock Available: 15
18 Define a class employee with data members 'empid , name and salary. Accept data for three
objects and display it.
class employee
{
int empid; String name;
double salary; void
getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter Emp number : "); empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine(); System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
}
void show()

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 12 of 42


{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
}
class EmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3; i++)
{
e[i] = new employee(); e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<3; i++)
{
e[i].show();
}
}
}
19 State use of finalize( ) method with its syntax.
Use of finalize( ):
Sometimes an object will need to perform some action when it is destroyed. Eg. If an object
holding some non java resources such as file handle or window character font, then before the object is
garbage collected these resources should be freed. To handle such situations java provide a mechanism
called finalization. In finalization, specific actions that are to be done when an object is garbage
collected can be defined. To add finalizer to a class define the finalize() method. The java run-time
calls this method whenever it is about to recycle an object.
Syntax:
protected void finalize ( )
{
}
20 Name the wrapper class methods for the following:
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
(i) To convert string objects to primitive int:
String str=”5”;
int value = Integer.parseInt(str);

(ii) To convert primitive int to string objects:


int value=5;
String str=Integer.toString(value);
21 Explain the types of constructors in Java with suitable example.
(Note: Any two types shall be considered).
Constructors are used to initialize an object as soon as it is created. Every time an object is created
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 13 of 42
using the „new‟ keyword, a constructor is invoked. If no constructor is defined in a class, java
compiler creates a default constructor. Constructors are similar to methods but with to differences,
constructor has the same name as that of the class and it does not return any value.
The types of constructors are:
1.Default constructor
2.Constructor with no arguments
3.Parameterized constructor
4.Copy constructor

1. Default constructor: Java automatically creates default constructor if there is no default or


parameterized constructor written by user. Default constructor in Java initializes member data
variable to default values (numeric values are initialized as 0, Boolean is initialized as false and
references are initialized as null).

class test1
{ int i;
boolean b;
byte bt;
float ft;
String s;
public static void main(String args[])
{
test1 t = new test1(); // default constructor is called.
System.out.println(t.i);
System.out.println(t.s);
System.out.println(t.b);
System.out.println(t.bt);
System.out.println(t.ft);
}
}
2. Constructor with no arguments: Such constructors does not have any parameters. All the objects
created using this type of constructorshas the same values for its data members.
Eg:
class Student
{
int roll_no;
String name;
Student()
{
roll_no = 50;
name="ABC";
}
void display()
{
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 14 of 42


public static void main(String a[])
{
Student s = new Student();
s.display();
}}

3. Parametrized constructor: Such constructor consists of parameters. Such constructors can be


used to create different objects with datamembers having different values.
class Student
{
int roll_no;
String name;
Student(int r, String n)
{
roll_no = r;
name=n;
}
void display()
{
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[])
{
Student s = new Student(20,"ABC");
s.display();
}
}

4. Copy Constructor : A copy constructor is a constructor that creates a new object using an existing
object of the same class and initializes each instance variable of newly created object with
corresponding instance variables of the existing object passed as argument. This constructor
takes a single argument whose type is that of the classcontaining the constructor.

class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = obj.length;
breadth= obj.breadth;
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 15 of 42
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
System.out.println("Area of First Rectangle : "+(r1.length*r1.breadth));
System .out.println("Area of First Second Rectangle : "+(r1.length*r1.breadth));
}
}
22 Define a class student with int id and string name as data members and a method void SetData
( ). Accept and display the data for five students.
import java.io.*;
class student
{
int id;
String name;
BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
void SetData()
{
try
{
System.out.println("enter id and name for student");
id=Integer.parseInt(br.readLine());
name=br.readLine();
}
catch(Exception ex)
{}
}
void display()
{
System.out.println("The id is " + id + " and the name is "+ name);
}
public static void main(String are[])
{
student[] arr;
arr = new student[5];
int i;
for(i=0;i<5;i++)
{
arr[i] = new student();
}
for(i=0;i<5;i++)
{
arr[i].SetData();
}
{
for(i=0;i<5;i++) arr[i].display();
}
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 16 of 42
}
}
23 Explain dynamic method dispatch in Java with suitable example.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time.
•When an overridden method is called through a superclass reference, Java determines which version
(superclass/subclasses) of that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is
made at run time.
•At run-time, it depends on 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
•A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java
uses this fact to resolve calls to overridden methods at run time. Therefore, if a superclass contains a
method that is overridden by a subclass, then when different types of objects are referred to through a
superclass reference variable, different versions of the method are executed. Here is an example that
illustrates dynamic method dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
Example:
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 17 of 42
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();

// obtain a reference of type A


A ref;

// ref refers to an A
object ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;
// calling B's version of m1()
ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}
24 Explain the four access specifiers in Java.
There are 4 types of java access modifiers:
1.private 2. default 3. Protected 4. Public
1) private access modifier: The private access modifier is accessible only within class.
2) default access specifier: If you don‟t specify any access control specifier, it is default, i.e. it
becomes implicit public and it is accessible within the program.
3) protected access specifier: The protected access specifier is accessible within package and
outside the package but through inheritance only.
4) public access specifier: The public access specifier is accessible everywhere. It has the widest
scope among all other modifiers.
25 Differentiate between Method overloading and method overriding.
Sr.
No. Method overloading Method overriding
1 Overloading occurs when two or more Overriding means having two methods with
methods in one class have the same method the same method name and parameters (i.e.,
name but different parameters. method signature)
2 In contrast, reference type determines which The real object type in the run-time, not
overloaded method will be used at compile the reference variable's type, determines
time. which overridden method is used at runtime
3 Polymorphism not applies to overloading Polymorphism applies to overriding

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 18 of 42


4 overloading is a compile- time concept. Overriding is a run-time concept
26 Describe the use of any methods of vector class with their syntax. (Note: Any method other than
this but in vector class shall beconsidered for answer).
 boolean add(Object obj)-Appends the specified element to theend of this Vector.
 Boolean add(int index,Object obj)-Inserts the specified element atthe specified position in this
Vector.
 void addElement(Object obj)-Adds the specified component tothe end of this vector,
increasing its size by one.
 int capacity()-Returns the current capacity of this vector.
 void clear()-Removes all of the elements from this vector.
 Object clone()-Returns a clone of this vector.
 boolean contains(Object elem)-Tests if the specified object is acomponent in this vector.
 void copyInto(Object[] anArray)-Copies the components of thisvector into the specified array.
 Object firstElement()-Returns the first component (the item atindex 0) of this vector.
 Object elementAt(int index)-Returns the component at thespecified index.
 int indexOf(Object elem)-Searches for the first occurence of thegiven argument, testing for
equality using the equals method.
 Object lastElement()-Returns the last component of the vector.
 Object insertElementAt(Object obj,int index)-Inserts the specifiedobject as a component in this
vector at the specified index.
 Object remove(int index)-Removes the element at the specifiedposition in this vector.
 void removeAllElements()-Removes all components from thisvector and sets its size to zero.
27 Explain the command line arguments with suitable example.
Java Command Line Argument:
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used as an
input. So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Command Line Arguments can be used to specify configuration information while launching
your application. There is no restriction on the number of java command line
arguments. You can specify any number of arguments Information is passed as Strings.
They are captured into the String args of your main method Simple example of command-line
argument in java In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from the command prompt.

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
28 Define array. List its types.
An array is a homogeneous data type where it can hold onlyobjects of one data type.
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 19 of 42
Types of Array:
1) One Dimensional
2) Two Dimensional
3) Multi Dimensional
29 Differentiate between String and String Buffer.
String String Buffer c
String is a major class String Buffer is a peer classof String
Length is fixed (immutable) Length is flexible (mutable)
Contents of object cannot bemodified Contents of object can bemodified
Object can be created by assigning String Objects can be created by calling constructor of
constants enclosed in double quotes. StringBuffer class using “new”
Ex:- String s=”abc”; Ex:- StringBuffer s=newStringBuffer (“abc”);
30 Differentiate between class and interfaces.
Class Interface
1)doesn‟t Supports multipleinheritance 1) Supports multipleinheritance
2)”extend ” keyword is usedto inherit 2)”implements ” keyword isused to inherit
3) class contain method body 3) interface contains abstract method (method
without body)
4)contains any type ofvariable 4)contains only final variable
5)can have constructor 5)cannot have constructor
6)can have main() method 6)cannot have main() method
7)syntax: 7)syntax:
Class classname Inteface Innterfacename
{ {
Variable declaration,Method declaration Final Variable declaration, abstract Method
} declaration
}
31 Compare array and vector. Explain elementAT( ) and addElement( ) methods.
Sr. Array Vector
No.
1 An array is a structure that holds multiple The Vector is similar to array holds multiple
values of the same type. objects and like an array; it contains
components that can be accessed using an
integer index.
2 An array is a homogeneous data type Vectors are heterogeneous. You can have
where it can hold only objects of one data objects of different data types inside a Vector.
type.
3 After creation, an array is a fixed-length The size of a Vector can grow or shrink as
structure. needed to accommodate adding and removing
items after the Vector has been created.
4 Array can store primitive type data element. Vector are store non-primitive type data
element
5 Array is unsynchronized i.e. Vector is synchronized i.e. when the size will be

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 20 of 42


automatically increase the size when the exceeding at the time; vector size will increase
initialized size will be exceed. double of initial size.
6 Declaration of an array : Declaration of Vector:
int arr[] = new int [10]; Vector list = new Vector(3);
7 Array is the static memory allocation. Vector is the dynamic memory allocation.
8 Array allocates the memory for the fixed Vector allocates the memory dynamically
size ,in array there is wastage of memory. means according to the requirement no wastage
of memory.
9 No methods are provided for adding and Vector provides methods for adding and
removing elements. removing elements.
10 In array wrapper classes are not used. Wrapper classes are used in vector
11 Array is not a class. Vector is a class.

1) elementAT( ):
The elementAt() method of Java Vector class is used to get the element at the specified
index in the vector. Or The elementAt() method returns an element at the specified index.

2) addElement( ):
The addElement() method of Java Vector class is used to add the specified element to the
end of this vector. Adding an element increases the vector size by one.
32 List any four methods of string class and state the use of each.
The java.lang.String class provides a lot of methods to work onstring. By the help of these methods,
We can perform operations on string such as trimming, concatenating, converting, comparing,
replacing strings etc.
1) to Lowercase (): Converts all of the characters in this Stringto lower case.
Syntax: s1.toLowerCase() Example: String s="Sachin";
System.out.println(s.toLowerCase());

Output: sachin

2) to Uppercase():Converts all of the characters in this String toupper case


Syntax: s1.toUpperCase() Example:
String s="Sachin"; System.out.println(s.toUpperCase());
Output: SACHIN

3) trim (): Returns a copy of the string, with leading and trailing whitespace omitted.
Syntax: s1.trim() Example:
String s=" Sachin "; System.out.println(s.trim());
Output:Sachin

4) replace ():Returns a new string resulting from replacing all occurrences of old Char in this
string with new Char.
Syntax: s1.replace(„x‟,‟y‟) Example:
String s1="Java is a programming language. Java is a platform.";
String s2=s1.replace("Java","Kava"); //replaces all occurrences of "Java" to "Kava"

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 21 of 42


System.out.println(s2);

Output: Kava is a programming language. Kava is a platform.


33 Write a program to check whether the string provided by the user is palindrome or not.
import java.lang.*; import

java.io.*; import java.util.*;

class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String word=br.readLine( );
I
int len=word.length( )-1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{
if(word.charAt(l)==word.charAt(r))
{
l++; r-;
}
else
{
flag=0;
break;
}
}
if(flag==1)
{
System.out.println("palindrome");
}
else
{
System.out.println("not palindrome");
}
} }
34 Write a program to createst a vector with five elements as (5,15, 25, 35, 45). Insert new element
at 2nd position. Remove and 4th element from vector.
1
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 22 of 42
import java.util.*;class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector(); v.addElement(new Integer(5));
v.addElement(new Integer(15));v.addElement(new Integer(25));
v.addElement(new Integer(35));v.addElement(new Integer(45));
System.out.println("Original array elements are");

for(int i=0;i<v.size();i++)
{
System.out.println(v.elementAt(i));
}
v.insertElementAt(new Integer(20),1); // insertnew element at 2nd position
v.removeElementAt(0); //remove first element
v.removeElementAt(3); //remove fourth element
System.out.println("Array elements after insertand remove operation ");
for(int i=0;i<v.size();i++)
{
System.out.println(v.elementAt(i));
}
}}
35 Define a class „Book‟ with data members bookid, bookname and price.Accept data for seven
objects using Array of objects and display it.
import java.lang.*;import java.io.*; class
Book
{
String bookname;int bookid;
int price;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void getdata()
{
try
{
System.out.println("Enter Book ID=");
bookid=Integer.parseInt(br.readLine()); System.out.println("Enter
Book Name=");bookname=br.readLine();
System.out.println("Enter Price=");
price=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Error");
}
}
void display()
{
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 23 of 42
System.out.println("Book ID="+bookid);
System.out.println("Book Name="+bookname);
System.out.println("Price="+price);
}
}
class bookdata
{
public static void main(String args[])
{
Book b[]=new Book[7];for(int i=0;i<7;i++)
{
b[i]=new Book();
}
for(int i=0;i<7;i++)
{
b[i].getdata();
}
for(int i=0;i<7;i++)
{
b[i].display();
}
}
}
2.INHERITANCE, INTERFACE AND PACKAGE
1 List the types of inheritances in Java. (Note: Any four types shall be considered)
Types of inheritances in
Java:
i. Single level inheritance
ii. Multilevel inheritance
iii. Hierarchical inheritance
iv. Multiple inheritance
v. Hybrid inheritance

2 State the use of final keyword with respect to inheritance.


Final keyword : The keyword final has three uses. First, it can be used to create the equivalent of a
named constant.( in interface or class we use final as shared constant or constant.)
Other two uses of final apply to inheritance
Using final to Prevent Overriding While method overriding is one of Java‟s most powerful features,
To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.
The following fragment illustrates final:

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 24 of 42


class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
As base class declared method as a final , derived class can not override the definition of base class
methods.
3 List any four Java API packages.
1. java.lang
2. java.util
3. java.io
4. java.awt
5. java.net
6. java.applet
4 Describe final variable and final method.
Final method: making a method final ensures that the
functionality defined in this method will never be altered in any way, ie a final method cannot be
overridden.
Syntax:
final void findAverage ()
{
//implementation
}
Example of declaring a final method:
class A
{
final void show()
{
System.out.println (“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
System.out.println(“in show of B”);
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 25 of 42
}}
Final variable: the value of a final variable cannot be changed. Final variable behaves like class
variables and they do not take any space on individual objects of the class.
Example of declaring final variable:
final int size = 100;
5 Define package. How to create user defined package?Explain with example.
Java provides a mechanism for partitioning the class namespace into more manageable parts. This
mechanism is the package. Thepackage is both naming and visibility controlled mechanism. Package
can be created by including package as the first statementin java source code. Any classes declared
within that file will belong to the specified package. Package defines a namespace in which classes
are stored.
The syntax for defining a package is:
package pkg;
Here, pkg is the name of the package
eg : package mypack;
Packages are mirrored by directories. Java uses file system directories to store packages. The class
files of any classes whichare declared in a package must be stored in a directory which hassame name
as package name. The directory must match with the package name exactly. A hierarchy can be
created by separating package name and sub package name by a period(.) aspkg1.pkg2.pkg3; which
requires a directory structure as pkg1\pkg2\pkg3.
Syntax:
To access package In a Java source file, import statements occur immediately following the
package statement (ifit exists) and before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package package1;public class Box
{
int l= 5; int b = 7;int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;class volume
{
public static void main(String args[])
{
Box b=new Box();b.display();
}
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 26 of 42


6 Implement the following inheritance

interface Salary
{
double Basic Salary=10000.0;void Basic Sal();
}
class Employee
{
String Name;int age;
Employee(String n, int b)
{
Name=n;age=b;
}
void Display()
{
System.out.println("Name of Employee :"+Name);
System.out.println("Age of Employee :"+age);
}
}
class Gross_Salary extends Employee implements Salary
{
double HRA,TA,DA;
Gross_Salary(String n, int b, double h,double t,double d)
{
super(n,b);
HRA=h;
TA=t;
DA=d;
}
public void Basic_Sal()
{
System.out.println("Basic Salary :"+Basic_Salary);
}
void Total_Sal()
{
Display(); Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA + HRA;
System.out.println("Total Salary :"+Total_Sal);
}
}
class EmpDetails

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 27 of 42


{ public static void main(String args[])
{ Gross_Salary s=new Gross_Salary("Sachin",20,1000,2000,7000);
s.Total_Sal();
}
}
7 Write a program to demonstrate multiple inheritances.
interface sports
{
int sports_weightage=5;void calc_total();
}

class person
{
String name;
String category;
person(String nm,String c)
{
name=nm; category=c;
}
}
class student extends person implements sports
{
int marks1,marks2;
student(String n,String c, int m1,int m2)
{
super(n,c); marks1=m1; marks2=m2;
}
public void calc_total()
{
int total;
if (category.equals("sportsman"))
total=marks1+marks2+sports_weightage;
else
total=marks1+marks2; System.out.println("Name="+name);
System.out.println("Category ="+category);
System.out.println("Marks1="+marks1);
System.out.println("Marks2="+marks2);
System.out.println("Total="+total);
}
public static void main(String args[])
{
student s1=new student("ABC","sportsman",67,78);
student s2= new student("PQR","non-sportsman",67,78);
s1.calc_total();
s2.calc_total();
}
}
8 What is interface? Describe its syntax and features.
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 28 of 42
Definition: Java does not support multiple inheritances with only classes. Java provides an alternate
approach known as interface to support concept of multiple inheritance. An interface is similar to class
which can define only abstract methods and final variables.
Syntax:
access interface InterfaceName
{
Variables declaration;
Methods declaration;
}

Features:
 The interfaces are used in java to implementing the concept ofmultiple inheritance.
 The members of an interface are always declared as constant i.e. theirvalues are final.
 The methods in an interface are abstract in nature. I.e. there is no codeassociated with them.
 It is defined by the class that implements the interface.
 Interface contains no executable code.
 We are not allocating the memory for the interfaces.
 We can„t create object of interface.
 Interface cannot be used to declare objects. It can only be inherited bya class.
 Interface can only use the public access specifier.
 An interface does not contain any constructor.
 Interfaces are always implemented.
 Interfaces can extend one or more other interfaces.
9 Write a program to create a class 'salary with data members empid', „name' and „basicsalary'.
Write an interface 'Allowance‟ which stores rates of calculation for da as 90% of basic salary,
hra as 10% of basic salary and pf as 8.33% of basic salary. Include a method to calculate net
salary and display it.
interface allowance
{
double da=0.9*basicsalary;
double hra=0.1*basicsalary;
double pf=0.0833*basicsalary;
void netSalary();
}
class Salary
{
int empid;
String name;
float basicsalary;
Salary(int i, String n, float b)
{
empid=I;
name=n;
basicsalary =b;
}
void display()
{

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 29 of 42


System.out.println("Empid of Emplyee="+empid);
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+ basicsalary);
}
}
class net_salary extends salary implements allowance
{
float ta;
net_salary(int i, String n, float b, float t)
{
super(i,n,b); ta=t;
}
void disp()
{
display();
System.out.println("da of Employee="+da);
}
public void netsalary()
{
double net_sal=basicsalary+ta+hra+da;
System.out.println("netSalary of Employee="+net_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
net_salary s=new net_salary(11, “abcd”, 50000);
s.disp();
s.netsalary();
}
}
10 What is package in Java? Write a program to create a package and import the package in
another class.
Package: Java provides a mechanism for partitioning the class namespace into more manageable parts
called package (i.e package are container for a classes). The package is both naming and visibility
controlled mechanism. Package can be created by including package as the first statement in java
source code. Any classes declared within that file will belong to the specified package.
Syntax:
package pkg;
Here, pkg is the name of the package

Program:
package1:
package package1;public class Box
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 30 of 42
{
int l= 5; int b = 7;int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}

Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
11 What is use of super and final with respect to inheritance.
Super Keyword: The super keyword in Java is a reference variable which is used to refer immediate
parent class object. Whenever you create the instanceof subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.
Example:
class A
{
int i;
A(int a, iont b)
{
i=a+b;
}
void add()
{
System.out.println(“sum of a and b=”+i);
}
}
class B extends A
{
int j;
B(int a,int b, int c)
{
super(a,b);j=a+b+c;
}
void add()
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 31 of 42
{
super.add();
System.out.println(“Sum of a, b and c is:” +j);
}
}
Final Keyword: A parameter to a function can be declared with the keyword“final”.
This indicates that the parameter cannot be modified in the function.
The final keyword can allow you to make a variable constant.

Example:
Final Variable: The final variable can be assigned only once. The value of afinal variable can never
be changed.
final float PI=3.14;

Final Methods: A final method cannot be overridden. Which means even though a sub class can call
the final method of parent class without any issuesbut it cannot override it.
Example:
class XYZ
{
final void demo()
{
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ


{
void demo()
{
System.out.println("ABC Class Method");
}

public static void main(String args[])


{
ABC obj= new ABC();obj.demo();
}
}

The above program would throw a compilation error, however we can use theparent class final method
in sub class without any issues.
class XYZ
{
final void demo()
{
System.out.println("XYZ Class Method");
}
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 32 of 42


class ABC extends XYZ
{
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
XYZ Class Method

final class: We cannot extend a final class. Consider the below example:final class XYZ
{
}

class ABC extends XYZ


{
void demo()
{
System.out.println("My Method");
}
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
The type ABC cannot subclass the final class XYZ
3.EXCEPTION HANDLING, AND MULTITHREADING
1 Write the syntax of try-catch-finally blocks.
try{
//Statements to be monitored for any exception
}
catch(ThrowableInstance1 obj)
{
//Statements to execute if this type of exception occurs
}
catch(ThrowableInstance2 obj2)
{
//Statements
}
Finally
{
//Statements which should be executed even if any exception happens
}
Write a program to create two threads. One thread will display the numbers from 1 to 50
(ascending order) and other thread will display numbers from 50 to 1 (descending order).
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 33 of 42
class Ascending extends Thread
{
public void run()
{
for(int i=1; i<=15;i++)
{
System.out.println("Ascending Thread : " + i);
}
}
}
class Descending extends Thread
{
public void run()
{
for(int i=15; i>0;i--) {
System.out.println("Descending Thread : " + i);
}
}
}
public class AscendingDescending Thread
{
public static void main(String[] args)
{
Ascending a=new Ascending();
a.start();
Descending d=new Descending();
d.start();
}
}
2 Write a program to input name and salary of employee andthrow user defined exception if
entered salary is negative.
import java.io.*;
class NegativeSalaryException extends Exception
{
public NegativeSalaryException (String str)
{
super(str);
}
}
public class S1
{
public static void main(String[] args) throws IOException
{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Name of employee");
String name = br.readLine();
System.out.print("Enter Salary of employee");
int salary = Integer.parseInt(br.readLine());
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 34 of 42
try
{
if(salary<0)
throw new NegativeSalaryException("Enter Salary amountisnegative");
System.out.println("Salary is "+salary);
}
catch (NegativeSalaryException a)
{
System.out.println(a);
}
}}
3 Define error. List types of error.
Errors are mistakes that can make a program go wrong. Errors may be logical or may be typing
mistakes. An error may produce an incorrect output or may terminate the execution of the program
abruptly or even may cause the system to crash.

Errors are broadly classified into two categories:


1. Compile time errors
2. Runtime errors
4 Define exception. State built-in exceptions.
An exception is a problem that arises during the execution of aprogram. Java exception handling is
used to handle error conditions in aprogram systematically by taking the necessary action

Built-in exceptions:
 Arithmetic exception: Arithmetic error such as division byzero.
 ArrayIndexOutOfBounds Exception: Array index is outof bound
 ClassNotFoundException
 FileNotFoundException: Caused by an attempt to accessa nonexistent file.
 IO Exception: Caused by general I/O failures, such asinability to read from a file.
 NullPointerException: Caused by referencing a null object.
 NumberFormatException: Caused when a conversionbetween strings and number fails.
 StringIndexOutOfBoundsException: Caused when a program attempts to access a
nonexistent character positionin a string.
 OutOfMemoryException: Caused when there‟s not enough memory to allocate a new object.
 SecurityException: Caused when an applet tries to perform an action not allowed by the
browser‟s security setting.
 StackOverflowException: Caused when the system runs outof stack space.
5 Explain the two ways of creating threads in Java.
Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending the Thread class.
Thread class provide constructors and methods to create and perform operations on a thread. This class
implements the Runnable interface.
When we extend the class Thread, we need to implement the method run(). Once we create an object,
we can call the start() of the thread class for executing the method run().

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 35 of 42


Eg:
class MyThread extends Thread
{
public void run()
{
for(int i = 1;i<=20;i++)
{
System.out.println(i);
}
}

public static void main(String a[])


{
MyThread t = new MyThread();
t.start();
}
}
a. By implementing the runnable interface.
Runnable interface has only on one method- run().
Eg:
class MyThread implements Runnable
{
public void run()
{
for(int i = 1;i<=20;i++)
{
System.out.println(i);
}
}

public static void main(String a[])


{
MyThread m = new MyThread();
Thread t = new Thread(m);
t.start();
}
6 Define an exception called 'No Match Exception' that is thrown when the passward accepted is
not equal to "MSBTE'. Write the program.
import java.io.*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 36 of 42
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
if (str.compareTo("MSBTE")!=0) // can be done with equals() throw new
NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}}
7 Explain life cycle of thread.

Thread Life Cycle Thread has five different states throughout itslife.

1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State

Thread should be in any one state of above and it can be movefrom one state to another
by different methods and ways.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 37 of 42


Newborn state: When a thread object is created it is said to be ina new born state. When the thread is
in a new born state it is not scheduled running from this state it can be scheduled for runningby start()
or killed by stop(). If put in a queue it moves to runnable state.

Runnable State: It means that thread is ready for execution and is waiting for the availability of the
processor i.e. the thread has joined the queue and is waiting for execution. If all threads haveequal
priority, then they are given time slots for execution in round robin fashion. The thread that
relinquishes control joins the queue at the end and again waits for its turn. A thread can relinquish the
control to another before its turn comes by yield().
Running State: It means that the processor has given its time tothe thread for execution. The thread
runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.
Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state byusing either of the following thread method.
1) suspend() : Thread can be suspended by this method. Itcan be rescheduled by resume().
2) wait(): If a thread requires to wait until some event occurs, it can be done using wait
method and can bescheduled to run again by notify().
3) sleep(): We can put a thread to sleep for a specified timeperiod using sleep(time) where time
is in ms. It re-entersthe runnable state as soon as period has elapsed /over
Dead State: Whenever we want to stop a thread form running further we can call its stop().The
statement causes the thread tomove to a dead state. A thread will also move to dead state automatically
when it reaches to end of the method. The stop method may be used when the premature death is
required.
8 Write a program to create two threads one thread will printeven no. between 1 to 50 and other
will print odd number between 1 to 50.
import java.lang.*;
class Even extends Thread
{
public void run()
{
try
{
for(int i=2;i<=50;i=i+2)
{
System.out.println("\t Even thread :"+i);sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("even thread interrupted");
}
}
}
class Odd extends Thread
{
public void run()
{
try
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 38 of 42
{
for(int i=1;i<50;i=i+2)
{
System.out.println("\t Odd thread :"+i);sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("odd thread interrupted");
}
}
}
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}
9 Explain following clause w.r.t. exception handling
i) try ii) catch iii) throw iv) finally
i) try: Program statements that you want to monitor for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown.
Syntax:
try
{
// block of code to monitor for errors
}
ii) catch: Your code can catch this exception (using catch) and handle it in some rational manner.
System-generated exceptions are automatically thrown by the Java runtime system. A catch block
immediately follows the try block. The catch block can have one or more statements that are necessary
to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
iii) throw: It is mainly used to throw an instance of user defined exception.
Example:
throw new myException(“Invalid number”);
assuming myException as a user defined exception.
iv)finally: finally block is a block that is used to execute important code such as closing connection,
stream etc. Java finally block is always executed whether exception is handled or not. Java finally
block follows try or catch block.
Syntax:
finally
{

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 39 of 42


// block of code to be executed before try block ends
}
10 Define thread priority ? Write default priority values and the methods to set and change them.
Thread Priority:
In java each thread is assigned a priority which affects the order in which it is scheduled for running.
Threads of same priority are given equal treatment by the java scheduler.
Default priority values as follows
The thread class defines several priority constants as: -

MIN_PRIORITY =1

NORM_PRIORITY = 5

MAX_PRIORITY = 10

Thread priorities can take value from 1-10.

getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority


of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority
goes out of the range, which is 1 (minimum) to 10 (maximum).

import java.lang.*;

public class ThreadPriorityExample extends Thread


{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 40 of 42


System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().gtName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrority();
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPiority());
}
11 Explain types of Exception
Types of Exceptions:
Java exceptions can be classified as Built-inexceptions and user defined exceptions
1) Built-in Exceptions: Built-in exceptions are the exceptions which areavailable in Java
libraries. These exceptions are suitable to explain certainerror situations. Below is the list of
important built-in exceptions in Java.
2) Arithmetic Exception: It is thrown when an exceptional condition hasoccurred in an arithmetic
operation.
3) 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.
4) ClassNotFoundException: This Exception is raised when we try to access a class whose
definition is not found
5) FileNotFoundException: This Exception is raised when a file is not accessible or does not
open.
6) IOException: It is thrown when an input-output operation failed orinterrupted

2) User-Defined Exceptions: Sometimes, the built-in exceptions in Java are not able to describe a
certain situation. In such cases, user can also create exceptions which are called „user-defined
Exceptions‟.
Following steps are followed for the creation of user-defined Exception.
The user should create an exception class as a subclass of Exception class. Since all the exceptions
are subclasses of Exception class, the user shouldalso make his class a subclass of it. This is done
as:
class MyException extends Exception
We can create a parameterized constructor with a string as a parameter.We can use this to store
exception details.
MyException(String str)
{
super(str);
}
To raise exception of user-defined type, we need to create an object to hisexception class and
throw it using throw clause, as
throw new MyException(“Error message here….”);
12 Create two threads where first will print numbers between 1 to 10 whereas other will print odd
number between 11 to 20.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 41 of 42


class eventhread extends Thread
{
public void run()
{
for(int i=1;i<=10;i=i+2)
{
System.out.println("Even no="+ i);
}
}
}
class oddthread extends Thread
{
public void run()
{
for(int i=11;i<=20;i=i+2)
{
System.out.println("Odd no="+ i);
}
}
}
class threadtest
{
public static void main(String args[])
{
eventhread e1= new eventhread();oddthread o1= new
oddthread(); e1.start();
o1.start();
}
}
Output:
E:\java\bin>javac threadtest.javaE:\java\bin>java
threadtest
Odd no=11 Even no=2 Odd no=13
Odd no=15 Even no=4 Even no=6
Odd no=17Odd no=19Even no=8
Even no=10

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 42 of 42

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy