0% found this document useful (0 votes)
3 views33 pages

Java Programming Key Paper

Uploaded by

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

Java Programming Key Paper

Uploaded by

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

CMR TECHNICAL CAMPUS

UGC AUTONOMOUS

[Link] – IV Semester, Regular End Examinations, August-2021


Java Programming [19CS405PC]
(Common to CSE & IT)

PART - A

1)
a) what is the significance of Java's byte code?
Ans: Bytecode is a dot class file(.class) which is a highly optimized set of instructions that is executed by the Java
Virtual Machine. Bytecode helps Java achieve both portability and security.

b) what is an Object? how to allocate memory for objects?


Ans: An instance of a class or an object is anything which is physically exist in the real – world. To allocate memory
to an object, we must use new operator. So the object is always allocated memory on heap.

Ex: ClassName obj=new ClassName();

c) What is nested interface in java?


An interface, i.e., declared within another interface or class, is known as a nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain.

Ex: interface A

Interface B

}
d) define serialization in java?
Serialization is a mechanism of converting the state of an object into a byte stream. A Java object is serializable
if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface,
java.

e) What is the difference between throw and throws keywords in java?


Throw Throws
throw keyword is used within the method throws keyword is used with the method signature.
Checked exception cannot be propagated using For the propagation checked exception must use
throw [Link] exception can be propagated throws keyword followed by specific exception class
using throw. name.
throw keyword is used to throw an exception throws keyword is used to declare one or more
explicitly. exceptions, separated by commas.

f) how does java support inter thread communication?


Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be [Link] is
implemented by following methods of Object class:
wait()
notify()
notifyAll()

g) what is the difference between hashtable and hashmap in java?


HashMap is non-synchronized. It is not thread-safe and can't be shared between many threads without proper
synchronization code whereas Hashtable is synchronized. ... HashMap allows one null key and multiple null
values whereas Hashtable doesn't allow any null key or value.

h) what is autoboxing and unboxing in java?


Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their
corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and
so on.

i) what is a layout in java?


Layout means the arrangement of components within the container. In other way we can say that placing the
components at a particular position within the container.
Ex: Border layout, Grid Layout, Box Layout, Flow Layout, GridBag Layout..

j) what is the container class in java and also mention its subclasses?
A Container is a subclass of Component that can contain other components, including other containers.
Container allows you to create groupings of objects on the screen.
Panel, Window, Frame, Dialog, and FileDialog, Button, CheckBox, RadioButton, Label, TextBox, TextArea.

PART – B
2. A) what is the role and responsibility of jvm in program execution?

Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code or applications. It
converts Java bytecode into machines language. JVM is a part of Java Run Environment (JRE). In other programming
languages, the compiler produces machine code for a particular system.

2. B). write a program to reverse a string in java?


import [Link].*;
import [Link].*;
import [Link].*;

// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "Hello";

// getBytes() method to convert string


// into bytes[].
byte[] strArray = [Link]();

byte[] result = new byte[[Link]];

// Store result in reverse order into the


// result byte[]
for (int i = 0; i < [Link]; i++)
result[i] = strArray[[Link] - i - 1];

[Link](new String(result));
}
}

OR
public class StringFormatter {
public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
[Link]();
return [Link]();
}
}

public class TestStringFormatter {


public static void main(String[] args) {
[Link]([Link]("Hello"));
}
}
3.A) How does java support multiple inheritance explain with an example?
When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends
class A and B then this type of inheritance is known as multiple inheritance. Java doesn't allow multiple inheritance.

To achieve this using Interface concept:

Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends
multiple interfaces.

Interface Father

Void property();

Interface Mother

Void property();

Class Child implements Father, Mother

Public void property()

[Link](“This is my property”);

Public static void main(String args[])

Child obj=new Child();

[Link]();

}
3.B) Can abstract class be declared as final? Justify your answer.
No, you cannot make an abstract class or method final in Java because the abstract and final are the mutually exclusive
concept. ... An abstract method must be overridden to be useful and called but when you make the abstract method
final it cannot be overridden in Java, hence there would be no way to use that method

4. A) What is the importance of CLASSPATH? Discuss


CLASSPATH: CLASSPATH is an environment variable which is used by Application ClassLoader to locate and load the .
class files. The CLASSPATH defines the path, to find third-party and user-defined classes that are not extensions or part
of Java platform.

Step 1:

Right click on MyComputer

Step 2:

Click on Advanced System Settings.

