JPR E-Content FINAL
JPR E-Content FINAL
{
pi=p; radius=r;
void area()
{
float ar=pi*radius*radius; System.out.println("Area="+ar);
void display()
{
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 5 of 57
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();
}
}
Define type casting. Explain its types with syntax and example.
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.
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.
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 6 of 57
Narrowing Casting: Explicit type cast is requires to Narrowingconversion to inform the compiler
that you are aware of the possible loss of precision.
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
Explain any two logical operator in java with example.
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
Output:
a && b = falsea || b = true
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");
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 8 of 57
}
}//end of else
}}
Output:
7 is prime number
Write a program to calculating area and perimeter of rectangle.
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);
}
}
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.
Example: double x;
int y=2;
float z=2.2f;
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 9 of 57
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.
“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;
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
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;
}
}}
2.DERIVED SYNTACTICAL CONSTRUCTS IN JAVA
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",
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);
}
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 57
}
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));
}
}
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(new InputStreamReader(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 57
}
}
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 57
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// ref refers to an A
object ref = a;
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
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 57
Types of Array:
1) One Dimensional
2) Two Dimensional
3) Multi Dimensional
Differentiate between String and String Buffer.
String String Buffer c
String is a major class String Buffer is a peer class of String
Length is fixed (immutable) Length is flexible (mutable)
Contents of object cannot be modified Contents of object can be modified
Object can be created by assigning String Objects can be created by calling constructor of
constants enclosed in double quotes. String Buffer class using “new”
Ex:- String s=”abc”; Ex:- StringBuffer s=new StringBuffer (“abc”);
Differentiate between class and interfaces.
Class Interface
1)doesn‟t Supports multipleinheritance 1) Supports multipleinheritance
2)”extend ” keyword is used to 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
}
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
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.
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
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"
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");
}
} }
Write a program to create a vector with five elements as (5,15, 25, 35, 45). Insert new element
st
at 2nd position. Remove 1 and 4th element from vector.
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 22 of 57
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));
}
}}
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 57
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();
}
}
}
3.INHERITANCE, INTERFACE AND PACKAGE
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
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 57
{ public static void main(String args[])
{ Gross_Salary s=new Gross_Salary("Sachin",20,1000,2000,7000);
s.Total_Sal();
}
}
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();
}
}
What is interface? Describe its syntax and features.
Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 28 of 57
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.
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 57
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();
}
}
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 57
{
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();
}
}
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 instance of 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 57
{
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");
}
}
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");
}
}
final class: We cannot extend a final class. Consider the below example:final class XYZ
{
}
Built-in exceptions:
Arithmetic exception: Arithmetic error such as division by zero.
ArrayIndexOutOfBounds Exception: Array index is out of bound
ClassNotFoundException
FileNotFoundException: Caused by an attempt to access a nonexistent file.
IO Exception: Caused by general I/O failures, such as inability to read from a file.
NullPointerException: Caused by referencing a null object.
NumberFormatException: Caused when a conversion between strings and number fails.
StringIndexOutOfBoundsException: Caused when a program attempts to access a
nonexistent character position in 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 out of stack space.
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 57
Eg:
class MyThread extends Thread
{
public void run()
{
for(int i = 1;i<=20;i++)
{
System.out.println(i);
}
}
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.
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 have equal
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 time period 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.
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 57
{
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();
}
}
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 57
// block of code to be executed before try block ends
}
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
getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.
import java.lang.*;
Mention the steps to add applet to HTML file. Give sample code.
Adding Applet to the HTML file:
Steps to add an applet in HTML document
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the body section of HTML
file.
2. Specify the name of the applet‟s .class file.
3. If the .class file is not in the current directory then use the codebase parameter to specify:-
a. the relative path if file is on the local system, or
b. the uniform resource locator(URL) of the directory containing the file if it is on a remote
computer.
4. Specify the space required for display of the applet in terms of width and height in pixels.
5. Add any user-defined parameters using <param> tags
6. Add alternate HTML text to be displayed when a non-java browser is used.
7. Close the applet declaration with the </APPLET> tag.
Open notepad and type the following source code and save it into file name
“Hellojava.java” import
java.awt.*; import
java.applet.*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello Java",10,100);
}}
Use the java compiler to compile the applet “Hellojava.java” file. C:\jdk>
Example:
<param name=”color” value=”red”>
Describe the applet life cycle in detail.
init(): The init() method is the first method to execute when the applet is executed. Variable declaration
and initialization operations are performed in this method.
start(): The start() method contains the actual code of the applet that should run. The start() method
executes immediately after the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab to another tab in the browser.
destroy(): The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed. stop() method executes just before when destroy() method is
invoked. The destroy() method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet display area. The paint() method
executes after the execution of start() method and whenever the applet or browser is resized.
• init()
• start()
• paint()
• stop()
• destroy()
iii) Fill Oval: Drawing Ellipses and circles: To draw an Ellipses or circles used fillOval() method can
be used. It draws the Solid Ellipses and circles.
Syntax: void fillOval(int top, int left, int width, int height)
The filled ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top and
left and whose width and height are specified by width and height to draw filled circle, specify the
same width and height the following program draws several ellipses and circle.
Example: g.fillOval(10,10,50,50);
v) drawLine ():
The drawLine() method is used to draw line which take two pair of coordinates, (x1,y1)
and (x2,y2) as arguments and draws a line between them.
The graphics object g is passed to paint() method.
Syntax: g.drawLine(x1,y1,x2,y2);
Example: g.drawLine(100,100,300,300;)
Write a program to create an applet for displaying circle, rectangle and triangle one below the
other and filled them with red, green and yellow respectively.
import java.awt.*; import java.applet.*;
/* <applet code="test.class" width=200 height=200>
</applet> */
}
}
Output:
import java.io.*;
class Model6B
{
public static void main(String[] args) throws Exception
{
int lineCount=0, wordCount=0;
String line = "";
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
FileWriter fw = new FileWriter("Sample.txt"); //create text file for writing
System.out.println("Enter data to be inserted in file: ");
String fileData = br1.readLine();
fw.write(fileData);
fw.close();
BufferedReader br = new BufferedReader(new FileReader("Sample.txt"));
while ((line = br.readLine()) != null)
{
lineCount++; // no of lines count
String[] words = line.split(" ");
wordCount = wordCount + words.length; // no of words count
}
System.out.println("Number of lines is : " + lineCount);
System.out.println("Number of words is : " + wordCount);
}}