Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

Credit Based Third Semester B.C.A Degree Examination, Nov./Dec.

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.

3. a) Write a note on Java contribution to the internet.


b) List and explain different primitive data types available in
Java.
c) With syntax and example explain the process of reading a string
from the keyboard.
d) Explain while loop and do while loop with syntax and example.
Unit-II
4. a) Explain how to declare, initiate, initialize and use a one
dimensional array with example.
b) With an example explain command line arguments.
c) With an example explain method overloading.
d) Write a note on: 6+6+6+4
i) Abstract class and Abstract method
ii) Final class and Final method.

5. a) Explain any 4 String methods with suitable example.


b) With an example explain the different types of constructors
supported by Java.
c) Explain how to pass variable-length arguments with suitable example.
d) With an example explain single level inheritance.
Unit-III
6. a) With an example explain how to create and importing the
user defined package. 5+5+5+5
b) With an example explain implementing an interface.
c) Illustrate the use of finally with suitable example.
d) Define synchronization. With an example explain how
synchronization is achieved in multithread environment using
synchronized methods.

7. a) Explain the Java’s access control mechanism using access


modifier keyword.
b) With an example explain how a user defined exception is defined
and used for handling errors.
c) With an example explain how a thread created by implementing
runnable interface.
d) Write a note on Thread Priority.
Unit-IV
8. a) With an example explain passing parameters to an applet.
b) What is the purpose of TextField class? Explain any three
methods of text field class with syntax and example.
c) What is the purpose of layout managers? With an example
explain the use of GridLayout. 5+5+5+5
d) With an example explain how to create a swing applet.

9. a) What is the purpose of MouseListener interface? With syntax


and example explain any five methods of MouseListener interface.
b) Name the controls required for creating a menu. With an example
explain creation of menu.
c) With syntax and example explain the purpose of showStatus()
method.
d) With an example explain the use of anonymous inner classes to handle
events.
Credit Based Third Semester B.C.A Degree Examination, Nov./Dec. 2015
(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 polymorphism?
b) List different integer data types available in Java.
c) Write a for loop to display even numbers between 1 and 100.
d) What are classes and objects?
e) What is the use of finalize () method in java?
f) Write the syntax for defining a one dimensional array in java.
g) List any four API packages of Java
h) How to assign priority to thread? What is the default priority?
i) Differentiate the keywords throw and throws.
j) Write the syntax of applet tag.
k) What is the purpose of repaint () method?
l) What is a listener?
PART-B
Unit-I
2. a) Explain the while and do...while statement with syntax and an example.
b) Explain the process of reading string from the keyboard with suitable
example.
c) Write a note on Java streams. (8+6+6)
3. a) List and explain arithmetic and logical operators in Java.
b) List and explain different primitive data types available in Java.
c) Explain any three forms of for loop with suitable example. (6+6+8)
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)
b) Explain method overriding with suitable example.
c) Explain how to return an object from a method with suitable example.

5. a) What is method over loading? Explain with a suitable example.


