Sunteți pe pagina 1din 21

S.Y. B.Sc. (IT) : Sem.

IV
Core Java
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75

Q.1 Attempt any THREE of the following : [15]


Q.1(a) Write a short note on Java Virtual Machine (JVM). [5]
Ans.: 1. Java Virtual Machine [JVM] is at the heart of Java's platform. Java Virtual Machine is
an Abstract Computer. It emulates a Java processor on the CPU of the host machine i.e.
a machine within a machine. JVM interprets Java byte code and translates the
interpretations into actions or operating system calls.
2. For example, a request to open and read a file will involve an operating system call.
Different operating systems handle requests in different manner, but the developer
does not need to worry about this. JVM takes over the responsibility of handling these
translations. This way, the operating system and CPU architecture on which Java
software is running is completely immaterial to the developer. JVM, thus is the key
component that brings Platform Independence feature to Java. Nowadays, several
popular platforms have their own JVM implementations and hence a Java program
written and compiled on a Java-compliant platform can be run on any other Java-
compliant platform.

3. Working of JVM:
(a) Using the Java compiler [javac] the developer's
created source code is compiled to byte code
instructions [which the JVM understands]
(b) The interpreter [a part of the JVM] converts these
byte code instructions to the machine language that
is understood by the hardware for which the
interpreter has been created
(c) Finally the JVM asks the underlying operating system
to execute the machine level instructions
(d) JVM can be :
 Incorporated into a Web browser in order to execute Java applets
 Installed and bound to Web servers to execute server-side Java programs
 Installed on a client machine to run stand-alone Java applications

4. JVM Components : JVM is composed of the following two components:


(a) Classloader : Loads the .class files from permanent storage media after converting
them into the implementation dependent internal data structures. The .class files of the
Java API are also loaded into the JVM. The JVM can control multiple class loaders at
runtime.
(b) Execution Engine : Uses the above data structures and converts the byte code
instructions into machine-level instructions for the underlying operating system which
are subsequently executed by the Operating system.

5. Technically, JVM :
(a) Invokes when a Java program executes
(b) Terminates when the Java program ends
(c) Starts the application by executing main() defined within the program
(d) Requires the name of the .class file that contains main() to start an application

6. The number of JVMs running on the machine is equal to the number of Java I programs
that are being executed.

-1-
Vidyalankar : S.Y. B.Sc. (IT)  CJ

Q.1(b) List and explain the salient features of Java. [5]


Ans.: Java has various features as follows :
1. Simple : Java is very simple especially compared to languages like C, C++. Java doesn’t
allow pointers, which was a complicated concept in C/C++. Java also doesn’t allow
operator overlapping, goto statement etc. Besides the syntax rules of Java are kept
almost similar to that of C/C++, hence allowing easy migration for the C/C++
programmers.

2. Purely object-oriented : Java is a purely object oriented language means no program


can be written without a class. An object oriented programming language needs to
necessarily have classes and object. A class is a type of objects and an object is an
instance of class.

3. Platform Independent : This is most important feature of Java. This was the main
feature what James Gosling wanted from the programming language to be used in their
software. Platform independent means a program made for one platform will also work
on any other platform. A platform is a combination of a system (computer), operating
system and other packages with that system. For example, a Pentium based system with
windows, or a Pentium based system with Linux, or a AMD based system with Window
etc. The feature “Platform Independent” ensures that the program or software
developed in the Java programming language can work on any of the above said or some
other platform. This was not possible in earlier programming languages like C/C++. This
is possible with Java because of a special tool called as Java Virtual Machine (JVM).

4. Distributed : This feature of Java was found to be very useful. Because of being
platform independent, a java based program can be distributed over internet and hence
run on any platform (system) in the world. This feature of being distributed of Java has
made many things possible over the Internet.

5. Dynamic : We have seen what is meant by dynamic and static in C++. Those things that
happen during the compile time are called as static while those things that happen
during the execution time are called as dynamic. Java has more dynamic features
compared to C++.

6. Multi-Threaded : This is another new thing implemented in Java. A thread is one


