Java Programming Model Answer, Exercises of Mathematics

A model answer for a java programming exam conducted by the maharashtra state board of technical education. It covers various topics in java programming, including string conversion, inheritance types, exception handling, i/o streams, and thread creation. Detailed explanations, code examples, and syntax for these concepts. It serves as a comprehensive reference for students preparing for java programming exams or assignments.

Typology: Exercises

2014/2015

Uploaded on 04/29/2022

57-samarth-hatte
57-samarth-hatte 🇮🇳

3 documents

1 / 23

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 1 / 23
22412
Important Instructions to examiners:
1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the candidate’s answers and model
answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant
answer based on candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
Q.
No
.
Sub
Q.N.
Answer
Marking
Scheme
1.
a)
Ans.
Attempt any FIVE of the following:
List any eight features of Java.
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
10
2M
Any
eight
features
2M
b)
Ans.
State use of finalize( ) method with its syntax.
Use of finalize( ):
Sometimes an object will need to perform some action when it is
2M
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Java Programming Model Answer and more Exercises Mathematics in PDF only on Docsity!

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

Important Instructions to examiners:

  1. The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
  2. The model answer and the answer written by candidate may vary but the examiner may try to assess the understanding level of the candidate.
  3. The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for subject English and Communication Skills).
  4. While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
  5. Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and there may be some difference in the candidate’s answers and model answer.
  6. In case of some questions credit may be given by judgement on part of examiner of relevant answer based on candidate’s understanding.
  7. For programming language papers, credit may be given to any other program based on equivalent concept.

Q. No .

Sub Q.N.

Answer Marking Scheme

1. a) Ans.

Attempt any FIVE of the following: List any eight features of Java. 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

2M

Any eight features 2M

b) Ans.

State use of finalize( ) method with its syntax. Use of finalize( ): Sometimes an object will need to perform some action when it is

2M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

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() { }

Use 1M

Syntax 1M

c)

Ans.

Name the wrapper class methods for the following: (i) To convert string objects to primitive int. (ii) To convert primitive int to string objects. (i) To convert string objects to primitive int: String str=”5”; int value = Integer.parseInt(str);

(ii) To convert primitive int to string objects: int value=5; String str=Integer.toString(value);

2M

1M for each method

d)

Ans.

List the types of inheritances in Java. (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

2M

Any four types ½M each

e) Ans.

Write the syntax of try-catch-finally blocks. 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{

2M

Correct syntax 2 M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

byte code.

Diagram 1M

b)

Ans.

Explain the types of constructors in Java with suitable example. (Note: Any two types shall be considered). 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
  5. 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;

4M

Explana tion of the two types of construc tors 2 M

Example 2 M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

public static void main(String args[]) { test1 t = new test1(); // default constructor is called. System.out.println(t.i); System.out.println(t.s); System.out.println(t.b); System.out.println(t.bt); System.out.println(t.ft); } }

  1. 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() { System.out.println("Roll no is: "+roll_no); System.out.println("Name is : "+name); } public static void main(String a[]) { Student s = new Student(); s.display(); } }
  2. 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;

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

System .out.println("Area of First Second Rectangle : "+ (r1.length*r1.breadth)); } } c) Ans.

Explain the two ways of creating threads in Java. 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++) { System.out.println(i); } } public static void main(String a[]) { MyThread t = new MyThread(); t.start(); } } 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++) { System.out.println(i); } } public static void main(String a[]) { MyThread m = new MyThread(); Thread t = new Thread(m); t.start(); }

4M

2M

each for explaini ng of two types with example

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

d) Ans.

Distinguish between Input stream class and output stream class. 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 java.io 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 stream to read data from a source;

Java application uses an output stream to write data to a destination;. 2 It may read from a file, an array, peripheral device or socket

It may be a write to file, an array, peripheral device or socket 3 Input stream classes reads data as bytes

Output stream classes writes data as bytes 4 Super class is the abstract inputStream class

Super class is the abstract OutputStream class 5 Methods: public int read() throws IOException public int available() throws IOException public void close() throws IOException

Methods: public void write(int b) throws IOException public void write(byte[] b) throws IOException public void flush() throws IOException public void close() throws IOException 6 The different subclasses of Input Stream are: File Input stream, Byte Array Input Stream, Filter Input Stream, Piped Input Stream, Object Input Stream, DataInputStream.

The different sub classes of Output Stream class are: File Output Stream, Byte Array Output Stream , Filter output Stream, Piped Output Stream, Object Output Stream, DataOutputStream

4M

Any four points for input stream class and output stream class 1M each

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

for(i=0;i<5;i++) { arr[i].display(); } } } b) Ans.

Explain dynamic method dispatch in Java with suitable example. 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() { System.out.println("Inside A's m1 method"); } }

class B extends A { // overriding m1() void m1()

4M

Explana tion 2M

Example 2M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

System.out.println("Inside B's m1 method"); } }

class C extends A { // overriding m1() void m1() { System.out.println("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;

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

(iv) getFamily ( ): The getfamily() method Returns the family of the font. String family = f.getFamily(); Where f is an object of Font class d)

Ans.

Write a program to count number of words from a text file using stream classes. (Note : Any other relevant logic shall be considered) import java.io.*; public class FileWordCount { public static void main(String are[]) throws IOException { File f1 = new File("input.txt"); int wc=0; FileReader fr = new FileReader (f1); int c=0; try { while(c!=-1) { c=fr.read(); if(c==(char)' ') wc++; } System.out.println("Number of words :"+(wc+1)); } finally { if(fr!=null) fr.close(); } } }

4M

Correct program 4M

a)

Ans.

Attempt any THREE of the following: Describe instance Of and dot (.) operators in Java with suitable example. 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).

4M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

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(); System.out.println(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 this.name=”john”; where name is a instance variable referenced by ‘this’ keyword c.getdata(); where getdata() is a method invoked on object ‘c’.

Descript ion and example of each operator 2 M

b) Ans.

Explain the four access specifiers in Java. 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.

4M

Each access specifier s 1M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

e) Ans.

Write a program to copy content of one file to another file. class fileCopy { public static void main(String args[]) throws IOException { FileInputStream in= new FileInputStream("input.txt"); FileOutputStream out= new FileOutputStream("output.txt"); int c=0; try { while(c!=-1) { c=in.read(); out.write(c); } System.out.println("File copied to output.txt...."); } finally { if(in!=null) in.close(); if(out!=null) out.close(); } } }

4M

Correct logic 2M

Correct Syntax 2M

a)

Ans.

Attempt any TWO of the following: Describe the use of any methods of vector class with their syntax. (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.

6M

Any 6 methods with their use 1M each

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

 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. b)

Ans.

Explain the concept of Dynamic method dispatch with suitable example. 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:

6M

Explana tion 3 M

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

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

(Autonomous) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION MODEL ANSWER

Subject: Java Programming Subject Code:

c)

Ans.

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). class Ascending extends Thread { public void run() { for(int i=1; i<=15;i++) { System.out.println("Ascending Thread : " + i); } } }

class Descending extends Thread { public void run() { for(int i=15; i>0;i--) { System.out.println("Descending Thread : " + i); } } }

public class AscendingDescending Thread { public static void main(String[] args) { Ascending a=new Ascending(); a.start(); Descending d=new Descending(); d.start(); } }

6M

Creation of two threads 4M

Creating main to create and start objects of 2 threads: 2M

a) Ans.

Attempt any TWO of the following: Explain the command line arguments with suitable example. Java Command Line Argument: The java command-line argument is an argument i.e. passed at the time of running the java program.

6M