b) Explain the use of command-line arguments in Java with suitable
example.
c) Explain single inheritance with suitable example. (8+6+6)
Unit-III
6. a) Explain how to create and implement interface using suitable example.
b) List and explain any 6 built-in exceptions of Java. (8+6+6)
c) Explain how to create user defined exceptions in Java with example.
7. a) Explain the process of creating a thread by using thread class with
suitable example. (8+6+6)
b) Illustrate the use of multiple catch statements with suitable example.
c) Explain exception handling in Java with suitable example.
Unit-IV
8. a) Explain how to create an Applet in java with suitable example.
b) List and explain the components of Delegation Event Model.
c) Explain the advantages of Swing. (8+6+6)
9. a) Explain how to pass parameter to an applet with a suitable example.
b) List and explain different Event Listener Interfaces. (8+6+6)
c) Mention the purpose of different layout managers available in Swing.
**********
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?
b) List any four primitive data types available in Java.
c) What is stream? List different types of streams defined by Java.
d) What do you mean by type conversion in Java? Give an example.
e) What is the purpose of final variable?
f) What is the purpose of super() keyword in Java?
g) Define package. Give one advantage of package.
h) List any four built-in exceptions in Java.
i) What is multithreading?
j) List the key items of a swing GUI.
K) Write the limitations of AWT components.
l) What is the purpose of Volatile modifier?
PART –B
UNIT-1
2. a) Explain Java’s contribution to Internet.
b) Explain automatic type conversion with a suitable code example.
c) Explain labelled break statement with syntax and example.
d) Explain for loop with syntax and example. (5+5+5+5)
3. a) Write a note on labeled loops in Java.
b) Explain the different forms of if statement with syntax and example.
c) Explain the process of reading the string with a suitable code example.
d) Write a Java code to print the odd numbers between 1 and N using
continue statement. (6+4+5+5)
UNIT-II
4. a) What are command line arguments? Explain the use of command line
arguments with example.
b) Explain the use of constructors with a suitable example.
c) List and explain any five string methods.
d) Explain method overriding with a suitable example. (5+5+5+5)
5. a) Explain different methods to initialize an array with suitable example.
b) Explain how to pass objects to methods with suitable example.
c) Explain the use of static methods with an example.
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)
UNIT-III
6. a) Explain the creation and usage of package. (5+5+5+5)
b) Explain the different states of a thread.
c) Explain the general syntax for defining and implementing an interface.
Give code example.
d) Illustrate the use of multiple catch statements with proper examples.
7. a) List and explain different API packages available in Java.
b) List and explain any five thread methods.
c) Explain how to create user defined exceptions in Java with example.
d) Illustrate the use of finally with suitable example. (5+5+5+5)
UNIT-IV
8. a) How does an Applet differ from standalone program?
b) Explain any six event classes in java.awt.event.
c) Explain the use of Jlist and any four methods associated with it.
d) Write a note on menu creation. (4+6+5+5)
9. a) Explain how to pass parameters to an Applet with an example.
b) List and explain any six EventListner interfaces.
c) Explain the purpose of Headless exception.
d) Explain different methods associated with checkboxes. (5+6+4+5)
BCA 504 - Java Programming QUESTION BANK
Unit I
Questions carrying 2 marks
1. What is Java Bytecode?
2. What is an Applet?
3. List any four features of Java
4. What is data Encapsulation?
5. What is polymorphism?
6. Write the meaning of public static void main (String args [])
7. Mention two ways of writing comments in Java
8. How to create single-line and multi-line comments in Java?
9. List any 4 primitive data types available in Java.
10. What is the difference between 10.3 and 10.3f?
11. List different integer data types available in Java
12. What are the two ways of initializing variables?
13. What is dynamic initialization of variables? Give example.
14. What are block-level variables? Give example.
15. List different arithmetic operators available in Java
16. List different relational operators available in Java
17. What is the purpose of break statement? Give example.
18. Differentiate break and continue.
19. What is type conversion? What are its types?
20. What is automatic (implicit) type conversion? Give example
21. When does automatic type conversion take place?
22. Write the meaning of System.out.println ()
23. How platform independence is achieved in Java?
24. How to create a block of code? Give example.
25. Write a single print statement to produce the following output
ONE
TWO
THREE
26. In an expression, what types are byte and short promoted to?
27. Write the for statement for a loop that counts from 1000 to 0 by -2
28. Write a for loop to display even numbers between 1 and 100
29. What is stream? List different types of streams in Java.
30. Differentiate byte and character streams.
31. List the predefined streams of system object
32. Write the syntax of simple if statement
Questions carrying 3 or more marks
1. List and explain different features of Java
2. Explain Java’s contribution to Internet
3. What are identifiers? Write the rules to be followed when creating an
identifier.
4. List and explain different primitive data types available in Java.
5. Explain automatic type conversion with suitable code example.
6. Explain explicit type conversion with example.
7. What are streams? List and explain different byte and character streams
available in Java.
8. Write a note on Java Streams.
9. Explain the process of reading a character from the keyboard with suitable
example.
10. Explain the process of reading a string with suitable example.
11. Explain different forms of if statement with syntax and example
12. Explain switch statement with syntax and example
13. Explain for loop with syntax and example.
14. What is infinite loop? Explain how to construct an infinite loop in Java
15. Explain any three forms of for loop with suitable example.
16. Explain while loop with syntax and example
17. Explain do while loop with syntax and example.
18. Explain break statement with suitable example.
19. Explain continue statement with suitable example
20. Explain labeled break statement with syntax and example.
Unit II
Questions carrying 2 marks
1. What are arrays?
2. How to create and instantiate a one dimensional array reference variable?
Give example
3. How to initialize an array at the time of creation? Give example.
4. What is the use of length member of arrays?
5. What are different ways of constructing String? Give example.
6. List any four methods associated with Strings.
7. What are command-line arguments?
8. What are classes and objects?
9. What is the purpose of new operator?
10. Write the syntax to create a class in Java.
11. Write a statement that creates and instantiates an object in Java.
12. What are constructors?
13. What is the purpose of a constructor?
14. What is garbage collection?
15. What is the use of finalize () method in Java?
16. What is the use of this keyword in java?
17. List different access modifiers available in Java.
18. Differentiate public and private access modifiers.
19. What is method overloading?
20. What is recursion?
21. Mention one advantage and one drawback of recursion.
22. What is the purpose of static keyword?
23. What is the specialty of static variable? (How to access static variable in
Java)
24. List any two restrictions of static methods.
25. What is the specialty of static method? (How to access a static method in
Java)
26. What is inheritance?
27. What is the purpose of keyword extends?
28. What is the purpose of super ()?
29. What is method overriding?
30. What are abstract classes?
31. What are abstract methods?
32. How to prevent methods from overriding?
33. What are final variables?
34. What is the purpose of final class?
35. What are final methods?
Questions carrying 3 or more marks
1. What are arrays? Explain how to declare instantiate initialize and use a
one-dimensional array with suitable code example.
2. Explain how to assign array references with suitable example.
3. Explain different methods to initialize an array with suitable example.
4. Explain the use of length member with suitable code example.
5. Explain the use of for each style of loop with suitable code example.
6. Explain any four string methods with suitable example.
7. Explain the use of command-line arguments in Java with suitable example.
8. Write the general form of a class? Explain how to define a class in Java
with suitable example.
9. Explain how to create an object in Java with suitable example.
10. Explain the use of Constructors with suitable example.
11. Explain how garbage collection is achieved in Java.
12. Explain the use of finalize () method in Java with suitable example.
13. Explain the use of access modifiers with suitable example.
14. Explain how to pass objects to methods with suitable example.
15. Explain how to return an object from a method with suitable example
16. Explain method overloading with suitable example.
17. Explain constructor overloading with suitable example.
18. Create a class Student with members Register number, name and marks
in three subjects. Use constructors to initialize objects and write a method
that displays the information of a student.
19. Explain recursion with suitable example
20. Explain the use of static variables with suitable example.
21. Explain the use of static methods with suitable example.
22. Explain the use of static blocks with suitable example.
23. Explain nesting of classes with suitable example.
24. Explain how to pass variable-length arguments with suitable example.
25. Explain how a superclass reference can refer to a subclass object with
suitable example.
26. Explain single inheritance with suitable example.
27. Explain method overriding with suitable example.
28. Explain multi-level inheritance with suitable example.
29. Explain the purpose abstract and final classes.
Unit III
Questions carrying 2 marks
1. What is a package?
2. How to define a package?
3. What is namespace?
4. How to import a package?
5. How to import a specific class of a package?
6. List any four API packages of Java.
7. What is an interface?
8. What is a thread?
9. What are different methods of creating threads?
10. What is multithreading?
11. List different states of a thread. 12. What is synchronization?
13. List any four thread methods.
14. What is the purpose of join () method in case of threads?
15. What is the purpose of isAlive () method in case of threads?
16. How to assign priority to thread?
17. What is the purpose of notify () method?
18. What is the purpose of notifyall () method?
19. When does a thread move to blocked state?
20. Differentiate suspend () and stop () methods of a thread.
21. What is the purpose of resume () method?
22. What is the purpose of wait () and notify () methods?
23. What is an exception?
24. What is the purpose of exception handler?
25. Differentiate the keywords throw and throws.
26. List the subclasses of Throwable class and mention their purpose.
27. List any four types of exceptions in Java.
28. What is the purpose of try and catch block?
29. What is meant by rethrowing and exception?
30. List any 2 methods defined by Throwable class along with their purpose.
Questions carrying 3 or more marks
1. Explain how to create and use a package in Java with suitable example.
2. List and explain different API packages available in Java.
3. Explain how to create and implement interface using suitable example.
4. Explain the process of creating a thread by implementing Runnable
interface with suitable example.
5. List and explain any five thread methods
6. List and explain different states of a thread
7. Explain the purpose of synchronization.
8. Explain exception handling in Java with suitable example.
9. Illustrate the use of multiple catch statements with suitable example.
10. List and explain different methods of Throwable class.
11. Illustrate the use of finally with suitable example.
12. List and explain any 5 built-in exceptions of Java
13. Explain how to create user defined exceptions in Java with example.
Unit IV
Questions carrying 2 marks
1. What is an Applet?
2. List two types of Applets available in Java.
3. What is the purpose of appletviewer?
4. Write HTML file to run an applet program named Simple.
5. List any two features of Applets.
6. What is the purpose of paint () method?
7. List any four methods associated with Applets
8. What is the purpose of repaint () method?
9. Differentiate stop () and destroy () methods.
10. What is the purpose of update () method.
11. Write the purpose of showStatus () method.
12. List the super classes of Applet defined by AWT
13. List any 4 methods defined by Applet
14. What is an event? Give example.
15. What is a listener?
16. What is the purpose of Event Listener?
17. List any 4 Event classes in java.awt.event
18. List any 4 commonly used Event Listener Interfaces
19. What is the purpose of MouseListener Interface?
20. List any four methods of MouseListener Interface.
21. What is the purpose of transient modifier?
22. What is the purpose of volatile modifier?
23. What is the purpose of assert keyword?
24. What is the purpose of strictfp?
25. What is the purpose of native keyword?
26. What are native methods?
27. What are the limitations of AWT components?
28. List the key items of a swing GUI
29. List any four layout managers supported by swing
30. What happens when the constructor JButton (String msg) is called?
31. What is the purpose of add () and remove () methods of Container class?
32. What are Headless Exceptions?
33. List any four types of adjustment events in case of scroll bars
34. What is the purpose of setText () and getText () methods?
35. What is the purpose of TextArea control?
36. What is the purpose of Layout Manager Interface?
37. What is FlowLayout?
Questions carrying 3 or more marks
1. How does Applet differ from stand-alone program?
2. Write the complete Applet skeleton
3. Explain how to pass parameters to an Applet with suitable example
4. List and explain any 6 methods defined by Applet
5. List and explain the components of Delegation Event Model
6. List and explain any 6 event classes in java.awt.event
7. List and explain different Event Listener Interfaces
8. Explain the advantages of Swing
9. Explain how any two Mouse events are handled in Applets with suitable
example
10. Mention the purpose of different layout managers available in Swing
11. Explain the purpose of JFrame and explain any four methods associated
with it.
12. Explain the purpose of JButton and explain any four methods
associated with it.
13. Explain the use of JTextField and any four methods associate with it
14. Explain the use of JList and any for methods associated with it.
15. Explain the purpose of Headless Exception.
16. Explain the process of adding and removing components to a Container
17. Illustrate the use of Label with suitable example.
18. List and explain various methods associated with Button
19. List and explain different methods associated with check boxes
20. Write a note on menu creation
21. Explain different methods associate with TextField control with suitable
example. V semester BCA
BCA508 DC & Java Lab
PART A -20 marks (Program -16 marks execution- 4 marks)
1. Write a program to retrieve data from personal telephone directory
in the form of a database table. When the user hits a character the
names which start with the character and the telephone number
must appear. (For example if names are Anil, Arjun, Ashwin ,Ram,
Raj, Deeepak etc, When ‘A’ is hit, Anil , Arjun, Ashwin must be
displayed with respective no.s., When A is continued with ‘r’, only
Arjun’ detail to be shown from the above list)
2. Write a program to create a Student database with fields Stud_no,
Stud_name, Class, Mark1.mark2. Perform these operations
a)Input the student information from the keyboard. b) Display
Specific student information. c)Delete Specific student information.
3. Write a Java class called Tempconverter with methods for
calculating conversion operations. Have this class as a servant and
create a server program and register in the rmiregistry. Write a client
program to invoke these remote methods of the servant and do the
calculations. Accept inputs interactively.
4. Write a Java class called Tax with methods for calculating Income
Tax. Have this class as a servant and create a server program and
register in the rmiregistry. Write a client program to invoke these
remote methods of the servant and do the calculations. Accept
inputs interactively.
5. Write a Java class called SimpleInterest with methods for calculating
Simple Interest. Have this class as a servant and create a server
program and register in the rmiregistry. Write a client program to
invoke these remote methods of the servant and do the calculations.
Accept inputs at command prompt
PART B - 25 marks (Program -20 marks execution- 5 marks)
1. Write menu driven program to accept a Number &
a) Reverse and sum of individual digits
b) To generate N Fibonacci Numbers.
2. Design a class to represent a bank account include the following
members (Using constructors). Use menu driven program.
a) To deposit an amount
b) To withdraw an amount after checking minimum balance of
1000/=
c) To display the name and balance
(Data members: Name of the Depositor, Account number, Balance
amount in the account. Methods: To assign initial values (constructors))
3. Develop a program to produce pay slip of an employee name, code
and designation. And another base class consisting of the data
members, such as account number, date of joining and basic pay. The
derived class consists of data member of other earning (PF, LIC,
TAX). (Implement using interface).
4. Program to demonstrate multithreading using runnable interface.
Define three different threads, one to calculate square of first n
integers, another to calculate cube of first n integers and third thread to
find the square root of the first n integers. Apply various thread
priority.
5. Create a package to convert temperature in centigrade into Fahrenheit,
and one more package to calculate the simple Interest. Implement
both package in the Main () by accepting the required inputs for each
application.
PART C- 35 Marks
(Program -28 marks execution- 7 marks)
(USE proper layouts to place items neatly)
1. Create an applet to implement simple calculator. The integer data are
to be entered through the text box and the operation that is to be
performed (operator) (+, -, *, /) to be given through command buttons.
When the user press the compute button result should be displayed.
 Do the validation for empty textbox for numbers.
 Handle “Division by zero”