function in a program or a process. We can have multiple threads that can run
concurrently with the same program. There is a time sharing implemented to share the
processor resource for multiple threads on a time scale i.e. one thread runs for some
time then another thread for some time and so on multiple threads can run concurrently
wherein any one of the thread is being executed by the processor at any given time.

7. Garbage collected : An object which is no more in use is automatically thrown in


garbage by JVM. Thus the memory allocated to an object is automatically made free and
available for other variables or objects. This removes the requirement of destructor as
it was required in C++. In C++ the memory allocated to an object was to be made free by
a destructor. In Java it is automatically done, hence garbage collected.

8. Robust : Java has a very good inbuilt exception handling capacity that makes a Java
program robust. Also, Java does not keeps the authority of memory allocation and de-
allocation with the programmer. JVM automatically allocates and free up the memory
allocated for an object. Hence a software made on Java will not crash so easily as it would
do on a C/C++ based software.
9. Secure : Security issues like virus attack are less possible on a Java based software.

10. Interpreted : Java programs are said to be interpreted. Java programs are converted
into a special byte code. This byte code is interpreted by the JVM. JVM interprets the

-2-
Prelim Question Paper Solution

byte code generated by the Java complier. By interprets, it means that the JVM
converts the byte code into the machine understandable code.

11. Portable : A program written on Java is portable i.e. it can be carried over anywhere on
any computer. This is because the Java program is platform independent and home can
work on any computer.

12. High Performance : Earlier there was a problem with JVM. The JVM has to interpret
the Java program and then execute the same. This use to take more time i.e. first
convert from byte code to machine code, then execute it. Later Java people introduced
a special tool in JVM called as Just In Time (JIT) compiler. This increased the speed
and hence giving high performance.

13. Scalability : Java based programs are scalable over a huge number of systems besides
computer. The team of Sun Microsystems Inc. had mainly developed this programming
language tool for programming the systems used in consumer electronics like washing
machine, microwave oven, etc. Hence this programming language can be used even in such
independent systems and not just computers. Thus Java is said to be scalable over all
systems.

Q.1(c) What are the primitive data types in java? Briefly explain their size, range and [5]
other details.
Ans.: A primitive values or type is predefined by the language and is named as a reserved
keyword. There are eight primitive data types :
1) byte :
 It is a 8 bit signed two’s compliment integer.
 It has a minimum value of 128 and a maximum of 127.
2) short :
 The short datatype is a 16 bit signed two’s compliment integer.
 It has a minimum value of 32,768 and maximum value 32767.
 You use sheet to save memory in large array.
3) int :
 By default int data type is a 32bit signed two’s complement integer, which has a
minimum value of 231  1.
4) long :
 The long data type is a 64 bit two’s compliment integer.
 The signed long has a minimum value of 263 and a maximum value of 263  1.
5) boolean :
 It can accept either true or false values.
 By default the boolean value is false.
 Size is 1 bit.
e.g. : Boolean b = true ;
if (b = = true).
system.out.println(“Match”);
6) Char :
 It’s a Unicode character.
 The default value is \u0000
 Size is 16 bits
 A character is a single character.
e.g.: char a =‘A’;
system.out.println(“Char A = ” + a);
7) float :
 The float datatype is a single precision 32 bit floating point.
 Size is 32 bits.

-3-
Vidyalankar : S.Y. B.Sc. (IT)  CJ

 Suffix used is F/&


e.g.: float fi = 3.14f;
8) double :
 double datatype is a double precision 64 bit floating point.
 for decimal values this datatype is generally the default choice.
e.g.: double salary = 10000.00;
system.out.println(“Salary =” + salary);

Q.1(d) Write a java code to : [5]