Step 3: A dialog box will open. Click on Environment Variables.


Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a semicolon (;) at the end.
Paste the Path of MySQL-Connector [Link] file.

If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable name as CLASSPATH
and Variable value as C:\Program Files\Java\jre1.8\lib;.;
4. B) What is an interface? Give the general form of interface and also discuss the implementation details
of interfaces.
An interface is similar to class. It is a collection of abstract methods. A class implements an interface.

Syn: interface Interface_Name

Abstract methods

Implementation of interface is two types:

1. Interface to interface
2. Interface to class
1. Interface to interface:

We can extends the interface to another interface.

Ex: interface A

Void add();

Interface B extends A
{

Void sub();

2. Interface to Class:
We can implements interface to classes.
Ex: interface A
{
Void add();
}
Class MyInterface implements A
{
Public void add()
{
[Link](“This is Addition method”);
}
}

5. A) What are I/O streams in Java?

A stream is a flow of data from one place to another place or A stream is a sequence of data.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) [Link]: standard output stream

2) [Link]: standard input stream

3) [Link]: standard error stream

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.

Java IO streams are typically either byte based or character based.


Byte Stream class:
5. B) Write a java program to accept a file name and search the mobile number based on given name.
import [Link];

import [Link]; import

[Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

public class HashTab {

public static void main(String[] args) {

HashTab prog11 = new HashTab();

Hashtable hashData = [Link]("[Link]");

[Link]("File data into Hashtable:\n" + hashData);

[Link](hashData, "raja");

[Link](hashData, "123");

[Link](hashData, "----");

private void printTheData(Hashtable hashData, String input) {

String output = null;

if (hashData != null) {

Set keys = [Link]();

if ([Link](input)) {

output = [Link](input);

else {

Iterator iterator = [Link]();

while ([Link]()) {

String key = [Link]();

String value = [Link](key);


if ([Link](input)) {

output = key; break;

}}}

[Link]("Input given:" + input);

if (output != null) {

[Link]("Data found in HashTable:" + output);

else {

[Link]("Data not found in HashTable");

private Hashtable readFromFile(String fileName) {

Hashtable hashData = new Hashtable();

try { File f = new File("D:\\java\\" + fileName);

BufferedReader br = new BufferedReader(new FileReader(f));

String line = null;

while ((line = [Link]()) != null) {

String[] details = [Link]("\t");

[Link](details[0], details[1]);

}}

catch (FileNotFoundException e) {

[Link]();

catch (IOException e) {
[Link]();

} return hashData;

6. A) What is the importance of Exception Handling in java? Define and distinguish between checked and
unchecked exceptions.
Java exception handling is important because it helps maintain the normal, desired flow of the program even when
unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail.

Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked
exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Unchecked are the exceptions that are not checked at compiled time. so it is not forced by the compiler to either handle
or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.

6. B) Explain the synchronization of multiple threads in Java with an example.

Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

There are two types of synchronization:

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.


Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three
ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when
the thread completes its task.

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

7. A) Demonstrate nested try and finally statements in exceptional handling.

Java Nested try block

In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we
enter a statement in try block, context of that exception is pushed onto the stack.

For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can
handle the ArithemeticException (division by zero).

Syntax:

//main try block


try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Ex:
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}

[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
Finally
{
[Link]("normal flow..");
}
}
}

7. B) Write the states associated with threads. Write a java program to create a thread.

Life cycle of a Thread (Thread States)

1. Life cycle of a thread


1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

A thread can be in one of the five states.


1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the
running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.

Thread class extends Object class and implements Runnable interface.

Example: 1
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Example: 2
class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
8. A) How to implement Priority Queue in Java?
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that
a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed
according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The
elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue
construction time, depending on which constructor is used.
// Java program to demonstrate the
// working of PriorityQueue
import [Link].*;

class PriorityQueueDemo {

// Main Method
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

// Adding items to the pQueue using add()


[Link](10);
[Link](20);
[Link](15);

// Printing the top element of PriorityQueue


[Link]([Link]());

// Printing the top element and removing it


// from the PriorityQueue container
[Link]([Link]());

// Printing the top element again


[Link]([Link]());
}
}

8. B) What are the legacy classes in Java?


Legacy Classes:
classes and interfaces that formed the collections framework in the older version of Java are known as Legacy classes.

All the legacy classes are synchronized. The [Link] package defines the following legacy classes:

1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector

Hashtable Class

The Hashtable class is similar to HashMap. It also contains the data into key/value pairs. It doesn't allow to enter any null key
and value because it is synchronized. Just like Vector, Hashtable also has the following four constructors.

Stack Class

Stack class extends Vector class, which follows the LIFO(LAST IN FIRST OUT) principal for its elements. The stack implementation
has only one default constructor, i.e., Stack().

Dictionary Class

The Dictionary class operates much like Map and represents the key/value storage repository. The Dictionary class is an
abstract class that stores the data into the key/value pair. We can define the dictionary as a list of key/value pairs.

Properties Class

Properties class extends Hashtable class to maintain the list of values. The list has both the key and the value of type string.

Vector Class

Vector is a special type of ArrayList that defines a dynamic array. ArrayList is not synchronized while vector is synchronized.
The vector class has several legacy methods that are not present in the collection framework. Vector implements Iterable
after the release of JDK 5 that defines the vector is fully compatible with collections, and vector elements can be iterated by
the for-each loop.

9. A) How to implement Map interface in Java?

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map
contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, LinkedHashMap, and
TreeMap. The hierarchy of Java Map is given below:

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and

LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class.


It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap.
It maintains ascending order.

Example:

// Java program to demonstrate


// the working of Map interface

import [Link].*;
class HashMapDemo {
public static void main(String args[])
{
Map<String, Integer> hm = new HashMap<String, Integer>();

[Link]("a", new Integer(100));


[Link]("b", new Integer(200));
[Link]("c", new Integer(300));
[Link]("d", new Integer(400));

// Traversing through the map


for ([Link]<String, Integer> me : [Link]()) {
[Link]([Link]() + ":");
[Link]([Link]());
}
}
}

9. B) What are the various methods used in String Tokenizer class?

The [Link] class allows you to break a string into tokens. It is simple way to break string.

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.


String nextToken() returns the next token from the
StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

10. A) Explain the event-handling mechanism in java with an example.

Changing the state of an object is known as an event. Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when
an event occurs. Java Uses the Delegation Event Model to handle the events.

Example: Java event handling by implementing ActionListener


import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);

//register listener
[Link](this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

10. B) How to pass the parameters to an Applet? Explain with an example.

Parameters are passed to applets using NAME & VALUE attributes in <PARAM> tags between the opening and closing APPLET
tags. Inside the applet. You can read the values passed through the PARAM tags with the getParameter() method of the java.

Syntax:

public String getParameter(String parameterName)


Example:
[Link]
import [Link];
import [Link];

public class UseParam extends Applet{

public void paint(Graphics g){


String str=getParameter("msg");
[Link](str,50, 50);
}

}
[Link]

<html>
<body>
<applet code="[Link]" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

11. A) Write a short note on the Following


i) JFrame ii) JTabbedPane

i) JFrame:
JFrame is a top-level container that provides a window on the screen. A frame is actually a base window
on which other components rely, namely the menu bar, panels, labels, text fields, buttons, etc. Almost
every other Swing application starts with the JFrame window.
Example:
Public class MyClass extends JFrame
{
---
}
ii) JTabbedPane:
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a
given title or icon. It inherits JComponent class.

JTabbedPane class declaration


public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants
{
-----
}

11. B) Write a program to create a frame for a simple arithmetic calculator using swing
components and layout managers?

//Simple Calculator Program:


import [Link].*;
import [Link].*;
import [Link].*;

/*
* <applet code="Calculator" width=500 height=500></applet>
* */

public class Calculator extends Applet implements ActionListener


{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(10,89,90);
setBackground(k);
t1=new TextField(50);
GridLayout gl=new GridLayout(6,3);
setLayout(gl);
for(int i=0;i<i++)
{
b[i]=new Button(""+i);
}
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("%");
clear=new Button("Clear");
EQ=new Button("=");
[Link](this);
add(t1);
for(int i=0;i<i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]();
char ch=[Link](0);

if ( [Link](ch))
[Link]([Link]()+str);
else
if([Link]("+"))
{
v1=[Link]([Link]());
OP='+';
[Link]("");
}
else if([Link]("-"))
{
v1=[Link]([Link]()); OP='-';
[Link]("");
}
else if([Link]("*"))
{
v1=[Link]([Link]());
OP='*';
[Link]("");
}
else if([Link]("/"))
{
v1=[Link]([Link]());
OP='/';
[Link]("");
}
else if([Link]("%"))
{
v1=[Link]([Link]());
OP='%';
[Link]("");
}

if([Link]("="))
{
v2=[Link]([Link]());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
[Link](""+result);
}
if([Link]("Clear"))
{
[Link]("");
}
}
}

*****

You might also like