2. Write an applet program to accept the employee name, employee
number and basic salary as parameters. Find the gross and net salaries
on the following conditions.
if Salary <= 20000 if Salary > 20000
D.A is 40% Salary D.A is 50% of salary
H.R.A is 10% Salary. H.R.A 15% of salary
P.F 12% of Gross P.F 12% of Gross
PT is Rs .100 PT is Rs.150
Gross = basic salary +D.A +HRA
Net = Gross -PT –PF
3. Using the swing components, design the frame for shopping a book
that accepts book code, book name, and Price. Calculate the discount
on code as follows.
Code Discount rate
101 15%
102 20%
103 25%
Any other 5%
Find the discount amount and Net bill amount. Display the bill.
4. Using the swing components, design the form for an electricity office
for accepting meter no. customer name, previous reading, and current
reading. Use Data validation to see that current reading is more than
previous reading. Produce the bill in neat format.
Bill is calculated as follows.
Compute total no of units consumed and total amount to be paid by
each consumer the condition is
If unit consumed is <=150 charge is 200.
For the next 50 units Rs 1.50 per unit
For the next 100 units charge = Rs2.00/ unit
For the next additional units charge is Rs 3.00 per unit or Rs
500 whichever is maximum.
Scheme of valuation:
Part A -20 marks (Program -16 marks execution- 4 marks)
Part B - 25 marks (Program -20 marks execution- 5 marks)
Part C- 35 marks (Program -28 marks execution- 7 marks)
Viva-10 marks Record- 10 marks Total-80 marks
Credit Based Third Semester B.C.A Degree Examination, Nov./Dec. 2014
(New Syllabus) (2013-14 Batch Onwards)
JAVA PROGRAMMING
Time: 3 Hours Max.Marks:100
Note: Answer any ten questions from Part-A andanyone full question from
each Unit in Part-B.
PART-A (10x2=20)
1. a) Define Byte code. Write the benefits of bytecode.
 The Java Programming language is both compiled and