(i) Check whether the string “madam” is starting and ending with same letter
(ii) Count all vowels in string “welcome”
(iii) Replace ‘w’ with ‘W’ in a string “welcome”
(iv) Append “Welcome” and “MADAM”
Ans.: package stringdemo;
public class StringDemo
{
public static void main(String[] args)
{
String s1="MADAM";
String s2="welcome";
int v=0;
if(s1.charAt(0)==s1.charAt(s1.length()-1))
System.out.println(s1+" Start and end char of the string is same ");
for(int i=0;i<s2.length();i++)
{
char ch= s2.charAt(i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
v++;
}
System.out.println("Total Vowels in Welcome is "+v);
String updates2=s2.replace('w', 'W');
System.out.println(updates2);
String appends2s1 =s2.concat(s1);
System.out.println("Appending S2 and S1 = "+appends2s1);
}
}

Q.1(e) Explain any five String methods. [5]


Ans.:
char charAt(int index) returns char value for the particular
index
int length() returns string length
String substring(int beginIndex) returns substring for given begin
index.
String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index.
boolean contains(CharSequence s) returns true or false after matching
the sequence of char value.
boolean equals(Object another) checks the equality of string with
the given object.
boolean isEmpty() checks if string is empty.
String concat(String str) concatenates the specified string.
String replace(char old, char new) replaces all occurrences of the

-4-
Prelim Question Paper Solution

specified char value.


static String equalsIgnoreCase(String another) compares another string. It doesn't
check case.
int indexOf(int ch) returns the specified char value
index.
int indexOf(String substring) returns the specified substring
index.
String toLowerCase() returns a string in lowercase.
String toUpperCase() returns a string in uppercase.
String trim() removes beginning and ending spaces
of this string.
static String valueOf(int value) converts given type into string. It is
an overloaded method.

Q.1(f) Explain the terms : [5]


narrowing, widening, auto boxing, unboxing, instantiation
Ans.: Narrowing :
 It is nothing but downward casting.
 Data is lost in narrowing.
e.g.: float f = 10.5 f;
int a = (int) f ;
system.out.println(f); || 10.5
system.out.println(a); || 10

Widening :
 It is also known as upward casting.
 Data loss does not happen during widening.
e.g.: int a = 10;
float f = a;
system.out.println(a); || 10
ststem.out.println(f); || 10.0

Instantiation :
 Java is an object oriented programming language. In oops, an object is an instance of a
class.
e.g. : Employee class, any new employee object used in the program is considered as an
instance of that class.
Therefore the term for creating a new instance of that class is instantiation.

Autoboxing :
 Converting a primitive value into an object of the corresponding wrapper class is called
autoboxing.
e.g. : Converting int. to Integer class.
The java complier applies autoboxing when a primitive value is :
 Passed as a parameter to a method.
 Assigned to a variable of the corresponding wrapper class.

Q.2 Attempt any THREE of the following: [15]


Q.2(a) Discuss in details the working of ‘foreach’ loop in java. [5]
Ans.: In Java, there is another form of for loop (in addition to standard for loop) to work with
arrays and collection, the enhanced for loop.
Syntax : for(data_type item : collection)
{

}

-5-
Vidyalankar : S.Y. B.Sc. (IT)  CJ

In the above syntax,


 collection is a collection or array variable which you have to loop through.
 item is a single item from the collection.

Here's how the enhanced for loop works. For each iteration, for-each loop
1. iterates through each item in the given collection or array (collection),
2. stores each item in a variable (item)
3. executes the body of the loop.

Here's an example to iterate through elements of an array using standard for loop:
class AssignmentOperator
{
public static void main(String[] args)
{
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// foreach loop
for (char item: vowels)
{
System.out.println(item);
}
}
}

Q.2(b) Write a short note on access specifiers in java. [5]


Ans.: There are 4 types of Java access modifies :
1. Private 2. Default 3. Protected 4. Public

1. The private access modifier is accessible only within class.


e.g.: Class A {
private int data = 40;
private void msg ( ) {
System.out.println (“Hello java”);
}
public class simple
{
public static void main (String args [ ])
{
A obj = new A( );
system.out.println (obj.data);
obj.msg ( );
}
}
}

2) Default :
 If you don’t use any modifier, it is treated as default by default.
 The default modifier is accessible only within package.

3) Protected :
 The protected access modifier is accessible within package & outside the package but
through inheritance only.
 The protected access modifiers can be applied on the data members method &
constructor. It can’t be applied on the class.

-6-
Prelim Question Paper Solution

4) Public :
 It is accessible everywhere. It has the widest scope among all other modifiers.
Access Within Within Outside subclass Outside
Modifier Class Package Package Package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Q.2(c) Explain method overloading with example. [5]


