0% found this document useful (0 votes)
7 views22 pages

UnitWise ModelAnswer

The document is a model answer sheet for a Java Programming examination from the Maharashtra State Board of Technical Education, covering various topics such as basic syntactical constructs, derived syntactical constructs, inheritance, interfaces, and packages. It includes questions and answers on Java features, command line arguments, constructors, access specifiers, types of inheritance, method overloading vs overriding, and dynamic method dispatch. The document serves as a study guide for students preparing for their Java programming exams.

Uploaded by

rajmane5457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views22 pages

UnitWise ModelAnswer

The document is a model answer sheet for a Java Programming examination from the Maharashtra State Board of Technical Education, covering various topics such as basic syntactical constructs, derived syntactical constructs, inheritance, interfaces, and packages. It includes questions and answers on Java features, command line arguments, constructors, access specifiers, types of inheritance, method overloading vs overriding, and dynamic method dispatch. The document serves as a study guide for students preparing for their Java programming exams.

Uploaded by

rajmane5457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

SUMMER – 2019 EXAMINATION – MODEL ANSWER

Subject: Java Programming Subject Code: 22412

(Questions arranged UNIT-WISE as per MSBTE I-Scheme Syllabus)

UNIT – I
Basic Syntactical Constructs in Java

Q. List any eight features of Java.

Answer:

Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic

Q. Explain the concept of platform independence and portability with respect to


Java language.

Answer:

Java is a platform independent language. This is possible because when a java program is
compiled, an intermediate code called the byte code is obtained rather than the machine
code. Byte code is a highly optimized set of instructions designed to be executed by the
JVM which is the interpreter for the byte code. Byte code is not a machine specific code.
Byte code is a universal code and can be moved anywhere to any platform. Therefore
java is portable, as it can be carried to any platform. JVM is a virtual machine which
exists inside the computer memory and is a simulated computer within a computer
which does all the functions of a computer. Only the JVM needs to be implemented for
each platform. Although the details of the JVM will defer from platform to platform, all
interpret the same byte code.

Diagram:

[Source Code] → [Java Compiler] → [Byte Code] → [JVM (Windows OS / Linux OS)]

Q. Describe instance Of and dot (.) operators in Java with suitable example.

Answer:

Instance of operator:

The java instance of operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
The instance of in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false. If we apply the instance of operator
with any variable that has null value, it returns false.
Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
[Link](sinstanceofSimple1);//true
}
}
dot (.) operator:

The dot operator, also known as separator or period used to separate a variable or
method from a reference variable. Only static variables or methods can be accessed using
class name. Code that is outside the object's class must use an object reference or
expression, followed by the dot (.) operator, followed by a simple field name.
Example
[Link]="john"; where name is a instance variable referenced by 'this' keyword
[Link](); where getdata() is a method invoked on object 'c'.

Q. Explain the command line arguments with suitable example.

Answer:

Java Command Line Argument:

The java command-line argument is an argument i.e. passed at the time of running the
java program.
The arguments passed from the console can be received in the java program and it can
be used as an input.
So, it provides a convenient way to check the behaviour of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Command Line Arguments can be used to specify configuration information while
launching your application.
There is no restriction on the number of java command line arguments.
You can specify any number of arguments
Information is passed as Strings.
They are captured into the String args of your main method
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[]){
[Link]("Your first argument is: "+args[0]);
}
}
compile by > javac [Link]
run by > java CommandLineExample sonoo
UNIT – II
Derived Syntactical Constructs in Java

Q. State use of finalize( ) method with its syntax.

Answer:

Use of finalize( ):

Sometimes an object will need to perform some action when it is destroyed. Eg. If an
object holding some non java resources such as file handle or window character font,
then before the object is garbage collected these resources should be freed. To handle
such situations java provide a mechanism called finalization. In finalization, specific
actions that are to be done when an object is garbage collected can be defined. To add
finalizer to a class define the finalize() method. The java run-time calls this method
whenever it is about to recycle an object.
Syntax:

protected void finalize() {


}

Q. Name the wrapper class methods for the following:


(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.

Answer:

(i) To convert string objects to primitive int:

String str="5";
int value = [Link](str);
(ii) To convert primitive int to string objects:

int value=5;
String str=[Link](value);

Q. Explain the types of constructors in Java with suitable example.

Answer:

Constructors are used to initialize an object as soon as it is created. Every time an object
is created using the 'new' keyword, a constructor is invoked. If no constructor is defined
in a class, java compiler creates a default constructor. Constructors are similar to
methods but with to differences, constructor has the same name as that of the class and
it does not return any value.
The types of constructors are:
1. Default constructor
2. Constructor with no arguments
3. Parameterized constructor
4. Copy constructor
1. Default constructor:

Java automatically creates default constructor if there is no default or parameterized


constructor written by user. Default constructor in Java initializes member data variable
to default values (numeric values are initialized as 0, Boolean is initialized as false and
references are initialized as null).
class test1 {
int i;
boolean b;
byte bt;
float ft;
String s;
public static void main(String args[]) {
test1 t = new test1(); // default constructor is called.
[Link](t.i);
[Link](t.s);
[Link](t.b);
[Link]([Link]);
[Link]([Link]);
}
}
2. Constructor with no arguments:

Such constructors does not have any parameters. All the objects created using this type
of constructors has the same values for its datamembers.
Eg:
class Student {
int roll_no;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
[Link]();
}
}
3. Parametrized constructor:

Such constructor consists of parameters. Such constructors can be used to create


different objects with datamembers having different values.
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r;
name=n;
}
void display() {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
[Link]();
}
}
4. Copy Constructor:

A copy constructor is a constructor that creates a new object using an existing object of
the same class and initializes each instance variable of newly created object with
corresponding instance variables of the existing object passed as argument. This
constructor takes a single argument whose type is that of the class containing the
constructor.
class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = [Link];
breadth= [Link];
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
[Link]("Area of First Rectangle : "+
([Link]*[Link]));
[Link]("Area of First Second Rectangle : "+
([Link]*[Link]));
}
}

Q. Define a class student with int id and string name as data members and a
method void SetData ( ). Accept and display the data for five students.

Answer:
import [Link].*;
class student
{
int id;
String name;
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
void SetData()
{
try
{
[Link]("enter id and name for student");
id=[Link]([Link]());
name=[Link]();
}
catch(Exception ex)
{}
}
void display()
{
[Link]("The id is " + id + " and the name is "+ name);
}
public static void main(String are[])
{
student[] arr;
arr = new student[5];
int i;
for(i=0;i<5;i++)
{
arr[i] = new student();
}
for(i=0;i<5;i++)
{
arr[i].SetData();
}
for(i=0;i<5;i++)
{
arr[i].display();
}
}
}
Q. Explain the four access specifiers in Java.

Answer:

There are 4 types of java access modifiers:


1. private 2. default 3. Protected 4. public

1) private access modifier: The private access modifier is accessible only within class.
2) default access specifier: If you don't specify any access control specifier, it is default,
i.e. it becomes implicit public and it is accessible within the program.
3) protected access specifier: The protected access specifier is accessible within package
and outside the package but through inheritance only.
4) public access specifier: The public access specifier is accessible everywhere. It has the
widest scope among all other modifiers.
UNIT – III
Inheritance, Interface and Package

Q. List the types of inheritances in Java.

Answer:

(Note: Any four types shall be considered)

Types of inheritances in Java:


i. Single level inheritance
ii. Multilevel inheritance
iii. Hierarchical inheritance
iv. Multiple inheritance
v. Hybrid inheritance

Q. Differentiate between method overloading and method overriding.

Answer:

Sr. No. Method overloading Method overriding


1 Overloading occurs when two Overriding means having two
or more methods in one class methods with the same method
have the same method name name and parameters (i.e.,
but different parameters. method signature)
2 In contrast, reference type The real object type in the run-
determines which overloaded time, not the reference
method will be used at compile variable's type, determines
time. which overridden method is
used at runtime
3 Polymorphism not applies to Polymorphism applies to
overloading overriding
4 overloading is a compile-time Overriding is a run-time
concept. concept

Q. Explain dynamic method dispatch in Java with suitable example.

Answer:

Dynamic method dispatch is the mechanism by which a call to an overridden method is


resolved at run time, rather than compile time.
• When an overridden method is called through a superclass reference, Java determines
which version (superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination is
made at run time.
• At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
• A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed. Here is an example that illustrates
dynamic method dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}

Q. Explain the concept of Dynamic method dispatch with suitable example.


(Extended)