interpreted. After writing a program you have to first compile
it.After compilation, the program is converted into a format
called bytecodes.
 These bytecodes can be executed on any computer. So byte
codes are said to be platform independent.Thebytecodes are
then interpreted by the Java interpreter.
 The Java interpreter is called the Java Virtual Machine (JVM)
or the Java Runtime Engine. The JVM converts the bytecodes
into the machine code that can be understood by the specific
computer on which it is run.
 A Java program can thus run on any kind of computer that has
a JVM. The Phrase ‘Write once, run anywhere’ is commonly
used to describe the nature of a Java Program.

Process of Compilation

Process of Convertingbytecode into machine code

b) Define scope and life time of a variable


 Variables declared and used inside methods are called local
variables.
 They are called so because they are not available for use outside
the method definition.
 Local variables can also be declared inside program blocks that
are defined between an opening brace { and a closing brace }.

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.

 We can have program blocks within other program blocks (called


nesting) as shown above.
 Each block can contain its own set of local variable declarations.
 We cannot declare a variable to have the same name as one in an
outer block.
 The variable x declared in Block1 is available in all the three
blocks. However, the variable n declared in Block2 is available
only in Block2, because it goes out of the scope at the end of
Block2. Similarly, m is accessible only in Block3.
 We cannot declare the variable x again in Block2 or Block3.

c)Define stream. Name the two types of stream defined in Java.


 Java programs perform I/O through streams.
 A stream is an abstraction that either produces or consumes
information.
 A stream is linked to a physical device by the Java I/O system.
 All streams behave in the same manner, even if the actual
physical devices they are linked to differ.
2
 Thus, the same I/O classes and methods can be applied to any
type of device.
 For example, the same methods that you use to write to the
console can also be used to write to a disk file.
 Java implements streams within class hierarchies defined in the
java.io package.
 Java defines two types of streams: byte and character.
Byte Streams
Byte streams provide a convenient means for handling input and
output of bytes.
Byte streams are used, for example, when reading or writing
binary data.
Character Streams
Character streams provide a convenient means for handling input
and output of characters.
They use Unicode and, therefore, can be internationalized.
Also, in some cases, character streams are more efficient than
byte streams

d)Define array. Write the purpose of length member.


 An array is a group of like-typed variables that are referred to by a
common name.
 Arrays of any type can be created and may have one or more
dimensions.
 A specific element in an array is accessed by its index.
 Arrays offer a convenient means of grouping related information.
Purpose of Length Member
 In Java, all arrays store the allocated size in a variable named
length. We can access the length of the array a using a.length.
Example:
intasize = a.length;
This information will be useful in the manipulation of a arrays
when their sizes are not known.
class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
3
}
}
This pr ogr am d isplays t he follow in g out put :
length of a1 is 10
length of a2 is 8
length of a3 is 4

e) What are constructors?


Constructor is a special type of method. It will initialize the object
when it is created. Constructors have the same name as the class
itself. Secondly they do not specify a return type, not even void.
This is because they return the instance of the class itself.
Example:
class Rectangle
{
int length, width;
Rectangle(int x, int y)
{
length = x;
width = y;
}
intreatArea()
{
int area = length * width;
return(area);
}
}
classRectArea //class with main method
{
public static void main(String args[])
{
Rectangle rect1 = new Reactangle(15,10);//calling constructor
int area1=rect1.rectArea();
System.out.println(“Area1 = “+area1);
}
}
output Area1=150

f) What is the use of ‘this’ keyword in Java?


 The this keyword is used inside an instance method to refer to
the current object.
4
 Class methods cannot use this keyword.
 Two local variables cannot have the same name inside the same
scope.
 However, you can have local variables to methods that have the
same name as the instance variable of the class.
 When a local variable has the same name as an instance variable,
the local variable hides the instance variable.
For example:
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}The output from this program is shown here:
Volume is 3000.0
Volume is 162.0

g) Define interface. Why it is used?