Ans.: Method Overloading:
 If in a class, if we have multiple methods with the same name, then it is called as
method overloading.
 Although name of methods are same but parameter list shoud be different.
 It means, either number of parameters or type of parameters of both must be
different.
 Method overloading is example of compile time polymorphism.
 This concept is mainly used if we want to execute same task multiple time.

Example : Write a program to calculate area of circle and area of rectangle using method of
overloading.
import java.util.;
class sample
{
void area (int r)
{
double a = 3.14rr;
System.out.println (“Area of circle=”+a);
}
void area (int  , int b)
{
int a =  b;
System.out.println (Area of rectangle =”+a);
}
}
class test
{
public static void main (String args[ ])
{
Sample s = new Sample ( );
Scanner t = new Scanner (System.in);
System out.printin (“Enter radius”);
int r = t. next Int ( );
s. area (r);
System.out.println (“Enter length, breadth”);
int  = t. nextInt ( );
int b = t. nextint ( );
s. area (  , b);
}
}

Q.2(d) Write a program to perform addition, subtraction, multiplication and division on [5]
two inputs using switch case.
Ans.: import java.util.Scanner;
class Calculator

-7-
Vidyalankar : S.Y. B.Sc. (IT)  CJ

{
public static void main(String[] args)
{
char operator;
double number1, number2, result;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter operator (either +, -, * or /): ");
operator = scanner.next().charAt(0);
System.out.print("Enter number1 and number2 respectively: ");
number1 = scanner.nextDouble();
number2 = scanner.nextDouble();
switch (operator)
{
case '+':
result = number1 + number2;
System.out.print(number1 + "+" + number2 + " = " + result);
break;

case '-':
result = number1 - number2;
System.out.print(number1 + "-" + number2 + " = " + result);
break;

case '*':
result = number1 * number2;
System.out.print(number1 + "*" + number2 + " = " + result);
break;

case '/':
result = number1 / number2;
System.out.print(number1 + "/" + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;
}
}
}

Q.2(e) Demonstrate the behaviour of static members in java with suitable example. [5]
Ans.:  If you declare any variable as static, it is known as static variable.
 If makes your program memory efficient.
 Static variables gets memory only once in class area at the time of class loading.
 Example :
Class Student
{
int rollno;
string name;
static string college = “ VIT”;
student (int r, string n)
{
rollno = r;
name = n;

-8-
Prelim Question Paper Solution

}
void display ( )
{
system.out.println (roll no + “ “ + name + “ “ + college);
}
public static void main (string args [ ]);
{
student S1 = new student (100, “ABC”);
student S2 = new student (1200, “PQR”);
s1.display( );
s2.display( );
}
}

Q.2(f) Explain variable arguments (Vargs). [5]


Ans.: Variable Arguments (Varargs) :
 The varargs allow the method to accept zero or multiple arguments.
 Before varargs either we use overloaded method or take an a array as the method
parameter but it was not considered good because it leads to maintenance problem.
 We don’t know how many arguments we will have to pass in the method, varargs is the
better approach.
 We don’t have to provide overloaded method so less codes.
 Syntax :
return  type method_name (data_type … variableName)
{

}

Q.3 Attempt any THREE of the following: [15]


Q.3(a) What is the use of keyword ‘this’? [5]
Ans.: this :
 This is a reference variable that refers to the current object.
 It is used to refer current class instance variable.
 It is used to invoke current class method.
 Used to invoke current class constructor.
 This can be used to return the current class instance from the method.

e.g., Public class Demo


{ int a,b;
Demo ( int a, int b)
{
this . a = a;
this . b = b;
}
void display ( )
{
system.out.println (“a =” + a + “b=” +b)
}
public static void main (string args [ ])
{
Demo.d = new demo (10, 20);
d . display ( );
}
}

-9-
Vidyalankar : S.Y. B.Sc. (IT)  CJ

Q.3(b) Explain the use of ‘super’ keyword. [5]


Ans.: Super keyword is used to access methods of the parent class while this is used to access
methods of the current class.

The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword :


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Example:
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

Here is given the 6 usage of this keyword in java:


1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name, float fee)
{
this.rollno=rollno;
this.name=name;

- 10 -
Prelim Question Paper Solution

this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);
}
class TestThis
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Q.3(c) Write a program to implement a concept of multilevel inheritance. [5]


