Professional Documents
Culture Documents
Finaljava - Copy - Book (1) - Pages-8-111
Finaljava - Copy - Book (1) - Pages-8-111
2014
(New Syllabus) (2013-14 Batch Onwards)
JAVA PROGRAMMING
Time: 3 Hours Max.Marks:100
Note: Answer any ten questions from Part-A and any one full question from
each Unit in Part-B.
PART-A (10x2=20)
1. a) Define Byte code. Write the benefits of byte code.
b) Define scope and life time of a variable
c) Define stream. Name the two types of stream defined in Java.
d) Define array. Write the purpose of length member.
e) What are constructors?
f) What is the use of ‘this’ keyword in Java?
g) Define interface. Why it is used?
h) Define Package. Name any two advantages of using the package.
i) What is an exception? What are the advantages of exception
handler?
j) Write two ways of identifying whether the thread has ended.
k) Write the syntax of <applet> tag and also write the purpose
compulsory attributes.
l) Write the limitations of AWT components with respect to Swing.
PART-B
Unit – I
2. a) Write a note on java buzzwords. 6+4+5+5
b) Write a note on:
i) Increment and decrement operator
ii) Type conversion in expression.
c) With the syntax and example explain the process of reading a
character from the Keyboard.
d) Explain nested switch statement with syntax and example.
Process of Compilation
1
These variables are visible to the program only from the
beginning of its program block to the end of the program block.
When the program control leaves a block, all the variables in the
block will cease to exist.
The area of the program where the variable is accessible (i.e.
usable) is called its scope.
6
An exception is an error that occurs at run time. Using Java’s exception
handling subsystem you can, in a structured and controlled manner,
handle run-time errors.
o A principal advantage of exception handling is that it automates
much of the error handling code that previously had to be entered
“by hand” into any large program.
o For example, in some older computer languages, error codes are
returned when a method fails, and these values must be checked
manually, each time the method is called. This approach is both
tedious and error-prone.
o Exception handling streamlines error handling by allowing your
program to define a block of code, called an exception handler,
that is executed automatically when an error occurs.
o It is not necessary to manually check the success or failure of each
specific operation or method call.
o If an error occurs, it will be processed by the exception handler.
o Another reason that exception handling is important is that Java
defines standard exceptions for common program errors, such as
divide-by-zero or file-not-found.
o To respond to these errors, your program must watch for and
handle these exceptions.
o Also, Java’s API library makes extensive use of exceptions.
7
k)Write the syntax of <applet> tag and also write the purpose
compulsory attributes.
/HelloWorldApplet.java
importjava.applet.Applet;
import java.awt.*;
/*<APPLET CODE="HelloWorldApplet.class" width=500
height=400></APPLET>*/
10
the programmers to use the efficient functions to available in these
languages. Native methods are linked dynamically at runtime.
15
Java achieves this protection by confining a Java program to
the Java execution environment and not allowing it access to
other parts of the computer.
b)List and explain different primitive data types available in Java.
Java’s Primitive Types:
Every variable in Java has a data type. Data types specify the size and type of
values that can be stored. Java language is rich in its data types. The variety
of data types available allows the programmer to select the type appropriate
to the needs of the application. Data types in Java under various categories
are shown in the diagram.
Integer Types
Integer types can hold whole numbers such as 123, -96, and 5639. The
size of the values that can be stored depends on the integer data type
we choose. Java supports four types of integers as shown in fig. they are
byte,short,int, and long. Java does not support the concept of unsigned
types and therefore all Java values are signed meaning they can be
positive or negative.
Type Width in Bits Range
byte 8 -128 to 127
short 16 -32,768 to 32,767
int 32 -2,147,483,648 to 2,147,483,647
long 64 -9,223,372,036,854,775,808 to
-9,223,372,036,854,775,807
/* compute the number of Cubic inches in 1 cubic mile*/
class inches{
public static void main(String args[]){
long ci, im;
im=5280*12;
ci=im*im*im;
System.out.println(“There are”+ci+”cubic inches in cubic mile.”);
16
}
} output is : There are 254358061056000 cubic inches in cubic mile.
Floating Point Types:
Integer types can hold only whole numbers and therefore we use
another type known as floating point type or hold numbers containing
fractional parts such as 27.59 and -1.375 (known as floating point
constants). There are two kinds of floating point storage they are float
and double. The float type values are single-precision numbers while
the double types represent double precision numbers.
Type size Minimum value Maximum value
float 4bytes 3.4e.038 3.4e+038
double 8bytes 1.7e-308 1 1.7e+308
Floating Point
Float Double
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Character Type
In order to share character constants in memory, Java provides a character
data type called char. The char type assumes a size of 2 bytes but, basically, it
can hold only a single character.
Here is a program that demonstrates char variables:
// Demonstrate char data type.
classCharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}This program displays the following output:
17
ch1 and ch2: X Y
Boolean Type
1. Java has a simple type, called boolean, for logical values.
2. It can have only one of two possible values, true or false.
3. This is the type returned by all relational operators, such as a < b.
4. boolean is also the type required by the conditional expressions that
govern the control statements such as if and for.
// Demonstrateboolean values.
classBoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
} The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
c)With syntax and example explain the process of reading a string from the
keyboard.
To read a string from the keyboard, use the version of readLine( ) that is a
member of the BufferedReader class.
Its general form is shown here: String readLine( ) throws IOException
Example:// Read a string from console using a BufferedReader.
import java.io.*;
classBRReadLines {
public static void main(String args[])throws IOException
{
// create a BufferedReader using System.in
BufferedReaderbr = new
18
BufferedReader(newInputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
d)Explain while loop and do while loop with syntax and example.
While loop:
The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true.
Here is its general form: while(condition) {
// body of loop
}
The condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional
expression is true.
When condition becomes false, control passes to the next line of code
immediately following the loop.
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
When you run this program, it will “tick” ten times:
tick 10 tick 9 tick 8 tick 7 tick 6 tick 5
tick 4 tick 3 tick 2 tick 1
do-while loop:
The general form of the do statement is,
initialization;
do
{
19
Body of the loop
}while (test condition);
1. On reaching the do statement, the program proceeds to evaluate the
body of the loop first.
2. At the end of the loop, the test condition in the while statement is
evaluated.
3. If the condition is true, the program continues to evaluate the body of
the loop once again.
4. This process continues as long as the condition is true.
5. When the condition becomes false, the loop will be terminated and the
control goes to the statement that appears immediately after the while
statement.
6. The test condition is evaluated at the bottom of the loop.
7. Therefore the body of the loop is always executed at least once.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
Unit-II
4. a) Explain how to declare, initiate, initialize and use a one dimensional
array with example.
One-Dimensional Arrays:
A list of items can be given one variable name using only one subscript
and such a variable is called a single subscripted variable or a one
dimensional array.
Creating an Array :- Creation of an array involves three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
Declaration of arrays :- Arrays in Java may be declared in two forms:
Form1 - type arrayname[];
Form2 – type [] arrayname;
Examples:
int number[];
float average[];
int[] counter;
20
float[] marks;
Creation of Arrays :- After declaring an array, we need to create it in
the memory. Arrays can be created using new operator only.
Syntax: arrayname = new type[size];
Examples:
number = new int[5];
average = new float[10];
The variable number refers to an array of 5 integers and average refers
to an array of 10 floating point values.
It is also possible to combine the two steps – declaration and creation –
into one as shown below:
int number[] = new int[5];
Initialization of Arrays: Values can be stored into the array using
subscript. This process is known as initialization.
arrayname[subscript] = value;
Example : number[0] = 35;
1. Java creates arrays starting with a subscript 0 and ends with a value
one less than the size specified.
2. Java protects array from overruns and underruns. Trying to access an
array beyond its boundaries will generate an error message.
3. We can also initialize the arrays automatically when they are
declared.
4. The general form is Type arrayname[] = {list of values};
5. The array initializer is a list of values separated by commas and
surrounded by curly braces.
6. In the above form size is not given. The compiler allocates enough
space for all the elements specified in the list.
Example: int number[] = {35, 40, 20, 57,19};
It is possible to assign an array object to another. Example,
int a[] = {1,2,3};
int b[];
b = a;
Both the arrays a and b will have the same values.
b) With an example explain command line arguments.
Using Command-Line Arguments:
There may be occasions when we may like our program to at in a
particular way depending on the input provided at the time of
execution.
This is achieved in Java programs by using what are known as
command line arguments.
Command line arguments are parameters that are supplied to the
21
application program at the time of invoking it for execution.
// Display all command-line arguments.
class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
} Try executing this program, as shown here:
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this args[1]: is args[2]: a
args[3]: test args[4]: 100 args[5]: -1
c) With an example explain method overloading.
In Java, it is possible create methods that have the same name, but
different parameter lists and different definitions. This is called
method overloading.
Method overloading is used when objects are required to perform
similar tasks but using different input parameters.
When we call a method in an object, Java matches up the method
name first and then the number and type of the parameters to
decide which one of the definitions to execute.
This process is known as polymorphism.
Example:
// Demonstrate method overloading.
class OverloadDemo { output:
void test() { No parameters
System.out.println("No parameters"); a: 10
} a and b: 10 20
// Overload test for one integer parameter. double a: 123.25
void test(int a) { Result of
System.out.println("a: " + a); ob.test(123.25):
} 15190.5625
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a)
System.out.println("double a: " + a);
22
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
d)Write a note on:
i) Abstract class and Abstract method
Abstract Methods and Classes :- Abstract method must be
redefined in a subclass. In this way making overriding
compulsory. This is done using the modifier keyword abstract in
the method definition. Example:
abstract class Shape
{
………….
………….
abstract void draw();
…………
…………
}
when a class contains one or more abstract methods, it
should also be declared as abstract as shown in the above
example.
While using abstract classes to instantiate objects directly. For
example,
1. We cannot use abstract classes to instantiate objects directly.
For example,
Shape s = new Shape();
is illegal because Shape is an abstract class.
2. The abstract methods of an abstract class must be defined in its
subclass.
3. We cannot declare abstract constructors or abstract static
methods.
23
ii) Final class and Final method.
Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features,
there will be times when you will want to prevent it from
occurring. 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:
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!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B.
If you attempt to do so, a compile-time error will result.
F inal Prevents Inheritance
1. You can prevent a class from being inherited by preceding its
declaration with final.
2. Declaring a class as final implicitly declares all of its methods
as final, too.
3. As you might expect, it is illegal to declare a class as both
abstract and final since an abstract class is incomplete by itself
and relies upon its subclasses to provide complete
implementations. Here is an example of a final class:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is
declared as final.
5. a) Explain any 4 String methods with suitable example.
The String class contains several methods that operate on strings. Here
are the general forms for a few:
boolean equals(str) Returns true if the invoking string contains the same
24
character sequence as str
int length() Obtains the length of a string
char charAt(index) Obtains the character at the index specified by index
int compartTo(str) Returns less than zero if the invoking string is less
than str, greater than zero if the invoking string is
greater than str, and zero if the strings are equal.
int indexOf(str) Searches the invoking string for the substring
specified by str. Returns the index of the first match
or -1 on failure
// Some String operations.
Class StrOps{
public static void main (String args[]) {
String str1="When it comes to Web programming, Java is #1.”;
String str2= new String (str1);
String str3="Java Strings are powerful.”;
int result,idx;
char ch;
System.out.println(“Length of str1:”+str1.length());
//display str1, one char at a time.
for(int i=0; i<str1.length();i++)
System.out.prinln(str1.charAt(i));
System.out.prinln();
if(str1.equals(str2))
System.out.println(“str1 equals str2”);
else
System.out.prinln(“str1 does not equal str2”);
if(str1.equals(str3))
System.out.println(“str1 equals str3”);
else
System.out.prinln(“str1 does not equal str3”);
result=str1.compareTo(str3);
if(result==0)
System.out.println(“str1 and str3 are equal”);
else if(result<0)
System.out.prinln(“str1 is less than str3”);
else
System.out.println(“str1 is greater than str3”);
// assing a new string to str2
Str2=“One Two Three One”;
idx=str2.indexOf(“One”);
System.out.println(“Index of first occurrence of One:”+idx);
idx=str2.lastIndexOf(“One”);
25
System.out.println(“Index of last occurrence of One:”+idx);
} Output is :
} Length of str1:45
When it comes toWeb programming, Java is #1.
Str1 equal str2
Str1 does not equl str3
Str1 is greater than str3
Index of first occurrence of One:0
Index of last occurrence of One: 14
int reatArea()
{
int area = length * width;
26
return(area);
}
}
31
Note: The try block must be accompanied by at least one catch
block or the finally block.
Syntax:
try {
//block of code to monitor for errors
}
catch(ExcepTypel exOb){
// handler for ExcepType1
}
catch(ExcepType2 exOb){
// handler for ExcepType2
}
//….
finally{
// finally code
}
Example: // Use finally.
class UseFinally {
public static void genException(int what) {
int t;
int nums[] = new int[2];
System.out.println("Receiving " + what);
try {
switch(what) {
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error.
break;
case 2:
return; // return from try block
}
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
return; // return from catch
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
32
System.out.println("No matching element found.");
}
finally {
System.out.println("Leaving try.");
}
}
}
class FinallyDemo {
public static void main(String args[]) {
for(int i=0; i < 3; i++) {
UseFinally.genException(i);
System.out.println();
}
}
}
Here is the output produced by the program.
Receiving 0
Can't divide by Zero!
Leaving try.
Receiving 1
No matching element found.
Leaving try.
Receiving 2
Leaving try.
d)Define synchronization. With an example explain how synchronization is
achieved in multithread environment using synchronized methods.
Synchronization
When using multiple threads, it is sometimes necessary to
coordinate the activities of two or more.
The process by which this is achieved is called synchronization.
The most common reason for synchronization is when two or more
threads need access to a shared resource that can be used by only
one thread at a time.
For example, when one thread is writing to a file, a second thread
must be prevented from doing so at the same time.
Although creating synchronized methods within classes that you
create is an easy and effective means of achieving synchronization, it
will not work in all cases.
For example, you might want to synchronize access to some
method that is not modified by synchronized.
33
This is the general form of a synchronized block:
synchronized(objref){
//Statements to be synchronized
}
// This program uses a synchronized block.
class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target)
{
// synchronized block
target.call(msg);
}
}
34
}
class Synch1 {
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
7. a)Explain the Java’s access control mechanism using access modifier
Keyword.
Classes and packages are both means of encapsulating and
containing the namespace and scope of variables and methods.
Packages act as containers for classes’ and other subordinate
packages.
Classes act as containers for data and code.
The class is Java’s smallest unit of abstraction.
Because of the interplay between classes and packages, Java
addresses four categories of visibility for class members:
■Subclasses in the same package
■Non-subclasses in the same package
■Subclasses in different packages
■Classes that are neither in the same package nor subclasses
The visibility of an element is determined by its access
specification—private, public, protected, or default—and the
package in which it resides.
Thus, the visibility of an element is determined by its visibility
within a class and its visibility within a package.
Private Default Protected Public
35
Same class Yes Yes Yes Yes
Same package No Yes Yes Yes
subclass
Same package No Yes Yes Yes
non-subclass
Different package No Yes Yes Yes
subclass
Different package No No Yes Yes
non-subclass
b) With an example explain how a user defined exception is defined and
used for handling errors.
Creating user defined Exception Subclasses
There may be times when we like to throw our own exceptions and we
do this by using the keyword throw.
Syntax: throw new throwable_subclass;
Example:
import java.lang.Exception;
class NewException extends Exception
{
NewException (String message)
{
super(message);
}
}
class TestNewException
{
public static void main (String args[])
{ Output:
int m =5, n = 2000; New exception caught
try
Very small number
{
float o = (float) m / (float) n; This is closing
if(o<0.01)
{
throw new NewException("Very small number");
}
}
catch (NewException e)
{
System.out.println("New exception caught");
System.out.println(e.getMessage());
}
36
finally
{
System.out.println("This is closing");
}
}
}
c) With an example explain how a thread created by implementing runnable
interface.
Implementing The ‘Runnable’ Interface :- We can create thread by
implementing Runnable interface. The Runnable interface declares the
run() method that is required for implementing threads in our
program. The steps required to implement thread are as follows:
1. Declare the class as implementing the Runnable interface.
2. Implement the run() method.
3. Create a thread by defining an object that is instantiated from this
“runnable” class.
4. Call the thread’s start() method to run the thread.
Program using Runnable interface :-
class X implements Runnable //step 1
{
Output:
public void run() //step 2
{ End of main Thread
for(int I=1; I<=10; I++) Thread X : 1
{ Thread X : 2
System.out.println(“\tThreadX : “+I); Thread X : 3
} Thread X : 4
} Thread X : 5
}
class RunnableTest Thread X : 6
{ Thread X : 7
public static void main(String srgs[]) Thread X : 8
{ Thread X : 9
X runnable = new X(); Thread X : 10
Thread threadX = new Thread(runnable); End //step 3
of ThreadX
threadX.start(); //step 4
System.out.println(“End of main Thread “);
}
}
d) Write a note on Thread Priority.
In Java, each thread is assigned a priority, which affects the order in
which it is scheduled for running.
37
The threads of the same priority are given equal treatment by the
Java scheduler and, therefore, they share the processor on a first-
come, first-serve basis.
Java permits us to set the priority of a thread using the setPriority()
method as follows:ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread’s priority
is set.
The Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value
between 1 and 10.
The default setting is NORM_PRIORITY.
Most user-level processes should use NORM_PRIORITY, plus or
minus 1.
Background tasks such as network I/O and screen repainting should
use a value very near to the lower limit.
Example:
class A extends Thread
{
public void run()
{
System.out.println(“threadA started”);
for (int i=1; i<=4; i++)
{
System.out.println(“\tFrom Thread A : i= “ +i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run()
{
System.out.println(“threadB started”);
for (int j=1; j<=4; j++)
{
System.out.println(“\tFrom Thread B : j = “ +j);
}
System.out.println(“Exit from B”);
38
}
}
class C extends Thread Output:
{ Start thread A
public void run() Start thread B
{
Start thread C
System.out.println(“threadC started”);
for (int k=1; k<=4; k++) threadB started
{ From Thread B : j =1
System.out.println(“\tFrom Thread C : k = “ +k); From Thread B : j =2
} ThreadC started
System.out.println(“Exit from C”); From Thread C : k =1
}
From Thread C : k =2
}
class ThreadPriority From Thread C : k =3
{ From Thread C : k =4
public static void main(String args[]) Exit from C
{ End of main thread
A threadA = new A(); From Thread B : j =3
B threadB = new B(); From Thread B : j =4
C threadC = new C();
Exit from B
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1); ThreadA started
threadA.setPriority(Thread.MIN_PRIORITY); From Thread A : i =1
System.out.println(“Start thread A”); From Thread A : i =2
ThreadA. Start(); From Thread A : i =3
System.out.println(“Start thread B”); From Thread A : i =4
ThreadB. Start(); Exit from A
System.out.println(“Start thread C”);
ThreadC. Start();
System.out.println(“End of main thread”);
}
}
Unit-IV
8. a)With an example explain passing parameters to an applet.
You can pass parameters to your applet.
To do so, use the PARAM attribute of the APPLET tag, specifying the
parameter’s name and value.
To retrieve a parameter, use the getParameter( ) method, defined by
Applet.
Its general form is shown here:
String getParameter(String paramName)
39
Here, paramName is the name of the parameter.
It returns the value of the specified parameter in the form of a String
object.
Here is an example that demonstrates passing parameters:
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Communicating Applet on the Web!</h1>
<APPLET CODE="HelloAppletMsg.class" width=500 height=400>
}
42
c) What is the purpose of layout managers? With an example
explain the use of GridLayout.
• A layout manager automatically arranges your controls within a window
by using some type of algorithm.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the
LayoutManager interface.
• The layout manager is set by the setLayout( ) method.
GridLayout
GridLayout lays out components in a two-dimensional grid. When you
instantiate a GridLayout, you define the number of rows and columns.
The constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout.
The second form creates a grid layout with the specified number of rows
and columns.
The third form allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
43
d) With an example explain how to create a swing applet.
A Swing applet extends JApplet rather than Applet. JApplet is derived
from Applet.
Thus, JApplet includes all of the functionality found in Applet and
adds support for Swing. J
Applet is a top-level Swing container.
Swing applets use the same four lifecycle methods : init( ), start( ), stop(
), and destroy( ).
A Swing applet will not usually override the paint( ) method
Here is an example of a Swing applet
// A simple Swing-based applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet {
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
// Initialize the applet.
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}// This applet does not need to override start(), stop(), or destroy().
// Set up and initialize the GUI.
private void makeGUI() {
// Set the applet to use flow layout.
setLayout(new FlowLayout());
// Make two buttons.
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
44
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
}
});// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
}
});// Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
}
}
9. a) What is the purpose of MouseListener interface? With syntax
and example explain any five methods of MouseListener interface.
To handle mouse and mouse motion events, you must implement the
MouseListener and the MouseMotionListener interfaces.
The MouseListener interface defines five methods.
If a mouse button is clicked, mouseClicked( ) is invoked.
When the mouse enters a component, the mouseEntered( ) method is
called.
When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased( ) methods are invoked
when a mouse button is pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
45
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this); Register this class as a listener
for mouse event
}// Handle mouse clicked.
public void mouseClicked(MouseEvent me) { This, and the
other event handlers, respond to mouse events.
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}//
// Handle mouse entered.
public void mouseEntered(
mouseEntered(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}//
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed
mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
46
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " +me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
} Sample output from this program is shown here:
}
b) Name the controls required for creating a menu. with an example
explain creation of menu.
In general, a menu bar contains one or more Menu objects.
Each Menu object contains a list of MenuItem objects.
Each MenuItem object represents something that can be selected by
the user.
Since Menu is a subclass of MenuItem, a hierarchy of nested
submenus can be created.
It is also possible to include checkable menu items.
Following is an example
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
47
import java.applet.*;
/*
<applet code="Menu Demo" width=250 height=250>
</applet>
*/
// Create a subclass of Frame.
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar); // create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4, item5;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("-"));
file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem item6, item7, item8, item9;
edit.add(item6 = new MenuItem("Cut"));
edit.add(item7 = new MenuItem("Copy"));
edit.add(item8 = new MenuItem("Paste"));
edit.add(item9 = new MenuItem("-"));
Menu sub = new Menu("Special");
MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First"));
sub.add(item11 = new MenuItem("Second"));
sub.add(item12 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
48
edit.add(test);
mbar.add(edit); // create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
// create an object to handle window //events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
class MyWindowAdapter extends WindowAdapter {
49
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}// Handle action events.
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
50
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}// Handle item events.
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}// Create frame window.
public class MenuDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
public void start() { f.setVisible(true); }
public void stop() { f.setVisible(false); }
}
c) With syntax and example explain the purpose of showStatus()method.
In addition to displaying information in its window, an applet can also
output a message to the status window of the browser or applet viewer
on which it is running.
To do so, call showStatus( ), which is defined by Applet, with the string
that you want displayed.
The general form of showStatus( ) is shown here:
void showStatus(String msg)
Here, msg is the string to be displayed.
The following applet demonstrates showStatus( ):
// Using the Status Window.
import java.awt.*;
import java.applet.*;
51
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet
{
// Display msg in applet window.
public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
} Sample output from this program is shown here:
}
53
Objects:
Objects are the basic run time entities in an object oriented system
which is used to solve the real world problems. Objects are instances
(variables) of a class. Every object of a class has its own identity,
attributes and behavior.
Identity refers to the name of the object.
Attributes refer to the properties of the object, and
Behavior refers to the functions that the object can perform.
The attribute and behavior together define the object. Consider the
following example.
class - student
member variables - name, roll number, mark1,mark2.
Member functions - total(), average() and Display()
Here the individual students can be the objects of the class Objects -
std1,std2
Class:
A Class is collection of object of similar type. Classes are user-defined
types that assist in representing and solving complex, real world
problems. A class is a collection of member variables of different types
(data) combined with functions (methods) that operate on a data.
The variables in the class are called member variables or member data
and the functions in the class are called member functions.
e) What is the use of finalize () method in java?
Constructor is used to initialize an object when it is declared. This
process is known as initialization. Java supports a concept called
finalization, which is just opposite to initialization.
Java run-time is an automatic garbage collecting system. It
automatically frees up the memory resources used by the objects.
But object may hold other non-object resources such as file
descriptors or window system fonts.
The garbage collector cannot free these resources. In that case we
must use finalizer method. This is similar to destructor in C++.
The finalize( ) method has this general form:
protected void finalize( )
{
54
// finalization code here
} It can be added to any class.
Java calls that method whenever it is about to reclaim the space for
that object. The finalize() method should explicitly define the task
to be performed.
f) Write the syntax for defining a one dimensional array in java.
One-Dimensional Arrays:
A list of items can be given one variable name using only one
subscript and such a variable is called a single subscripted variable or a
one dimensional array.
To declare a one-dimensional array, you can use this general form:
type array-name [ ] = new type [size];
Example: int sample[]=new int [10];
g) List any four API packages of Java
Package name Contents
java.lang Language Support classes. These are classes that
Java compiler itself uses and therefore they are
automatically imported. They include classes for
primitive types, strings, math functions, threads and
exceptions.
java.util Language utility classes such as vectors, hash tables,
random numbers, date etc.
java.io Input/output support classes. They provide facilities
for the input and output of data
java.awt Set of classes for implementing graphical user
interface. They include classes for windows,
buttons, lists, menus and so on
java.net Classes for networking. They include classes for
communicating with local computers as well as with
internet servers
java.applet Classes for creating and implementing applets.
h) How to assign priority to thread? What is the default priority?
In Java, each thread is assigned a priority, which affects the order in
which it is scheduled for running.
The threads of the same priority are given equal treatment by the
Java scheduler and, therefore, they share the processor on a first-
come, first-serve basis.
Java permits us to set the priority of a thread using the setPriority()
method as follows:ThreadName.setPriority(intNumber);
55
The intNumber is an integer value to which the thread’s priority
is set.
The Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value
between 1 and 10.
The default setting is NORM_PRIORITY.
Most user-level processes should use NORM_PRIORITY, plus or
minus 1.
Background tasks such as network I/O and screen repainting should
use a value very near to the lower limit.
i) Differentiate the keywords throw and throws.
Using throws
In some cases, if a method generates an exception that it does not
handle, it must declare that exception in a throws clause. Here is the
general form of a method that includes a throws clause:
re-type MethName(Param-list) throws except-list {
//body
}
Using throw:
It is possible to manually throw an exception by using the throw
statement. Its general form is shown here: throw exceptOb;
Here, exceptOb must be an object of an exception class derived from
Throwable.
j) Write the syntax of applet tag.
Refer question paper Nov/Dec 2014 Part A K Answer
k) What is the purpose of repaint () method?
Whenever your applet needs to update the information displayed in
its window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT’s Component class.
It causes the run-time system to execute a call to your applet’s paint(
) method.
For example, if part of your applet needs to output a string, it can
store this string in a String variable and then call repaint( ).
Inside paint( ), you will output the string using drawString( ).
The simplest version of repaint( ) is shown here:
56
void repaint( )
This version causes the entire window to be repainted.
l) What is a listener?
o A listener is an object that is notified when an event occurs.
o It has two major requirements.
o First, it must have been registered with one or more sources to
receive notifications about specific types of events.
o Second, it must implement methods to receive and process these
notifications.
o The methods that receive and process AWT events are defined in a
set of interfaces found in java.awt.event.
o For example, the MouseMotionListener interface defines methods
that receive notifications when the mouse is dragged or moved.
o Any object may receive and process one or both of these events if it
provides an implementation of this interface
PART-B
Unit-I
2. a) Explain the while and do...while statement with syntax and an example.
Refer Question paper Nov/December 2014 Part B Unit-I 3 d answer
b) Explain the process of reading string from the keyboard with suitable
example.
Refer Question paper Nov/December 2014 Part B Unit-I 3 c answer
c) Write a note on Java streams. (8+6+6)
Java defines two types of streams: byte and character.
Byte Streams
1. Byte streams provide a convenient means for handling input and
output of bytes.
2. Byte streams are used, for example, when reading or writing binary
data.
Character Streams
1. Character streams provide a convenient means for handling input
and output of characters.
2. They use Unicode and, therefore, can be internationalized.
3. Also, in some cases, character streams are more efficient than byte
streams.
The Byte Stream Classes
1. Byte streams are defined by using two class hierarchies. :
InputStreamandOutputStream.
2. Each of these abstract classes has several concrete subclasses that
handle the differences between various devices, such as disk files,
57
network connections, and even memory buffers.
3. To use the stream classes, you must import java.io.
4. The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement.
5. Two of the most important are read( ) and write( ), which,
respectively, read and write bytes of data. Both methods are declared as
abstract inside InputStream and OutputStream.
The Character Stream Classes
1. Character streams are defined by using two class hierarchies: Reader
and Writer.
2. These abstract classes handle Unicode character streams.
3. Java has several concrete subclasses of each of these.
4. The abstract classes Reader and Writer define several key methods
that the other stream classes implement.
5. Two of the most important methods are read( ) and write( ), which
read and write characters of data, respectively.
The Predefined Streams
1. All Java programs automatically import the java.lang package.
2. This package defines a class called System, which encapsulates
several aspects of the run-time environment.
3. System also contains three predefined stream variables: in, out, and
err.
4. These fields are declared as public, static, and final within System.
5. This means that they can be used by any other part of your program
and without reference to a specific System object.
a. System.out refers to the standard output stream.
b. System.in refers to standard input, which is the keyboard by default.
c. System.err refers to the standard error stream
d. System.in is an object of type InputStream;
e. System.out and System.err are objects of type PrintStream.
58
* Multiplication C=a*b=50
/ Division C=a/b=2
% Remainder C=a%b=0
60
System.out.println(" !a = " + g);
}
}
b) List and explain different primitive data types available in Java.
Refer Question paper Nov/December 2014 Part B Unit-I 3 b answer
c) Explain any three forms of for loop with suitable example. (6+6+8)
Some Variations on the for Loop: The for is one of the most versatile
statements in the Java language because it allows a wide range of
variations. For example, multiple loop control variables can be used.
Consider the following program:
// use commas in a for loop.
class comma {
public static void main(String args[]) {
inti , j;
for (i=0,j=10;i<j;i++,j--) //notice the two loop control variables
System.out.println(“i and j:”+i+“ ”+j);
}
} output:
i and j: 0 10
i and j: 1 9
i and j: 2 8
i and j: 3 7
i and j: 4 6
Missing Pieces
Some interesting for loop variations are created by leaving pieces of the
loop definition empty. In Java, it is possible for any or all of the
initialization, condition, or iteration portions of the for loop to be blank.
For example, consider the following program:
// parts of the for can be empty
class empty {
public static void main(String args[]) {
inti ;
for (i=0;i<10;){ // iteration expression is missing
System.out.println(“#pass#”+i);
i++; // increment loop var
}
}
} output: #pass #0 #pass #1 #pass #2 #pass #3 #pass #4# pass #5
# pass #6 # pass #7# pass #8 # pass #9 # pass #10
The Infinite Loop
61
You can create an infinite loop (a loop that never terminates) using the for
by leaving the conditional expression empty. For example, the following
fragment shows the way most Java programmers create an infinite loop:
for(; ;)// intentionally infinite loop
{
//……
} This loop will run forever
Loops with No Body
In Java, the body associated with a for loop (or any other loop) can be
empty. This is because a null statement is syntactically valid. Body-less
loops are often useful. For example, the following program uses one to
sum the numbers 1 through 5:
// the body of the loop can be empty
class empty3 {
public static void main(String args[]) {
inti, sum=0;
// sum the number through 5
for (i=1;i<=5;sum+=i++); //no body in this loop
System.out.println(“sum is”+sum);
}
} output : sum is 15
Unit-II
4. a) What is a class? Explain how objects are created from a class in Java
with a suitable program example.(8+6+6)
A class is a user defined data type with a template that serves to
define its properties.
Once the class type has been defined, we can create variables of that
type using declarations that are similar to the basic type declarations.
In Java, these variables are termed as instances of class, which are
the actual objects.
The basic form of a class defination is:
class classname [extends superclassname]
{
[variable declarations;]
[methods declaration;]
}
classname and superclassname are any valid Java identifiers.
The keyword extends indicates that the properties of the
superclassname class are extended to the class classname class.
62
This concept is known as inheritance.
Creating Objects :-
1. An object in Java is a block of memory that contains space to store all
the instance variables.
2. Creating an object is referred to as instantiating an object.
3. The new operator creates an object of the specified class and returns a
reference to that object.
4. Example :
Rectangle rect1; //declare
rect1 = new Rectangle(); //instantiate
The first statement declares a variable to hold the object reference and the
second one assigns the object reference to the variable.
5. Both statements can be combined as shown below:
Rectangle rect1 = new Rectangle();
Example:
class Rectangle
{
int length, width;
void getData(int x, int y)
{
length = x;
width = y;
}
int reatArea()
{
int area = length * width;
return(area);
}
}
class RectArea //class with main method
{
public static void main(String args[])
{
int area1, area2;
Rectangle rect1 = new Reactangle(); //creating objects
Rectangle rect2 = new Reactangle();
rect1.length =15; //Accessing variables
rect1.width = 10;
area1 = rect1.length * rect1.width;
rect2.getData(10,20); //Accessing methods
area2=rect2.rectArea();
System.out.println(“Area1 = “+area1);
63
System.out.println(“Area2 = “+area2);
}
}Output: Area1 = 150 Area2 = 240
b)Explain method overriding with suitable example.
When a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() { // This shows() in B overrides the one defined by A
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}The output produced by this program is shown here: k: 3
c) Explain how to return an object from a method with suitable example.
64
Returning Objects
A method can return any type of data, including class types that you
create. For example, in the following program, the incrByTen( )
method returns an object in which the value of a is ten greater than it is
in the invoking object.
/ Returning an object.
class Test {
int a;
Test(int i) { The output generated by this
a = i; program is shown here:
}
ob1.a: 2
Test incrByTen() {
Test temp = new Test(a+10); ob2.a: 12
return temp; ob2.a after second increase: 22
}
}
class RetOb { As you can see, each time
public static void main(String args[]) { incrByTen( ) is invoked, a new
Test ob1 = new Test(2); object is created, and a
Test ob2; reference to it is returned to
ob2 = ob1.incrByTen();
the calling routine.
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase:"+ob2.a);
}
}
5. a) What is method over loading? Explain with a suitable example.
Refer question paper nov/dec 2014 unit-II Part –B 4 c answer
b) Explain the use of command-line arguments in Java with suitable
example.
Refer question paper nov/dec 2014 unit-II Part –B 4 b answer
c) Explain single inheritance with suitable example. (8+6+6)
Refer question paper nov/dec 2014 unit-II Part –B 5 d answer
Unit-III
6. a) Explain how to create and implement interface using suitable example.
Refer Question paper nov/dec 2014 Part-A 1 g answer and
Refer Question paper nov/dec 2014 Part-B Unit-III 6 b answer
b) List and explain any 6 built-in exceptions of Java.(8+6+6)
65
Exception Meaning
ArithmeticException Arithmetic error, such as integer
divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of
an incompatible type
NumberFormatException Invalid conversion of a string to a
numeric format
ClassNotFoundException Class not found
illegalArgumentException Illegal argument used to invoke a
method
NoSuchMethodException A requested method does not exist
NullPointerException Invalid use of a null reference
c) Explain how to create user defined exceptions in Java with example.
Refer Question paper nov/dec 2014 Part-B Unit-III 7b answer
7. a) Explain the process of creating a thread by using thread class with
suitable example.(8+6+6)
Extending The Thread Class:- There are three steps to make our class
runnable as interface.
1. Declare the class as extending the Thread class.
2. Implement the run() method that is responsible for executing the
sequence of code that the thread will execute.
3. Create a thread object and call the start() method to initiate the thread
execution.
Declaring the Class :-The thread class can be extended as follows:
Class MyThread extends Thread
{
…………..
…………..
…………..
}
Implementing the run() Method :- The run() method has been inherited
by the class MyThread. We have to override this method in order to
implement the code to be executed by our thread. The basic
implementation of run() is as follows:
public void run()A
{
………….
…………. //thread code here
………….
}
66
When we start the new thread, Java calls the thread’s run() method. In
thread all the action takes place in thread.
S tarting New Thread :- The following statements actually creates and run
an instance of thread class.
MyThread AThread = new MyThread();
AThread.start(); //invokes run() method
The first line instantiates a new object of class MyThread, The thread is in
a newborn state.
The second line calls the start() method causing the thread to move into
runnable state. Then, the Java runtime will schedule the thread to run by
invoking its run() method. Now the thread is in the running state.
An example of using the thread class :- Output:
class A extends Thread
From Thread A : I =1
{
public void run() From Thread A : I =2
{ From Thread B : j =1
for(int I=1; I<=5; I++) From Thread B : j =2
{ From Thread C : k =1
System.out.println(“\tFrom Thread A : I =” +I); From Thread C : k =2
} From Thread A : I =3
System.out.println(“Exit from A”);
} From Thread A : I =4
} From Thread B : j =3
class B extends Thread From Thread B : j =4
{ From Thread C : k =3
public void run() From Thread C : k =4
{ From Thread A : I =5
for(int j=1; j<=5; j++)
Exit from A
{
System.out.println(“\tFrom Thread B : j =” +j); From Thread B : j =5
} Exit from B
System.out.println(“Exit from B”); From Thread C : k =5
} Exit from C
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5; k++)
{
System.out.println(“\tFrom Thread C : k =” +k);
}
67
System.out.println(“Exit from C”);
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
b) Illustrate the use of multiple catch statements with suitable example.
Using try and catch
you can associate more than one catch statement with a try. In fact, it is
common to do so. However, each catch must catch a different type of
exception. Here is the general form of the multiple try/catch exception
handling blocks:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler forExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler forExceptionType2
}
// ...
For example, the program shown here catches both array boundary
and divide-by-zero errors: // Use multiple catch statements.
class ExcDemo4 {
public static void main(String args[]) {
// Here, numer is longer than denom.
int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
int denom[] = { 2, 0, 4, 4, 0, 8 }; Output is: 4 / 2 is 2
for(int i=0; i<numer.length; i++) { Can't divide by Zero!
try { 16 / 4 is 4
System.out.println(numer[i] + " / " + 32 / 4 is 8
denom[i] + " is " + Can't divide by Zero!
numer[i]/denom[i]); 128 / 8 is 16
} No matching element found.
catch (ArithmeticException exc) { No matching element found.
68
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
}
}
}
c) Explain exception handling in Java with suitable example.
Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
They form an interrelated subsystem in which the use of one implies
the use of another.
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.
Your code can catch this exception using catch and handle it in
some rational manner.
System-generated exceptions are automatically thrown by the Java
run-time system.
To manually throw an exception, use the keyword throw.
In some cases, an exception that is thrown out of a method must be
specified as such by a throws clause.
Any code that absolutely must be executed upon exiting from a try
block is put in a finally block.
A Simple Exception Example:
class ErrorCheck
{
public static void main (String args[])
{
int a = 20;
int b = 10;
int c = 10;
int x, y;
try
{
x = a/(b-c);
}
catch(ArithmeticException e)
69
{
System.out.println ("Division by zero error");
}
y = a/(b+c);
System.out.println("The value of y is "+y);
}
} Output:
Division by zero error
The value of y is 1
Unit-IV
8. a) Explain how to create an Applet in java with suitable example.
//HelloWorldApplet.java
import java.applet.Applet;
import java.awt.*;
/*<APPLET CODE="HelloWorldApplet.class" width=500 height=400>
</APPLET>*/
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString ("Hello World of Java!",25, 25);
}
} Embedding Applet in Web Page
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Java Applet on the Web!</h1>
<APPLET CODE="HelloWorldApplet.class" width=500 height=400>
</APPLET>
</body>
</HTML>
This applet begins with two import statements.
The first imports the Abstract Window Toolkit classes.
Applets interact with the user (either directly or indirectly) through the
AWT, not through the console-based I/O classes.
The AWT contains support for a window-based, graphical user
interface.
The next import statement imports the applet package contains the
class Applet.
70
Every applet that you create must be a subclass (either directly or
indirectly) of Applet.
The next line in the program declares the class HelloWorldApplet.
This class must be declared as public because it will be accessed by
outside code.
Inside HelloWorldApplet, paint( ) is declared.
This method is defined by the AWT Component class (which is a
superclass of Applet) and is overridden by the applet.
paint( ) is called each time the applet must redisplay its output.
paint( ) is also called when the applet begins execution.
The paint( ) method has one parameter of type Graphics.
This parameter will contain the graphics context, which describes the
graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
Inside paint( ), there is a call to drawString( ), which is a member of the
Graphics class.
This method outputs a string beginning at the specified X, Y location.
It has the following general form: void drawString(String message, int
x, int y)
b) List and explain the components of Delegation Event Model.
The Delegation Event Model
Its concept is quite simple: a source generates an event and sends it to
one or more listeners.
In this scheme, the listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.
A user interface element is able to “delegate” the processing of an
event to a separate piece of code.
In the delegation event model, listeners must register with a source in
order to receive an event notification.
Events
In the delegation model, an event is an object that describes a state
change in a source.
Among other reasons, an event can be generated as a consequence of a
person interacting with the elements in a graphical user interface, such
as pressing a button, entering a character via the keyboard, selecting an
item in a list, and clicking the mouse.
Event Sources
An event source is an object that generates an event.
A source must register listeners in order for the listener to receive
notifications about a specific type of event.
71
Each type of event has its own registration method. Here is the general
form: public void addType Listener (Type Listener el)
Here, Type is the name of the event, and el is a reference to the event
listener.
For example, the method that registers a keyboard event listener is
called addKeyListener( ).
The method that registers a mouse motion listener is called
addMouseMotionListener( ).
When an event occurs, all registered listeners are notified and receive a
copy of the event object.
A source must also provide a method that allows a listener to unregister
an interest in a specific type of event.
The general form of such a method is this:
public void removeType Listener (Type Listener el)
Here, Type is the name of the event, and el is a reference to the event
listener.
For example, to remove a keyboard listener, you would call
removeKeyListener( ).
The methods that add or remove listeners are provided by the source
that generates events.
For example, the Component class provides methods to add and
remove keyboard and mouse event listeners.
Event Listeners
A listener is an object that is notified when an event occurs.
It has two major requirements.
First, it must have been registered with one or more sources to receive
notifications about specific types of events.
Second, it must implement methods to receive and process these
notifications.
The methods that receive and process AWT events are defined in a set
of interfaces found in java.awt.event.
For example, the MouseMotionListener interface defines methods that
receive notifications when the mouse is dragged or moved.
Any object may receive and process one or both of these events if it
provides an implementation of this interface
c) Explain the advantages of Swing. (8+6+6)
Swing components facilitate efficient graphical user interface (GUI)
development. These components are a collection of lightweight visual
components. Swing components contain a replacement for the
heavyweight AWT components as well as complex user-interface
components such as trees and tables.
72
Swing components contain a “pluggable look and feel (PL&F)”. This
allows all applications to run with the native look and feel on different
platforms. PL&F allows applications to have the same behavior on
various platforms. JFC contains operating systems neutral look and
feel.
Swing components do not contain peers. Swing components allow
mixing AWT heavyweight and swing lightweight components in an
application. The major difference between lightweight and heavyweight
components is that lightweight components can have transparent pixels
while heavyweight components are always opaque. Lightweight
components can be non-regular while heavyweight components are
always rectangular.
Swing components are JavaBean compliant. This allows components to
be used easily in a Bean aware applications building program. The root
of the majority of the swing hierarchy is the Jcomponent class. The
class is an extension of the AWT container class.
Swing components comprises of a large percentage of the JFC release.
The swing component toolkit consists of over 250 pure java classes and
75 interfaces contained in about 10 packages. They are used to build
lightweight user interface. Swing consists of user interface(UI) classes
and non user interface classes. The non-UI classes provide services and
other operations for the UI classes.
9. a) Explain how to pass parameter to an applet with a suitable example.
Refer question paper nov/Dec 2014 part B unit IV 8 a answer
b) List and explain different Event Listener Interfaces.(8+6+6)
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a
component is hidden, moved, resized, or shown
ContainerListener Defines two methods to recognize when a
component is added to or removed from a
container
FocusListener Defines two methods to recognize when a
component gains or losses keyboard focus
ItemListener Defines one method to recognize when the state of
an item changes.
KeyListener Defines three methods to recognize when a key is
pressed, released, or typed.
MouseListener Defines five methods to recognize when the
mouse is clicked, enters a component, exits a
73
component, is pressed, or is released
MouseMotionListener Defines two methods to recognize when the
mouse is dragged or moved
MouseWheelListener Defines one method to recognize when the mouse
wheel is moved.
TextListener Defines one method to recognize when a text
value changes.
WindowFocusListener Defines two methods to recognize when a window
gains or losses input focus.
WindowListener Defines seven methods to recognize when a
window is activated, closed, deactivated,
deiconified, iconified, opened, or quit
c) Mention the purpose of different layout managers available in Swing.
The layout manager controls the position of components within a
container. Java offers several layout managers.
Most are provided by the AWT (within java.awt), but Swing adds a
few of its own. All layout managers are instances of a class that
implements the LayoutManager interface.
Here is a list of a few of the layout managers available to the Swing
programmer:
FlowLayout A simple layout that positions components left-to-
right, top-to-bottom (Positions components right-
to-left for some cultural settings)
BorderLayout Positions components within the center or the
borders of the container. This is the default layout
for a content pane
GridLayout Lays out components within a grid
GridBagLayout Lays out different size components within a
flexible grid
BoxLayout Lays out components vertically or horizontally
within a box
SpringLayout Lays out components subject to a set of constraings
BorderLayout is implements a layout style that defines five
locations to which a component can be added. The first is the
center. The other four are the sides (i.e., borders), which are called
north, south, east, and west.
FlowLayout lays out components one row at a time, top to bottom.
When one row is full, layout advances to the next row. If you resize
the frame, the position of the components will change.
74
Credit Based Third Semester B.C.A Degree Examination, May 2016
(New Syllabus) (2013-14 Batch Onwards)
JAVA PROGRAMMING
Time: 3 Hours Max.Marks:100
Note: Answer any ten questions from Part-A and anyone full question from
each Unit in Part-B.
PART-A (10x2=20)
1. a) What is an Applet?
Applets are small Java programs that are embedded in Web pages.
They can be transported over the Internet from one computer (web
server) to another (client computers).
They transform web into rich media and support the delivery of
applications via the Internet.
b) List any four primitive data types available in Java.
Integer
Float
Character
Boolean
c) What is stream? List different types of streams defined by Java.
Refer question paper nov/dec 2014 part A 1 C answer
d) What do you mean by type conversion in Java? Give an example.
Refer question paper nov/dec 2014 part B 2 b ii answer
e) What is the purpose of final variable?
Final Variables and Methods: - All the variables and methods can be
overridden by default in subclasses. If we wish to prevent the subclasses
from overriding the members of the superclass, we can declare them as
final using the keyword final as a modifier.
Example:
finalint size = 100;
final void showstatus() { ……….. }
Making a method final ensures that the functionality defined in this
method will never be altered in any way. Similarly, the value of a final
variable can never be changed. Final variables behave like a class
variables and they do not take any space on individual objects of the
class.
f) What is the purpose of super() keyword in Java?
• A subclass can call a constructor defined by its superclass by use of the
following form of super: super(arg-list);
75
• Here, arg-list specifies any arguments needed by the constructor in the
superclass.
• super( ) must always be the first statement executed inside a subclass’
constructor.
• Example program:
class Room
{
int length, breadth;
Room(int x, int y)
{
length = x;
breadth = y;
}
int area()
{
return(length * breadth);
}
}
classBedRoom extends Room
{
int height;
BedRoom(int x, int y, int z)
{
super(x,y); //pass values to super class
height = z;
}
int volume()
{
return(length * breadth * height);
}
}
classInherTest
{
public static void main(String args[])
{
BedRoom room1 = new BedRoom(14,12,10);
int area1 = room1.area(); //super class method
int volume1= room1.volume(); //base class method
System.out.println(“Area = “+area1);
System.out.println(“Volume = “+volume1);
}
}Output: Area = 168 Volume = 1680
76
g) Define package. Give one advantage of package.
Refer question paper nov/December 2014 Part A 1 h answer
h) List any four built-in exceptions in Java.
Exception Meaning
ArithmeticException Arithmetic error, such as integer
divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of
an incompatible type
NumberFormatException Invalid conversion of a string to a
numeric format
ClassNotFoundException Class not found
i) What is multithreading?
A multithreaded program contains two or more parts that can
run concurrently.
Each part of such a program is called a thread, and each thread
defines a separate path of execution.
Thus, multithreading is a specialized form of multitasking.
j) List the key items of a swing GUI.
A Swing GUI consists of two key items: components and containers.The
difference between the two is found in their intended purpose:
A component is an independent visual control, such as a push button
or text field. A container holds a group of components.
Thus, a container is a special type of component that is designed to
hold other components.
Furthermore, in order for a component to be displayed, it must be
held within a container.
Thus, all Swing GUIs will have at least one container.
Because containers are components, a container can also hold other
containers.
This enables Swing to define what is called a containment hierarchy, at
the top of which must be a top-level container.
77
In a multithreaded program, sometimes two or more threads will share
the same variable.
For efficiency considerations, each thread can keep its own, private
copy of such a shared variable, possibly in a register of the CPU.
The real (or master) copy of the variable is updated at various times,
such as when a synchronized method is entered.
While this approach works fine, there may be times when it is
inappropriate.
PART –B
UNIT-1
2. a) Explain Java’s contribution to Internet.
Refer the Question paper nov/December 2014 Part B Unit –I 3a answer
b) Explain automatic type conversion with a suitable code example.
Refer the Question paper nov/December 2014 Part B Unit –I 2b answer
c) Explain labeled break statement with syntax and example.
Java does not have a goto statement because it provides a way to
branch in an arbitrary and unstructured manner.
The goto can be useful when you are exiting from a deeply nested
set of loops.
To handle such situations, Java defines an expanded form of the
break statement.
The general form of the labeled break statement is shown here:
break label;
Most often, label is the name of a label that identifies a block of
code
When this form of break executes, control is transferred out of the
named block. The labeled block must enclose the break statement,
The break statement can be used within while, do , for and switch
statements
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second;
// break out of second block
System.out.println("This won't execute");
78
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
} Running this program generates the following output:
Before the break.
This is after second block.
d) Explain for loop with syntax and example. (5+5+5+5)
The for loop is an entry controlled loop. The general form of the for
loop is
for (initialization; test condition; increment)
{
Body of the loop
}
The execution of the for statement is as follows:
1. Control variable is initialized using assignment statement such as i=1.
The variable i is known as loop control variable.
2. The value of the control variable is tested using test condition. If the
condition is true the body of the loop is executed , otherwise the loop
is terminated and the execution continues with the statement that
immediately follows the loop.
3. When the body of the loop is executed, the control is transferred
back to the for statement after evaluating the last statement in the for
loop. Now, the control variable is incremented and the new value of
the control variable is again tested to see whether it satisfies the loop
condition.
4. If the condition is satisfied, the body of the loop is again executed.
The process continues till the value of the control variable fails to
satisfy the test condition.
// Demonstrate the for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
79
}
}
3. a) Write a note on labeled loops in Java.
During the loop operations, it may be necessary to skip a part of the
body of the loop under certain conditions.
Java supports another statement called the continue statement,
which causes the loop to be continued with the next iteration after
skipping any statements in between.
The format of the continue statement is continue;
As with the break statement, continue may specify a label to
describe which enclosing loop to continue.
Here is an example program that uses continue to print a triangular
multiplication table for 0 through 9.
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) { The continue statement in
for(int j=0; j<10; j++) { this example terminates the
if(j > i) { loop counting j and
System.out.println(); continues with the next
continue outer; iteration of the loop
} counting i. output of this
program:
System.out.print(" " + (i * j));
0
} 01
} 024
System.out.println(); 0369
} 0 4 8 12 16
} 0 5 10 15 20 25
b) Explain the different forms of if statement with syntax and example.
The if statement is a powerful decision making statement and is
used to control the flow of execution of statements.
The if statement may be implemented in different forms depending
on the complexity of conditions to be tested.
1. Simple if statement
2. if … else statement
3. Nested if … else statement
4. else if ladder
Simple if statement: - The general form of the simple if statement is
80
if (test expression)
{ Statement-block;
}
Statement-x;
T he statement-block may be a single statement or a group of
statements. If the test expression is true, the Statement-block will be
executed. Otherwise the Statement-block will be skipped and the
execution will jump to the statement-x.
Example: class positive
{
public static void main (String args[])
{
int a=10;
if(a>0)
{
System.out.println(“number is positive”);
}
}
}
if … else statement:- The if….else statement is an extension of the
simple if statement. The general form is
if (test expression)
{ True –block Statement(s);
}
else
{ False –block Statement(s);
}
Statement-x;
If the test expression is true, then the true-block statement(s)
immediately following the if statement, are executed; otherwise, the
false-block statement(s) are executed.
In either case, the control is transferred subsequently to the
statement-x.
class positive
{
public static void main (String args[])
{
int a=10;
if(a>0)
{
System.out.println(“number is positive”);
81
}
else
{
System.out.println(“number is negative”);
}
}
}
Nested if else statement: When series of decisions are involved, we
may have to use more than one if … else statement in nested form as
follows: if (test condition1)
{ if (test condition 2)
{ Statement1;
}
else
{ Statement2;
}
}
else
{ Statement3;
} Statement-x;
if the condition1 is false, the statement-3 will be executed;otherwise
it continues to perform the second test. If the condition-2 is true, the
statement-1 will be evaluated; otherwise the statement-2 will be
evaluated and then the control is transferred to statement-x.
//Example
class biggest
{
public static void main (String args[])
{ int a=10,b=20,c=30;
if(a>b) {
if(a>c)
System.out.println(“a is biggest number”);
else
System.out.println(“c is biggest number”);
}
else
{
if(b>c)
System.out.println(“b is biggest number”);
else
System.out.println(“c is biggest number”);
}
82
}
}
else if ladder: The else if ladder is used when multipath decisions
are involved. A multipath decision is a chain of ifs in which the
statement associated with each else is an if.
It takes the following general form:
if (condition1) 1. This construct is known as else if
Statement1; ladder.
else if (condition2) 2. The conditions are evaluated from the
Statement2; top, downwards.
else if (condition3) 3. As soon as the true condition is found,
Statement3; the statement associated with it is
……………………………… executed and the control is transferred
else if (conditionN) to the statement-x.
Statement N; 4. When all conditions become false, the
else final else containing the default-
default-statement; statement will be executed.
statement-X;
//Example
class elseifladder
{
public static void main(String args[])
{
int rollNumber[]={111,222,333,444};
int marks[]={81,75,43,58};
for ( int i=0; i<rollNumber.length;i++)
{
if(marks[i]>79)
System.out.println(rollNumber[i]+”Honours”);
else if (marks[i]>59)
System.out.println(rollNumber[i]+”I Divison”);
else if (marks[i]>49)
System.out.println(rollNumber[i]+”II Divison”);
else
System.out.println(rollNumber[i]+”FAIL”);
}
}
} Output of the program is:
111 Honours 222 I Division 333 Fail 444 II Division
c) Explain the process of reading the string with a suitable code example.
Refer Question paper Nov/December 2014 Part B Unit-I 3 c answer
83
d) Write a Java code to print the odd numbers between 1 and N using
continue statement. (6+4+5+5)
// Demonstrate continue.
import java.lang.*;
import java.io.*;
class continue {
public static void main(String args[]) throws Exception{
int n;
DataInputStream b=new DataInputStream(System.in);
System.out.println("Enter N Value:");
n=Integer.parseInt(b.readLine());
for(int i=0; i<n; i++) {
if (i%2 == 0) continue;
System.out.print(i + " ");
System.out.println("");
}
}
} UNIT-II
4. a) What are command line arguments? Explain the use of command line
arguments with example.
Refer question paper nov/dec 2014 unit-II Part –B 4 b answer
b) Explain the use of constructors with a suitable example.
Refer question paper nov/dec 2014 unit-II Part –B 5 b answer
c) List and explain any five string methods.
Refer question paper nov/dec 2014 unit-II Part –B 5 a answer
d) Explain method overriding with a suitable example. (5+5+5+5)
Refer question paper nov/dec 2015 unit-II Part –B 4b answer
5. a) Explain different methods to initialize an array with suitable example.
Refer question paper nov/dec 2014 unit-II Part –B 4 a answer
b) Explain how to pass objects to methods with suitable example.
So far we have only been using simple types as parameters to
methods.
However, it is both correct and common to pass objects to methods.
For example, consider the following short program
// Objects may be passed to methods.
class Test {
int a, b;
84
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
} This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
the equals( )method inside Test compares two objects for
equality and returns the result.
That is, it compares the invoking object with the one that it is
passed.
If they contain the same values, then the method returns true.
Otherwise, it returns false.
Notice that the parameter o in equals( ) specifies Test as its type.
c) Explain the use of static methods with an example.
Static member is common to all the objects and defined without
using a particular object.
That is, the member belongs to the class as a whole rather than the
objects created from the class.
Static members are defined as follows:
static int count;
static int max(int x, int y);
The static members are associated with the class itself rather than
the individual objects.
Therefore static variables and static methods are often referred to as
class variables and class methods.
85
Static variables are used when we want to have a variable common to
all instances of a class.
For example, the variable that could keep a count of how many
objects of a class have been created.
Java creates only one copy of a static variable which can be used
even if the class is never actually instantiated.
Example:
class Mathoperation Static methods are called
{ using class names. Static
static float mul(float x, float y) methods have several
{
restrictions:
return(x*y);
} 1. They can only call other
static float divide(float x, float y) static methods.
{ 2. They can only access
return(x/y); static data.
} 3. They cannot refer to this
}
or super in any way.
class MathApplication
{
public void static main(String args[])
{
float a = Mathoperation.mul(4.0,5.0);
float b = Mathoperation.divide(a,2.0);
System.out.println(“b = “+b);
}
}
d) Write a Java code to find the sum of numbers from 1 to n by using
for...each style of loop. (5+5+5+5)
// Use a for-each style for loop. Output:
class ForEach { Value is: 1
public static void main(String args[]) { Value is: 2
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Value is: 3
int sum = 0; Value is: 4
Value is: 5
// use for-each style for to display and sum the values
Value is: 6
for(int x : nums) { Value is: 7
System.out.println("Value is: " + x); Value is: 8
sum += x; Value is: 9
} Value is: 10
System.out.println("Summation: " + sum); Summation: 55
86
}
} UNIT-III
6. a) Explain the creation and usage of package. (5+5+5+5)
refer Question paper nov/dec 2014 Part B Unit-III 6 a answer
b) Explain the different states of a thread.
A thread can be in one of several states.
It can be running.
It can be ready to run as soon as it gets CPU time.
A running thread can be suspended, which is a temporary halt to its
execution.
It can later be resumed.
A thread can be blocked when waiting for a resource.
A thread can be terminated, in which case its execution ends and
cannot be resumed.
Along with thread-based multitasking comes the need for a special
type of feature called synchronization, which allows the execution of
threads to be coordinated in certain well-defined ways.
s leep() – Blocked for a specified time
Suspend() – Blocked until further orders
Wait() – Blocked until certain condition occurs
yield
wait
87
d) Illustrate the use of multiple catch statements with proper examples.
refer Qeustion paper nov/dec 2015 part B Unit-III 7 b answer
7. a) List and explain different API packages available in Java.
refer Qeustion paper nov/dec 2015 part A 1g answer
b) List and explain any five thread methods.
run() Method :- The run() method has been inherited by the class
MyThread. We have to override this method in order to implement the
code to be executed by our thread. The basic implementation of run() is
as follows:
public void run()A
{
………….
…………. //thread code here
………….
}
When we start the new thread, Java calls the thread’s run() method. In
thread all the action takes place in thread.
Start() Method:- The following statements actually creates and run an
instance of thread class.
MyThread AThread = new MyThread();
AThread.start(); //invokes run() method
The first line instantiates a new object of class MyThread, The thread is in
a newborn state.
The second line calls the start() method causing the thread to move into
runnable state.
A program used suspend( ), resume( ), and stop( ), which are methods
defined by Thread, to pause, restart, and stop the execution of a thread.
Suspend () method: The suspend( ) method of the Thread
class can sometimes cause serious problems that involve deadlock.
Syntax: final void suspend( )
resume () method : The resume( ) method is also deprecated. It does not
cause problems but cannot be used without the suspend( ) method as its
counterpart.
Syntax: final void resume( )
stop () method:-The stop( ) method of the Thread class can sometimes
cause serious problems.
Syntax: final void stop( )
c) Explain how to create user defined exceptions in Java with example.
refer Qeustion paper nov/dec 2014 part B Unit-III 7 b answer
d) Illustrate the use of finally with suitable example. (5+5+5+5)
refer Qeustion paper nov/dec 2014 part B Unit-III 6 c answer
88
UNIT-IV
8. a) How does an Applet differ from standalone program ?
Although both the Applets and stand-alone applications are Java
programs, there are certain restrictions are imposed on Applets due to
security concerns:
a. Applets don’t use the main() method, but when they are load,
automatically call certain methods (init, start, paint, stop, destroy).
b. They are embedded inside a web page and executed in browsers.
c. They cannot read from or write to the files on local computer.
d. They cannot communicate with other servers on the network.
e. They cannot run any programs from the local computer.
f. They are restricted from using libraries from other languages.
The above restrictions ensure that an Applet cannot do any damage to the
local system.
b) Explain any six event classes in java.awt.event.
Event Class Descripiton
ActionEvent Generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved,
resized, or becomes visible.
ContainerEvent Generated when a component is added to or
removed from a container
FocusEvent Generated when a component gains or loses
keyboard focus.
InputEvent Abstract superclass for all component input event
classes
ItemEvent Generated when a check box or list item is clicked;
also occurs when a choice selection is made or a
checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the
keyboard.
MouseEvent Generated when the mouse is dragged, moved,
clicked, pressed, or released; also generated when
the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved
TextEvent Generated when the value of a text area or text field
is changed.
WindowEvent Generated when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Main Event Classes in java.awt.event
89
c) Explain the use of Jlist and any four methods associated with it.
JList
In Swing, the basic list class is called JList. It supports the
selection of one or more items from a list.
Although the list often consists of strings, it is possible to create a
list of just about any object that can be displayed.
JList provides several constructors. The one used here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified
by items.
JList is based on two models.
The first is ListModel:This interface defines how access to the list
data is achieved.
The second model is the ListSelectionModel interface, which
defines methods that determine what list item or items are selected.
Although a JList will work properly by itself, most of the time you
will wrap a Jlist inside a JScrollPane. This way, long lists will
automatically be scrollable, which simplifies GUI design.
A JList generates a ListSelectionEvent when the user makes or
changes a selection.
This event is also generated when the user deselects an item. It is
handled by implementing ListSelectionListener.
This listener specifies only one method, called valueChanged( ),
which is shown here: void valueChanged(ListSelectionEvent le)
Here, le is a reference to the object that generated the event
By default, a JList allows the user to select multiple ranges of items
within the list, but you can change this behavior by calling
setSelectionMode( ), which is defined by JList.
It is shown here: void setSelectionMode(int mode)
You can obtain the index of the first item selected, which will also be
the index of the only selected item when using single-selection
mode, by calling getSelectedIndex( ), shown here:
int getSelectedIndex( )
Indexing begins at zero. So, if the first item is selected, this method
will return 0. If no item is selected, –1 is returned.
Instead of obtaining the index of a selection, you can obtain the
value associated with the selection by calling getSelectedValue( ):
Object getSelectedValue( )
It returns a reference to the first selected value. If no value has been
selected, it returns null.
90
d) Write a note on menu creation. (4+6+5+5)
Refer Question paper nov/December 2014 part B Unit- IV 9 b answer
9. a) Explain how to pass parameters to an Applet with an example.
Refer Question paper nov/December 2014 part B Unit- IV 8a answer
b) List and explain any six EventListner interfaces.
Refer Question paper nov/December 2015 part B Unit- IV 9 b answer
c) Explain the purpose of Headless exception.
The HeadlessException
Most of the AWT controls have constructors that can throw a
HeadlessException when an attempt is made to instantiate a GUI
component in a non-interactive environment (such as one in which no
display, mouse, or keyboard is present). This exception is not handled
by the programs because an interactive environment is required to
demonstrate the AWT controls
Syntax: Label( ) throws HeadlessException
Button(String str) throws HeadlessException
Checkbox(String str) throws HeadlessException
List(int numRows) throws HeadlessException
Scrollbar(int style) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
d) Explain different methods associated with checkboxes. (5+6+4+5)
To retrieve the current state of a check box, call getState( ).
To set its state, call setState( ).
You can obtain the current label associated with a check box by calling
getLabel( ). To set the label, call setLabel( ).
These methods are as follows:
1. boolean getState( ) 2. void setState(boolean on)
3. String getLabel( ) 4. void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared.
The string passed in str becomes the new label associated with the
invoking check box.
Each time a check box is selected or deselected, an item event is
generated. This is sent to any listeners that previously registered an
interest in receiving item event notifications from that component.
Each listener implements the ItemListener interface.
That interface defines the itemStateChanged( ) method.
An ItemEvent object is supplied as the argument to this method.
91