o An interface is basically a kind of class.
5
o Like classes, interfaces contain methods and variables but with a
major difference.
o The difference is that interfaces define only abstract methods and
final fields.
o This means that interfaces do not specify any code to implements
these methods and data fields contain only constants.
o The Syntax for defining an interface is very similar to that for
defining a class.
The general form of an interface definition is
access interface name{
re-type method-name1(param-list);
re- type method-name2(param-list);
type val1=value;
type var2=value;
//……
re-type method-nameN(param-list);
type varN=value;
}

h) Define Package. Name any two advantages of using the package.


Packages are Java’s way of grouping a variety of classes and or interfaces
together. The grouping is usually done according to functionality. In
fact, packages act as, contain for classes.
By organizing our classes into packages we achieve the following
benefits:
1. The classes contained in the packages of other programs can be
easily reused.
2. In packages, classes can be unique compared with classes in other
packages. That is, two classes in two different packages can have the
same name. They may be referred by their fully qualified name
comprising the package name and the class name.
3. Packages provide a way to hide classes thus preventing other
programs or packages from accessing classes that are meant for internal
use only.
4. Packages also provide a way for separating design from coding. First
we can design classes and decide their relationships and then we can
implement the Java code needed for the methods. It is possible to
change the implementation of any method without affecting the rest of
the design

i) What is an exception? What are the advantages of exception handler?

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.

j)Write two ways of identifying whether the thread has ended.


o It is often useful to know when a thread has ended.
o Fortunately, Thread provides two means by which you can
determine if a thread has ended.
o First, you can call isAlive( ) on the thread.
Its general form is shown here: final booleanisAlive( )
The isAlive( ) method returns true if the thread upon which it is
called is still running. It returns false otherwise.
o While isAlive( ) is occasionally useful, the method that you will
more commonly use to wait for a thread to finish is called join( ),
shown here: final void join( ) throws InterruptedException
o This method waits until the thread on which it is called terminates.
Its name comes from the concept of the calling thread waiting until
the specified thread joins it.

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>*/

public class HelloWorldApplet extends Applet {


public void paint(Graphics g) {
g.drawString ("Hello World of Java!",25, 25);
}
}
1. This applet begins with two import statements.
2. The first imports the Abstract Window Toolkit classes.
3. Applets interact with the user (either directly or indirectly) through
the AWT, not through the console-based I/O classes.
4. The AWT contains support for a window-based, graphical user
interface.
5. The next import statement imports the applet package contains the
class Applet.
6. Every applet that you create must be a subclass (either directly or
indirectly) of Applet.
7. The next line in the program declares the class HelloWorldApplet.
8. This class must be declared as public because it will be accessed by
outside code.
9. Inside HelloWorldApplet, paint( ) is declared.
10. This method is defined by the AWT Component class (which is a
superclass of Applet) and is overridden by the applet.
11. paint( ) is called each time the applet must redisplay its output.
12. paint( ) is also called when the applet begins execution.
13. The paint( ) method has one parameter of type Graphics.
14. This parameter will contain the graphics context, which describes
the graphics environment in which the applet is running.
15. This context is used whenever output to the applet is required.
16. 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)

l)Write the limitations of AWT components with respect to Swing.


8
Swing AWT
Swing component does not need AWT component can be impleme
any native code to implement. nting with code.
Swing lets you specify which look AWT components always have thel
and feel your programs GUI uses ook and feel of the native platform.

Swing components don’t have to AWT components are always recta


be rectangular. ngular.
For ex. Buttons can be rounded.
PART-B
Unit – I
2. a) Write a note on java buzzwords.
Java Buzzwords(Features): Java language has the following attributes
■ Simple ■ Secure ■ Portable ■ Object-oriented■ Robust
■ Multithreaded■ Architecture-neutral■ Interpreted
■ High performance ■ Distributed ■ Dynamic
Let us know them briefly
■Simple: The aim of the developing java was to make it easy to learn
and use. Java does not have any of the difficult features of C++. The
syntax of java is very similar to that of c++. This made is easier for
programming to learn and understand.
■Secure: you can write java applications that cannot be attacked by
any harmful code. In the case of computer networks, Java
applications are safe from any harmful code that tries to create
viruses and attack the file system.
■Portable: people with different machines and operating systems can
use the same Java code without making any changes. For example,
you can take the same Java program that you executed on a windows
system and execute it on a non-Windows system such as Solaris or
linux without making any changes to the program
■Object-oriented: Java is a true object oriented language. Almost
everything in Java is an object. All program code and data reside
within objects and classes. Java comes with an extensive set of
classes, arranged in packages that we can use in our programs by
inheritance.
■Robust: Java is a robust language. It provides many safeguards to
ensure reliable code. It has strict compile time and run time
checking for data types. It is designed as garbage-collected language
relieving the programmers virtually all memory management
problems. Java also incorporates the concept of exception handling
9
which captures series errors and eliminates any risk of crashing the
system.
■Multithreaded: Multithreaded means handling multiple tasks
simultaneously. Java supports multithreaded programs. This means
that we need not wait for the application to finish one task before
beginning another. For example, we can listen to audio clip while
scrolling a page and at the same time download an applet from a
distant computer. This feature greatly improves the interactive
performance of graphical applications.
Architecture-neutral: Java programs can be easily moved from one
computer system to another, anywhere and anytime. Changes and
upgrades in operating systems, processors and system resources will
not force any changes in Java programs. Because of this Java has
become a popular language for programming on Internet which
interconnects different kinds of systems worldwide.
■Interpreted: Usually a computer language is either compiled or
interpreted. Java combines both these approaches thus making Java
a two-stage system. First, Java compiler translates source code into
byte code instructions. Byte codes are not machine instructions. In
the second stage, Java interpreter generates machine code that can
be directly executed by the machine that is running the Java
program. Thus Java is both compiled and an interpreted language.
■High performance: Java is slower than C++. Certain application
requires high speeds. In such cases, to increase the speed, you can
use Just-In-Time compilers (JIT compilers) that will improve the
performance of the Java Program. Memory management in Java is
done automatically by means of features such as automatic garbage
collection. Objects that no longer used are deleted and the memory
used by them is freed by the automatic garbage collector. This is
also one of the reason for its high performance.
■Distributed: - Java is designed as a distributed language for creating
applications on networks. It has the ability to share both data and
programs. Java applications can open and access remote objects on
Internet as easily as they can do in a local system. This enables
multiple programmers at multiple remote stations to work together
on a single project.
■Dynamic: Java is a dynamic language. Java is capable of
dynamically linking in new class libraries, methods and objects. Java
can also determine the type of class through a query. Java programs
support functions written in other languages such as C and C++.
These functions are known as native methods. This facility enables