Answer:

Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
When an overridden method is called through a superclass reference, Java determines
which version (superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination is
made at run time.
At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
If a superclass contains a method that is overridden by a subclass, then when different
types of objects are referred to through a superclass reference variable, different
versions of the method are executed. Here is an example that illustrates dynamic method
dispatch:
/ A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Explanation:
The above program creates one superclass called A and it's two subclasses B and C.
These subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are
declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
C c = new C(); // object of type C

Q. Describe the use of any methods of vector class with their syntax.

Answer:

(Note: Any method other than this but in vector class shall be considered for answer).

• boolean add(Object obj)-Appends the specified element to the end of this Vector.
• Boolean add(int index,Object obj)-Inserts the specified element at the specified
position in this Vector.
• void addElement(Object obj)-Adds the specified component to the end of this vector,
increasing its size by one.
• int capacity()-Returns the current capacity of this vector.
• void clear()-Removes all of the elements from this vector.
• Object clone()-Returns a clone of this vector.
• boolean contains(Object elem)-Tests if the specified object is a component in this
vector.
• void copyInto(Object[] anArray)-Copies the components of this vector into the
specified array.
• Object firstElement()-Returns the first component (the item at index 0) of this vector.
• Object elementAt(int index)-Returns the component at the specified index.
• int indexOf(Object elem)-Searches for the first occurence of the given argument, testing
for equality using the equals method.
• Object lastElement()-Returns the last component of the vector.
• Object insertElementAt(Object obj,int index)-Inserts the specified object as a
component in this vector at the specified index.
• Object remove(int index)-Removes the element at the specified position in this vector.
• void removeAllElements()-Removes all components from this vector and sets its size to
zero.
UNIT – IV
Exception Handling and Multithreading

Q. Write the syntax of try-catch-finally blocks.

Answer:
try{
//Statements to be monitored for any exception
} catch(ThrowableInstance1 obj) {
//Statements to execute if this type of exception occurs
} catch(ThrowableInstance2 obj2) {
//Statements
}finally{
//Statements which should be executed even if any exception happens
}

Q. Write a program to input name and salary of employee and throw user
defined exception if entered salary is negative.

Answer:
import [Link].*;
class NegativeSalaryException extends Exception
{
public NegativeSalaryException (String str)
{
super(str);
}
}
public class S1
{
public static void main(String[] args) throws IOException
{
BufferedReader br= new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter Name of employee");
String name = [Link]();
[Link]("Enter Salary of employee");
int salary = [Link]([Link]());
Try
{
if(salary<0)
throw new NegativeSalaryException("Enter Salary amount
isnegative");
[Link]("Salary is "+salary);
}
catch (NegativeSalaryException a)
{
[Link](a);
}
}
}

Q. Explain the two ways of creating threads in Java.

Answer:

Thread is a independent path of execution within a program.


There are two ways to create a thread:
1. By extending the Thread class.

Thread class provide constructors and methods to create and perform operations on a
thread. This class implements the Runnable interface. When we extend the class Thread,
we need to implement the method run(). Once we create an object, we can call the start()
of the thread class for executing the method run().
Eg:
class MyThread extends Thread {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread t = new MyThread();
[Link]();
}
}
a. By implementing the runnable interface.

Runnable interface has only on one method- run().


Eg:
class MyThread implements Runnable {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
[Link]();
}
}
Q. Write a program to create two threads. One thread will display the numbers
from 1 to 50 (ascending order) and other thread will display numbers from 50
to 1 (descending order).

Answer:
class Ascending extends Thread
{
public void run()
{
for(int i=1; i<=15;i++)
{
[Link]("Ascending Thread : " + i);
}
}
}
class Descending extends Thread
{
public void run()
{
for(int i=15; i>0;i--) {
[Link]("Descending Thread : " + i);
}
}
}
public class AscendingDescending Thread
{
public static void main(String[] args)
{
Ascending a=new Ascending();
[Link]();
Descending d=new Descending();
[Link]();
}
}
UNIT – V
Graphics and Applet

Q. Give the syntax of < param > tag to pass parameters to an applet.

Answer:

Syntax:

<param name="name" value="value">


Example:

<param name="color" value="red">

Q. Describe the use of following methods:


(i) Drawoval ( )
(ii) getFont ( )
(iii) drawRect ( )
(iv) getFamily ( )

Answer:

(i) Drawoval ( ):

Drawing Ellipses and circles: To draw an Ellipses or circles used drawOval() method can
be used. Syntax: void drawOval(int top, int left, int width, int height) The ellipse is drawn
within a bounding rectangle whose upper-left corner is specified by top and left and
whose width and height are specified by width and [Link] draw a circle or filled circle,
specify the same width and height.
Example: [Link](10,10,50,50);
(ii) getFont ( ):

It is a method of Graphics class used to get the font property