Ans.: class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

Output:
Class X method
Class Y method
Class Z method

Q.3(d) Explain use of ‘final’ keyword in detail. [5]


Ans.: Final : Final is a non-access modifier applicable only to a variable, a method or a class.
(a) If final is used with variable : It is used to create constant variables.
(b) If final is used with methods : It is used to prevent method overriding.

- 11 -
Vidyalankar : S.Y. B.Sc. (IT)  CJ

(c) If final is used with classes : It is used to prevent inheritance.


e.g., Final double pi = 3.142;

Finally : It is a block that in used to execute important code such as closing connection,
stream etc.
 Finally block always executed whether exception is handled or not.
 Finally block follows try or catch block.

Finalize ( ) : The java.lang.object. finalize ( ) is called by the garbage collector on an


object when garbage collection determines that there are no more references to the
object.

A subclass overrides the finalize method to dispose of the system resources or to perform
other clean up.

Q.3(e) Differentiate between abstract class and interface in java. [5]


Ans.:
Abstract Class Interface
1 An abstract class may provide code/ An interface cannot provide for code
methods which will have to be overridden (Remember the void methods shown in
later. above example).
2 Abstract Classes may contain class Interface does not contain class
modifiers. modifiers.
3 A class may inherit only one abstract A class may inherit several interfaces
class.
4 An abstract class defines the core Interfaces are used to define the
identity of a class and there it is used peripheral abilities of a class.
for objects of the same type.
5 An abstract class can have fields and No fields can be defined in interfaces.
constants defined.
6 Faster Processing. Slower processing.
7 If various implementations are of the If various implementations only share
same kind and use common behaviour or method signatures then it is better to
status then abstract class is better to use interfaces.
use.

8 Ex. Ex.
Public abstract class Public interface Demo
Shape { {
Public abstract void void draw ( );
draw ( ); }
}

Q.3(f) Explain the steps to create user defined package in java. [5]
Ans.: A java package is a group of similar types of classes, interfaces and sub-packages. Package
in java can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package :


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

- 12 -
Prelim Question Paper Solution

2) Java package provides access protection.


3) Java package removes naming collision.
Simple example of java package :
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

How to compile java package : If you are not using any IDE, you need to follow the syntax
given below:
1. javac -d directory javafilename

For example :
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).

How to run java package program : You need to use fully qualified name e.g. mypack.Simple
etc to run the class.
To Compile : javac -d . Simple.java
To Run : java mypack.Simple

Output :
Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

Q.4 Attempt any THREE of the following: [15]


Q.4(a) Why do we need to use vectors? Explain with the help of an example. [5]
Ans.: Vector implements a dynamic array. It is similar to ArrayList, but with two differences –
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.

Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program. Following is the list of
constructors provided by the vector class.

 Vector( )
This constructor creates a default vector, which has an initial size of 10.

 Vector(int size)
This constructor accepts an argument that equals to the required size, and creates a vector
whose initial capacity is specified by size.

Example:
import java.util.*;
public class VectorExample
{
public static void main(String args[])

- 13 -
Vidyalankar : S.Y. B.Sc. (IT)  CJ

{
/* Vector of initial capacity(size) of 2 */
Vector<String> vec = new Vector<String>(2);

/* Adding elements to a vector*/


vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
vec.addElement("Fig");
/* check size and capacityIncrement*/
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity increment is: "+vec.capacity());
/*Display Vector elements*/
Enumeration en = vec.elements();
System.out.println("\nElements are:");
while(en.hasMoreElements())
System.out.print(en.nextElement() + " ");
}
}
Output :
Size is: 4
Default capacity increment is: 4
Elements are:
Apple Orange Mango Fig

Q.4(b) Explain : (i) int k = Integer.paraselnt(num); [5]