10
the programmers to use the efficient functions to available in these
languages. Native methods are linked dynamically at runtime.

b)Write a note on:


i) Increment and decrement operator
Increment and Decrement Operator:
Java provides two operator increment operator ( ++ ) and decrement
operator (--). Increment operator is used to add 1 into the variable
previous value. Decrement operator is used to subtract 1 from the
variable previous value.
e.g. i++ // If initially i value is 10 then after this instruction
execution it becomes 11
i-- // If initially i value is 10 then after this instruction
execution it becomes 9
Increment operator has two formats: one is prefix and another is
postfix operator.
i++ and ++i
When first one is used in assignment it first perform the assignment
and then increment the value of ‘i’, while later one increment the value
of ‘i’ and then performs assignment.
Same thing is true for the decrement operator.
Operator Meaning Usage
++ Pre-Increment ++ expr
++ Post-Increment expr++
-- Pre-Decrement -- expr
-- Post-Decrement expr –
// Demonstrate ++
classIncDec {
public static void main(String args[]) {
int a = 1;
int b = 2; output:
int c; a=2
int d; b=3
c = ++b; c=4
d = a++; d=1
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
11
ii) Type conversion in expression.
 For some types, it is possible to assigning a value of one type to a
variable of a different type without a cast.
 Java does the conversion of the assigned value automatically.
 This is known as automatic type conversion.
 Automatic type conversion is possible only if the destination
type has enough precision to store the source value.
 For example, int is large enough to hold a byte value. Therefore,
byte b=75;
inta =b; are valid statements.
 The process of assigning a smaller type to a larger one is known
as widening or promotion and that of assigning a larger type to a
smaller one is known as narrowing.
Note that narrowing may result in loss of information.
The following program shows the creation of variables of basic
types and also shows the effect of type conversions.
class TypeWrap
{
public static void main(String args[])
{
System.out.println(“Variables created”);
char c = ‘x’;
byte b=50; Output:
short s= 1996; Variables created
int i=123456789; c=x;
long l=1234567654321L; b=50
float f1=3.142F; s=1996
float f2=1.2e-5F; i=123456789
double d2=0.000000987; l=1234567654321
System.out.println( “c =” +c); f1=3.142
System.out.println( “b =” +b f2=1.2e-005
System.out.println( “s =” +s); d2=9.87e-007
System.out.println( “i =” +i); Types converted
System.out.println( “l =” +l); (short)b=50
System.out.println( “f1 =” +f1); (short)i=-13035
System.out.println( “f2 =” +f2); (float)l=1.234567e+012
System.out.println( “d2=” +d2); (int)f1=3
System.out.println( “ ”);
System.out.println( “Types converted “);
short s1=(short)b;
short s2=(short)i;
float n1=(float)i;
12
int m1=(int)f1;
System.out.println(“ (short)b =” +s1);
System.out.println(“ (short)i =” +s2);
System.out.println(“ (float)l =” +n1);
System.out.println(“ (int)f1 =” +m1);
}
} Note that floating point constants have a default type of double.
So, float x=7.56 should be written as float x=7.56f;
c) With the syntax and example explain the process of reading a
character from the Keyboard.
To read a character from a BufferedReader, use read( ).
read( ) that we will be using is:int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input
stream and returns it as an integer value. It returns –1 when the end of
the stream is encountered.
// Use a BufferedReader to read characters from the console.
import java.io.*;
classBRRead {
public static void main(String args[])throws IOException
{ output:
char c; Enter
BufferedReaderbr = new BufferedReader(new characters, 'q' to
InputStreamReader(System.in)); quit.
System.out.println("Enter characters, 'q' to quit."); 123abcq
// read characters 1
do{ 2
c = (char) br.read(); 3
System.out.println(c); a
} while(c != 'q'); b
} c
} q
d) Explain nested switch statement with syntax and example.
You can use a switch as part of the statement sequence of an outer
switch. This is called a nested switch.
Since a switch statement defines its own block, no conflicts arise
between the case constants in the inner switch and those in the outer
switch.
Syntax:
switch(expression)
{
case constant1: statement sequence
switch(expression){
13
case constant1: statement sequence
break;
case constant2: statement sequence
break;
}
break;
case constant2: //….
For example, the following fragment is perfectly valid:
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
1. Here, the case 1: statement in the inner switch does not conflict with
the case 1: statement in the outer switch.
2. The count variable is only compared with the list of cases at the
outer level.
3. If count is 1, then target is compared with the inner list cases.

3. a) Write a note on Java contribution to the internet.


The reason for this is quite simple:
o Java expands the universe of objects that can move about freely in
cyberspace.
o In a network, two very broad categories of objects are transmitted
between the server and your personal computer: passive
information and dynamic, active programs.
o For example when you read your e-mail, you are viewing passive
data. Even when you download a program, the program’s code is
still only passive data until you execute it.
o However, a second type of object can be transmitted to your
computer: a dynamic, self-executing program.
o Such a program is an active agent on the client computer, yet is
initiated by the server.
o For example, a program might be provided by the server to
display properly the data that the server is sending.
14
o As desirable as dynamic, networked programs are, they also
present serious problems in the areas of security and portability.
 Java addresses those concerns has opened new form of program:
the applet.
Java Applets and Applications
Java can be used to create two types of programs: applications and applets.
 An application is a program that runs on your computer, under
the operating system of that computer.
 When used to create applications, Java is not much different
from any other computer language.
 An applet is an application designed to be transmitted over the
Internet and executed by a Java-compatible Web browser.
 An applet is actually a tiny Java program, dynamically
downloaded across the network, just like an image, sound file, or
video clip.
 The important difference is that an applet is an intelligent
program, not just an animation or media file.
 In other words, an applet is a program that can react to user
input and dynamically change—not just run the same animation
or sound over and over.
 As exciting as applets are, if Java were not able to address the