Font f = [Link]();
String fontName = [Link]();
Where g is a Graphics class object and fontName is string containing
name of the current font.
(iii) drawRect ( ):

The drawRect() method display an outlined rectangle.


Syntax: void drawRect(int top,int left,int width,int height)
The upper-left corner of the Rectangle is at top and left. The dimension of the Rectangle
is specified by width and height.
Example: [Link](10,10,60,50);
(iv) getFamily ( ):

The getfamily() method Returns the family of the font.


String family = [Link]();
Where f is an object of Font class

Q. Differentiate between Java Applet and Java Application (any four points)

Answer:

Sr. No. Java Applet Java Application


1 Applets run in web pages Applications run on standalone
systems.
2 Applets are not full featured Applications are full featured
application programs. programs.
3 Applets are the small Applications are larger
programs. programs.
4 Applet starts execution with its Application starts execution
init(). with its main ().
5 Parameters to the applet are Parameters to the application
given in the HTML file. are given at the command
prompt
6 Applet cannot access the local Application can access the local
file system and resources file system and resources.
7 Applets are event driven Applications are control driven.

Q. Describe the applet life cycle in detail.

Answer:

Below is the description of each applet life cycle method:


init():

The init() method is the first method to execute when the applet is executed. Variable
declaration and initialization operations are performed in this method.
start():

The start() method contains the actual code of the applet that should run. The start()
method executes immediately after the init() method. It also executes whenever the
applet is restored, maximized or moving from one tab to another tab in the browser.
stop():

The stop() method stops the execution of the applet. The stop() method executes when
the applet is minimized or when moving from one tab to another in the browser.
destroy():
The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed. stop() method executes just before when destroy()
method is invoked. The destroy() method removes the applet object from memory.
paint():

The paint() method is used to redraw the output on the applet display area. The paint()
method executes after the execution of start() method and whenever the applet or
browser is resized.
The method execution sequence when an applet is executed is:
• init()
• start()
• paint()
The method execution sequence when an applet is closed is:
• stop()
• destroy()
UNIT – VI
Managing Input, Output, Files in Java

Q. Define stream class. List its types.

Answer:

Definition of stream class:

An I/O Stream represents an input source or an output destination. A stream can


represent many different kinds of sources and destinations, including disk files, devices,
other programs, and memory arrays. Streams support many different kinds of data,
including simple bytes, primitive data types, localized characters, and objects. Java's
stream based I/O is built upon four abstract classes: InputStream, OutputStream, Reader,
Writer.
Types of stream classes:

i. Byte stream classes


ii. Character stream classes.

Q. Distinguish between Input stream class and output stream class.

Answer:

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The [Link] package
contains all the classes required for input and output operations. A stream is a sequence
of data. In Java, a stream is composed of bytes.
Sr. No. Input stream class Output stream class
1 Java application uses an input Java application uses an output
stream to read data from a stream to write data to a
source; destination;.
2 It may read from a file, an It may be a write to file, an
array, peripheral device or array, peripheral device or
socket socket
3 Input stream classes reads data Output stream classes writes
as bytes data as bytes
4 Super class is the abstract Super class is the abstract
inputStream class OutputStream class
5 Methods: Methods:
public int read() throws public void write(int b) throws
IOException IOException
public int available() throws public void write(byte[] b)
IOException throws IOException
public void close() throws public void flush() throws
IOException IOException
public void close() throws
IOException
6 The different subclasses of The different sub classes of
Input Stream are: File Input Output Stream class are: File
stream, Byte Array Input Output Stream, Byte Array
Stream, Filter Input Stream, Output Stream , Filter output
Piped Input Stream, Object Stream, Piped Output Stream,
Input Stream, Object Output Stream,
DataInputStream. DataOutputStream

Q. Write a program to count number of words from a text file using stream
classes.

Answer:

(Note : Any other relevant logic shall be considered)

import [Link].*;
public class FileWordCount
{
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;
try
{
while(c!=-1)
{
c=[Link]();
if(c==(char)' ')
wc++;
}
[Link]("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
[Link]();
}
}
}

Q. Write a program to copy content of one file to another file.

Answer:
class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("[Link]");
FileOutputStream out= new FileOutputStream("[Link]");
int c=0;
try
{
while(c!=-1)
{
c=[Link]();
[Link](c);
}
[Link]("File copied to [Link]......");
}
finally
{
if(in!=null)
[Link]();
if(out!=null)
[Link]();
}
}
}

You might also like