(ii) val = Ival, longValue();
(iii) dval = Double.valueOf(s);
Ans.: (i) int k = Integer.parseInt.(num);
In Java, anything that is accepted from user is in the form of string.
PauseInt is the method used to convert it into Integer. Here the value is stored in the
variable k.

(ii) Val = lval.longvalue( );


It returns the value of this Long as a long.
This method returns the numeric value represented by this object after conversion
of type long.
e.g., long obj = new long (77906);
long  = obj.longvalue ( );
system.out.println(“value of L =” + );

(iii) dval = Double.valueOf(s);


Here, dval is a variable of type Double value of is a method used to convert the s value
to double. Here s can be of another datatype.

Q.4(c) Explain life cycle of thread with a neat labeled diagram. [5]
Ans.: The life cycle of a thread :
 A thread exists in one of the five stages :
(i) New (ii) Runnable (iii) Running
(iv) Non-runnable (Blocked) (v) Dead
 The life cycle of the thread is completely controlled by JVM.

- 14 -
Prelim Question Paper Solution

Q.4(d) Explain any 3 different cases of exception handling. [5]


Ans.: An exception is a condition that is caused by a runtime error in the program.
1st Case : One try : One catch block
try {
int a = 10, b = 0,
int c = a/b;
system.out.println (“c =” + c);
system.out.println (“Exit”);
}
catch (ArithmeticException e)
{ system.out.println (“Division by 0 execptrun”); }
Here, if there is any error occurred during runtime it will be caught by the catch block.

2nd Case : One try : Many catch blocks


try { int a =10, b =5, c =3;
in x = a/ (bc);
int arr [ ] {3,4,5,6};
system.out.println (“x=” +x);
system.out.println(“arr[5] =” + arr [5]);
}
catch (ArithmeticExeception e )
{ system.out.println(“Division by zero”);}
catch (ArrayIndexOutOfBoundException e )
{
system.out.println(Array.index not found”);}
Here, when an exception in a try block is generated the java treat the multiple catch
statements Like cases in a switch statements.
3rd Case : One try : Many catch  finally
When finally block is defined, this is guaranteed to be executed, regardless of whether or
not in exception is thrown.
Syntax :
try{ ____
}
catch ()
{ ____
}
catch ()
{ ____
}
finally
{ ____
}

- 15 -
Vidyalankar : S.Y. B.Sc. (IT)  CJ

Q.4(e) Can we handle multiple exceptions using a single catch block? Justify your answer [5]
with an example.
Ans.: Java Catch Multiple Exceptions, Rethrow Exception. In Java 7, catch block has been
improved to handle multiple exceptions in a single catch block. If you are catching multiple
exceptions and they have similar code, then using this feature will reduce code duplication.

Example:
catch(IOException | SQLException ex)
{
logger.error(ex);
throw new MyException(ex.getMessage());
}
If a catch block handles multiple exception, you can separate them using a pipe (|) and in
this case exception parameter (ex) is final, so you can’t change it. The byte code generated
by this feature is smaller and reduce code redundancy.

Q.4(f) What do you mean by streams? Explain the concept of streams and types of [5]
streams available in Java.
Ans.: A stream is a sequence of objects that supports various methods which can be pipelined to
produce the desired result. The features of Java stream are  A stream is not a data
structure instead it takes input from the Collections, Arrays or I/O channels.

A stream can be defined as a sequence of data. There are two kinds of Streams –
 InPutStream : The InputStream is used to read data from a source.
 OutPutStream : The OutputStream is used for writing data to a destination.
FileInputStream

ByteArrayInputStream
InputStream BufferedInputStream
FilterInputStream
DataInputStream
ObjectInputStream
Object
FileOutputStream

ByteArrayOutputStream
OutputStream BufferedOutputStream
FilterOutputStream
DataOutputStream
ObjectOutputStream

In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

OutputStream : Java application uses an output stream to write data to a destination; it


may be a file, an array, peripheral device or socket.

InputStream : Java application uses an input stream to read data from a source; it may be
a file, an array, peripheral device or socket.

Q.5 Attempt any THREE of the following: [15]


Q.5(a) Explain <APPLET> and <PARAM> tags with their attributes. [5]
Ans.: <APPLET>tag
 Applets are embedded in HTML documents with the <APPLET> tag.