two fundamental problems associated with them: security and
portability.
Security:
 Every time that you download a “normal” program, you are
risking a viral infection.
 Prior to Java, most users did not download executable
programs frequently, and those who did scanned them for
viruses prior to execution.
 In addition to viruses, another type of malicious program
exists that must be guarded against.
 This type of program can gather private information, such as
credit card numbers, bank account balances, and passwords,
by searching the contents of your computer’s local file system.
Java answers both of these concerns by providing a “firewall”
between a networked application and your computer.
 When you use a Java-compatible Web browser, you can
safely download Java applets without fear of viral infection or
malicious intent.

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

b) With an example explain the different types of constructors supported by


Java.
Constructor is a special type of method. It will initialize the object when
it is created. Constructors have the same name as the class itself.
Secondly they do not specify a return type, not even void. This is
because they return the instance of the class itself.
Java supports two types of constructor: Default constructor and
Parameterized constructor
Default constructor:
In Default constructor it does not contains any argument list
Parameterized Constructors:
Parameters are added to a constructor in the same way that they are
added to a method: just declare them inside the parentheses after the
constructor’s name.
Example:
class Rectangle
{
int length, width;
Rectangle() // default constructor
{
Length=0;
Width=0;
}
Rectangle(int x, int y) //Parameterized constructor
{
length = x;
width = y;
}

int reatArea()
{
int area = length * width;
26
return(area);
}
}

class RectArea //class with main method


{
public static void main(String args[])
{
Rectangle rect=new Rectangle(); // calling default constructor
Rectangle rect1 = new Rectangle(15,10); //calling parameterized
int area1=rect1.rectArea();
System.out.println(“Area1 = “+area1);
}
}
c) Explain how to pass variable-length arguments with suitable example.
 A feature that simplified the creation of methods that require a
variable number of arguments.
 This feature is called varargs, which is short for variable-length
arguments.
 A method that takes a variable number of arguments is called a
variable-arity method, or simply a varargs method.
 The parameter list for a varargs method is not fixed, but rather
variable in length.
 Thus, a varargs method can take a variable number of arguments.
Varargs Basics
A variable-length argument is specified by three periods (...). For
example, here is how to write a method called vaTest( ) that takes a
variable number of arguments:
//Demonstrate variable- length Arguments Output:
class varArgs{ Number of args:1
//vaTest() uses a varag Contenst:
Static void vaTest(int… v){ arg0:10
System.out.println(“Number of args:”+v.length); Number of args:3
System.out.println(“Contents:”); Contents:
for(int i=0;i<v.length;i++) arg 0:1
System.out.println(“arg”+i+“:”+v[i]); arg1:2
System.out.prinln(); arg2:3
} Number of args:0
public static void main (String args[]){ Contents:
{
//Notice how vaTest() can be called with a variable number of arguments.
vaTest(10); // 1 arg
27
vaTest(1,2,3); // 3 args call with different numbers of arguments
vaTest(); // no args
}
}
d) With an example explain single level inheritance.
 The mechanism of deriving a new class from an old one is called
inheritance.
 The old class is known as the base class or super class or parent class
and the new one is called the subclass or derived class or child class.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
To see how, let’s begin with a short example.
The following program creates a superclass called A and a subclass
called B. Notice how the keyword extends is used to create a subclass
of A.
// A simple example of inheritance.
// Create a superclass.
class A { The output from this
int i, j; program is shown here:
void showij() { Contents of superOb:
System.out.println("i and j: " + i + " " + j); i and j: 10 20
} Contents of subOb:
} i and j: 7 8
// Create a subclass by extending class A. k: 9
class B extends A { Sum of i, j and k in subOb:
int k; i+j+k: 24
void showk() { As you can see, the subc
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
28
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Unit-III
6. a) With an example explain how to create and importing the
user defined package.
Creating our own package (user defined) involves the following steps:
1. Declare the package at the beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source
files are stored
4. Store the listings as the classname.java file in the subdirectory created
5. Compile the file. This creates .class fie in the subdirectory
Remember that case is significant and therefore the subdirectory name
must match the package name exactly
To create a package, we must first declare the name of the package
using the package keyword followed by a package name. This must be
the statement in a java source file name. This must be the first
statement in a java source file.
package firstpackage; //package declaration
public class FirstClass //class definition
{
-----------
----------(body of class)
---------
}
Here the package name is firstpackage. The class FirstClass is now
considered a part of this package. This listing would be saved as a file
called FirstClass.java and located in a directory named firstpackage.
29
When the source file is compiled, java will create a .class file and store
it in the same directory.
Remember that the .class file must be located in a directory that has the
same name as the package, and this directory should be a subdirectory
of the directory where classes that will import the package are located.

Accessing a package (or)importing a package:


The import statement can be used to search a list of packages for a
particular class. The general form of import statement for searching a
class follows:
import package1[.package2][.package3].classname;
Here package1 is the name of the top level package; package2 is the
name of the package that is inside the package1, and so on. Finally, the
explicit classname is specified. Note that the statement must end with
semicolon (;).
The import statement should appear before any class definition in a
source file. Multiple import statements are allowed.
Eg: import firstPackage.secondPackage.Myclass;
After defining this statement, all the members of the Myclass can be
directly accessed using the class name or its objects directly without
using the package name.
We can also use import package name.*;
Here package name may denote a single or a hierarchy of packages.
The *indicates that the compiler should search this entire package
hierarchy when it encounters a class name. So we can access all classes
contained in the above package directly.
b) With an example explain implementing an interface.
Implementing interfaces:
Interfaces are used as “superclasses” whose properties are inherited by
classes. It is therefore necessary to create a class that inherits the given
interface. This is done as follows:
class classname implements Interfacename
{
Body of classname
}
Here the classname “implements” the interface interfacename. A more
general form of implementation may look like this:
class classname extends superclass implements interface1,interface2,…
{
Body of classname
}
30
Example: //InterfaceTest.java
interface Area //interface defined
{
final static float pi=3.14F;
float compute(float x, float y);
}
class Rectangle implements Area //interface implemented
{
public float compute (float x, float y)
{
return (x*y);
}
}
class Circle implements Area //another implementation
{
public float compute ( float x, float y)
{
return ( pi*x*x);
}
}
class InterfaceTest
{
public static void main (String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area; //interface object
area = rect;
System.out.println(“Area of Rectangle=”+area.compute(10,20));
area =cir;
System.out.println(“Area of circle=”+area.compute(10,0));
}
}
Output: Area of Rectangle=200 Area of circle=314
c)Illustrate the use of finally with suitable example.
 The finally clause is an optional clause of try/catch block.
 The statements within the finally clause are executed irrespective
