Documente Academic
Documente Profesional
Documente Cultură
IV
Core Java
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75
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
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
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++.
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 32bit 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
-4-
Prelim Question Paper Solution
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.
-5-
Vidyalankar : S.Y. B.Sc. (IT) CJ
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);
}
}
}
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
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.14rr;
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( );
}
}
-9-
Vidyalankar : S.Y. B.Sc. (IT) CJ
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.
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();
}
}
Output:
Class X method
Class Y method
Class Z method
- 11 -
Vidyalankar : S.Y. B.Sc. (IT) CJ
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.
A subclass overrides the finalize method to dispose of the system resources or to perform
other clean up.
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.
- 12 -
Prelim Question Paper Solution
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.
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);
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
- 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
InputStream : Java application uses an input stream to read data from a source; it may be
a file, an array, peripheral device or socket.
- 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 DemoClass 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.
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.
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
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.
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.
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)
- 18 -
Prelim Question Paper Solution
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( )
- 20 -
Prelim Question Paper Solution
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 -