- 16 -
Prelim Question Paper Solution

 It contains the attributes that identify the applet to be displayed and optionally give
the web browser hints about how it should be displayed.
 There are different attributes in applet tag.
e.g.: <APPLET Code = Demo width = 100 height = 100 >
</APPLET>
So here the .java file should be stored and saved as Demo.java after compilation there
will be DemoClass file created.<APPLET> code will search for class file.

<PARAM> tag :
 The PARAM element is used to provide command Line arguments to a Java applet which
is embedded in a documents with the APPLET element. It has 2 attributes NAME
specifies the name of the argument, Value specifies the value for this argument.

Q.5(b) Explain Windows Fundamentals in AWT. [5]


Ans.: 1. The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level. The two most common windows are those derived from Panel,
which is used by applets, and those derived from Frame, which creates a standard
application window. Much of the functionality of these windows is derived from their
parent classes.

2. Component:
(a) At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component. Except for menus, all
user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component.
(b) It defines over a hundred public methods that are responsible for managing events,
such as mouse and keyboard input, positioning and sizing the window, and repainting. A
Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.

3. Container : The Container class is a subclass of Component. It has additional methods


that allow other Component objects to be nested within it. Other Container objects can
be stored inside of a Container (since they are themselves instances of Component).
This makes for a multileveled containment system. A container is responsible for laying
out (that is, positioning) any components that it contains. It does this through the use
of various layout managers.

4. Panel : The Panel class is a concrete subclass of Container. A Panel may be thought of as
a recursively nestable, concrete screen component. Panel is the superclass for Applet.
When screen output is directed to an applet, it is drawn on the surface of a Panel
object. In essence, a Panel is a window that does not contain a title bar, menu bar, or
border. This is why we don’t see these items when an applet is run inside a browser.
When you run an applet using an applet viewer, the applet viewer provides the title and
border. Other components can be added to a Panel object by its add( ) method
(inherited from Container). Once these components have been added, you can position

- 17 -
Vidyalankar : S.Y. B.Sc. (IT)  CJ

and resize them manually using the setLocation( ), setSize( ), setPreferredSize( ), or


setBounds( ) methods defined by Component.

5. Window : The Window class creates a top-level window. A top-level window is not
contained within any other object; it sits directly on the desktop. Generally, we won’t
create Window objects directly. Instead, we use a subclass of Window called Frame.

6. Frame : Frame encapsulates what is commonly thought of as a “window.” It is a subclass


of Window and has a title bar, menu bar, borders, and resizing corners. The precise look
of a Frame will differ among environments.

7. Canvas : Although it is not part of the hierarchy for applet or frame windows, there is
one other type of window that you will find valuable: Canvas. Derived from Component,
Canvas encapsulates a blank window upon which you can draw.

Q.5(c) What is a layout manager? Explain any two layouts. [5]


Ans.: The layout manager are used to arrange components in a particular manner. Layout Manager
is an interface that is implemented by all the classes of Layout managers.
Different layout managers :
 Flow Layout  Border Layout
 Grid Layout  Card Layout

 Flow Layout : It is used to arrange the components in a line one after another. It is
the default layout of applet or panel.
Constructions :
1. FlowLayout( )
2. FlowLayout(int align)
3. FlowLayout(int align, line hgap, int vgap)

Example : import java.awt.*;


public class flowDemo Extends Frame
{
Button b1, b2;
public FlowDemo( )
{
setLayout (new FlowLayout( ));
b1 =new Button (“OK”);
b2 = new Button (“Cancel);
add (b1);
add (b2);
setSize (400,400);
setVisible(true);
}
Public static void main(string args[ ])
{
new Flow Demo( );
}
}

 BorderLayout : It is used to arrange the components in five regions : north, south,


east, west and center.
Constructor :
1. BorderLayout( )
2. BorderLayout(int hgap, int vgap)

- 18 -
Prelim Question Paper Solution

Example: import java.awt.*;