of the fact that an exception is thrown or not.
 Typically, the statements within the finally clause do cleanup
process such as releasing resources, closing files, save status of the
process.

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>

<PARAM NAME="Greetings" VALUE="Hello Friend, How are


you?">
</APPLET>
</body>
</HTML>
//HelloAppletMsg.java
import java.applet.Applet;
import java.awt.*;
public class HelloAppletMsg extends Applet {
String msg;
public void init()
{
msg = getParameter("Greetings"); This is name of
if( msg == null) parameter specified in
msg = "Hello"; PARAM tag;
}
public void paint(Graphics g) { This method returns the
g.drawString (msg,10, 100); value of paramter.
}
}
b)What is the purpose of TextField class? Explain any three
methods of text field class with syntax and example.
 The TextField class implements a single-line text-entry area, usually
called an edit control.
 Text fields allow the user to enter strings and to edit the text using the
arrow keys, cut and paste keys, and mouse selections.
 TextField is a subclass of TextComponent.
 TextField defines the following constructors:
40
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
The first version creates a default text field.
The second form creates a text field that is numChars characters
wide.
The third form initializes the text field with the string contained
in str.
The fourth form initializes a text field and sets its width.
 TextField (and its superclass TextComponent) provides several
methods that allow you to utilize a text field.
 To obtain the string currently contained in the text field, call getText( ).
 To set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.
The user can select a portion of the text in a text field.
Also, you can select a portion of text under program control by using
select( ).
Your program can obtain the currently selected text by calling
getSelectedText( ).
These methods are shown here:
String getSelectedText( )
void select(int startIndex, int endIndex)
 getSelectedText( ) returns the selected text.
 The select( ) method selects the characters beginning at startIndex and
ending at endIndex–1.
 You can control whether the contents of a text field may be modified
by the user by calling setEditable( ).
 You can determine editability by calling isEditable( ).
 These methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
 isEditable( ) returns true if the text may be changed and false if not.
 In setEditable( ), if canEdit is true, the text may be changed. If it is
false, the text cannot be altered.
// Demonstrate text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
41
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet
implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}

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

d) With an example explain the use of anonymous inner classes to handle


events.
 you can implement listeners through the use of anonymous inner
classes.
 Anonymous inner classes are inner classes that don’t have a name.
 Anonymous inner classes make implementing some types of event
handlers much easier.
 For example, given a JButton called jbtn, you could implement an
action listener for it like this:
jbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
//Handle action event here
}
});
 Here, an anonymous inner class is created that implements the
ActionListener interface
 The body of the inner class begins after the { that follows new
ActionListener( ). Also notice that the call to addActionListener( ) ends
with a ) and a ; just like normal.
 The same basic syntax and approach is used to create an anonymous
inner class for any event handler.
 One advantage to using an anonymous inner class is that the
component that invokes the class’ methods is already known.
52
Credit Based Third Semester B.C.A Degree Examination, Nov./Dec. 2015
(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 polymorphism?
Polymorphism means the ability to take more than one form using
operator or functions in different ways. Depending on what they are
operating on is called “Polymorphism”. Carbon is considered
polymorphic as it crystallizes to form graphite as well as diamond.
Overloading is a kind of polymorphism.
b) List different integer data types available in Java.
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
c) Write a for loop to display even numbers between 1 and 100.
// Demonstrate the for loop.
classeven {
public static void main(String args[]) {
int n;
for(n=0; n<=100; n=n+2)
System.out.println("n= " + n);
}
}
d) What are classes and objects?

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.

3. a) List and explain arithmetic and logical operators in Java.


Arithmetic Operators:
It is also called as 'Binary operators'. It is used to perform arithmetical
operations. These operators operate on two operands. These all operators
can work with only built-in data type (int, float, char, double, etc.)
Operator Operation Example a=10 b=5
+ Addition C=a+b=15
- Subtraction C=a-b=5

58
* Multiplication C=a*b=50
/ Division C=a/b=2
% Remainder C=a%b=0

//Demonstrate the basic arithmetic operators.


class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d; output:
System.out.println("a = " + a); Integer Arithmetic Floating Point
System.out.println("b = " + b); a=2 da = 2.0
System.out.println("c = " + c); b=6 db = 6.0
System.out.println("d = " + d); c=1 dc = 1.5
System.out.println("e = " + e); d = -1 dd = -0.5
// arithmetic using doubles e=1 de = 0.5
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
Boolean Logical Operators
The Boolean logical operators shown here operate only on boolean
operands. All of the binary logical operators combine two boolean
values to form a resultant boolean value.
Operator Result
& Logical AND
| Logical OR
59
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
The logical Boolean operators, &, |, and ^, operate on boolean values
in the same way that they operate on the bits of an integer.
The logical !operator inverts the Boolean state: !true == false and !false
== true.
The following table shows the effect of each logical operation:
A B A|B A&B A^B !A
False False False False False True
True False True False True False
False True True False True True
True True True True False False
// Demonstrate the boolean logical operators.
classBoolLogic {
Output :
public static void main(String args[]) {
a = true
boolean a = true;
b = false
boolean b = false;
a|b = true
boolean c = a | b;
a&b = false
boolean d = a & b;
a^b = true
boolean e = a ^ b;
a&b|a&!b = true
boolean f = (!a & b) | (a & !b);
!a = false
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);

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.

K) Write the limitations of AWT components.


Refer question paper nov/Dec 2014 part a 1 L answer
l) What is the purpose of Volatile modifier?
 The volatile modifier tells the compiler that a variable can be changed
unexpectedly by other parts of your program. One of these situations
involves multithreaded programs.

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

c) Explain the general syntax for defining and implementing an interface.


Give code example.
refer Qeustion paper nov/dec 2014 part B Unit-III 6 b answer

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

You might also like