public class BLDemo ( )
{
Button b1, b2, b3, b4, b5,;
public BLDemo ( )
{
SetLayout (new BorderLayout ( ));
b1 = new Button (“North”);
b2 = new Button (“SOUTH”);
b3 = new Button (“EAST”);
b4 = new Button (“WEST”);
b5 = new Button (“CENTER”);
add(b1, BorderLayout,NORTH);
add(b2, BorderLayout,SOUTH);
add(b3, BorderLayout,EAST);
add(b4, BorderLayout,WEST);
add(b5, BorderLayout,CENTER);
setSize (400,400);
setVisible(true);
}
Public static void main(string args[])
{
New BLDemo( ) ;
}
}

Flow Layout : Border Layout :

North
Ok Cancel
West
East

Center

South

Q.5(d) Develop a frame that has three radio buttons Red, Green, Blue. On Click of any [5]
one of them background color of the frame should change accordingly.
Ans.: package buttondemo;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame implements ActionListener
{
Button b1,b2,b3;
public ButtonDemo()
{
setLayout(new FlowLayout());
b1= new Button("Red");
b2= new Button("Green");
b3= new Button("Blue");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);add(b2);add(b3);
setSize(300,300);
setVisible(true);

- 19 -
Vidyalankar : S.Y. B.Sc. (IT)  CJ

}
public static void main(String[] args)
{
new ButtonDemo();
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==b1)
setBackground(Color.RED);
else if (e.getSource()==b2)
{
setBackground(Color.GREEN);
}
else
{
setBackground(Color.BLUE);
}
}
}

Q.5(e) Briefly explain: delegation model, event, event listeners, and event sources. [5]
Ans.:  Delegation Model : The modern approach to handling events is based on the delegation
event. Model, which defines standard and consistent mechanisms to generate and
process events.
Its concept is simple. A source generates an event and sends it to one or more
Listeners. In this scheme, the Listeners simply waits until it receives an event. Once an
event is received the listener processes the event and then returns.
In the delegation event model, Listeners must register with a source in order to receive
an event notification.

 Events : In event is an object that describes a state change in a source. Events may
also occurs. That are not directly caused by interactions, with a user interface.
Example, Pressing a button

 Event Listeners : A Listener is an object that is notified when an event occurs. It has
2 major requirements. First, it must have been registered with one or more sources to
receive notifications about specific type of events. Second it must implement methods
to receive and process these notifications.
x : MouseMotion Listener

 Event Sources : A source is an object that generates an event. This occurs when the
internal state of that object changes in some way.
Sources may generate more than one type of event. A source must register Listeners in
order for listeners to receive notifications about a specific type of events.
Example : addkeyListener( ), addMouseMotionLister( )

Q.5(f) Explain MouseEvent class in detail. [5]


Ans.: 1. There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
 MOUSE_CLICKED : The user clicked the mouse.
 MOUSE_DRAGGED : The user dragged the mouse.
 MOUSE_ENTERED : The mouse entered a component.
 MOUSE_EXITED : The mouse exited from a component.

- 20 -
Prelim Question Paper Solution

 MOUSE_MOVED : The mouse moved.


 MOUSE_PRESSED : The mouse was pressed.
 MOUSE_RELEASED : The mouse was released.
 MOUSE_WHEEL : The mouse wheel was moved.

2. MouseEvent is a subclass of InputEvent. Here is one of its constructors:


MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks,
boolean triggersPopup)

Here:
 src is a reference to the component that generated the event.
 The type of the event is specified by type.
 The system time at which the mouse event occurred is passed in when.
 The modifiers argument indicates which modifiers were pressed when a mouse event
occurred. The coordinates of the mouse are passed in x and y.
 The click count is passed in clicks.
 The triggersPopup flag indicates if this event causes a pop-up menu to appear on
this platform.

3. Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their
forms are shown here:
int getX( ) int getY( )

4. Alternatively, you can use the getPoint( ) method to obtain the coordinates of the
mouse. It is shown here:
Point getPoint( )

It returns a Point object that contains the X,Y coordinates in its integer members: x
and y. The translatePoint( ) method changes the location of the event. Its form is shown
here:
void translatePoint(int x, int y)

Here, the arguments x and y are added to the coordinates of the event.

5. The getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here: int getClickCount( )



- 21 -

S-ar putea să vă placă și