Jpr 22412 Sample Test Paper 70 Marks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Sample Test Paper 70 Marks

22412 Java Programming

Q.1) Attempt any FIVE of the following. 10 Marks


a) Give syntax and example of following math functions.
i) sqrt ()
ii) pow ()

Answer:
i) sqrt () - The java.lang.Math.sqrt() returns the square root of a value of type double
passed to it as argument.
Syntax: public static double sqrt(double a); Output will be: 15
e.g. System.out.println(Math.sqrt(225));
ii) pow () - The java.lang.Math.pow() is used to calculate a number raise to the power of
some other number. This function accepts two parameters and returns the value of first
parameter raised to the second parameter.
Syntax: public static double pow(double a, double b)
e.g. System.out.println(Math.pow(5, 3)); Output will be: 125

b) Enlist access specifiers in Java.

1. Default – No keyword required


2. Private
3. Protected
4. Public
5. Private-protected

c) Name the methods from wrapper class for following task


i) To convert string objects to primitive int.
ii) To convert integer object to string object.

1. Integer.parseInt()
Example to convert a String “10” to primitive int.
String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
Output: 10

2. Integer.valueOf()
Alternatively, you can use Integer.valueOf(), it will returns an Integer object.
String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
Output : 10

ii) To convert integer object to string object.


public static String toString()
e.g.
int d = 1234;
Integer obj = new Integer(d);
String str = obj.toString();

d) State the use of static keyword

The static keyword in Java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than an instance of the class.

static variable- If you declare any variable as static, it is known as a static variable.

o It is used to refer to the common property of all objects.


o The static variable gets memory only once in the class area at the time of class loading.

static method- If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o It can be invoked without an object/instance of a class.
o It can access static data member and can change the value of it.

e) Enlist any 4 keywords used for exception handling in Java.


1. try
2. catch
3. throw
4. throws
5. finally

f) Give syntax of <param> tag to pass parameters to an Applet.


Syntax:
< PARAM NAME = appletParameter1 VALUE = value >

The <param> tag contains two attributes: name and value which are used to specify the name of
the parameter and the value of the parameter respectively.

<PARAM> tags are the only way to specify applet-specific parameters. It is used to pass
parameters to the applet. Applets read user-specified values for parameters with
the getParameter() method.

g) Give any two methods from File class with their usage.
1. boolean mkdir() : Creates the directory named by this abstract pathname.
2. boolean renameTo(File dest) : Renames the file denoted by this abstract pathname.
3. long length() : Returns the length of the file denoted by this abstract pathname.
4. boolean delete() : Deletes the file or directory denoted by this abstract pathname.
5. boolean exists() : Tests whether the file or directory denoted by this abstract pathname
exists.

Q.2) Attempt any THREE of the following. 12 Marks


a) Write a program to find largest between two numbers using ‘?:’ operator.
class largest
{
public static void main(String args[])
{
int n1 = 5, n2 = 10, max;

max = (n1 > n2) ? n1 : n2;

System.out.println("Largest number between " + n1 +


" and " + n2 + " is " + max + ". " );
}
}

Output:
Largest number between 5 and 10 is 10.
b) Define class Student with suitable data members create two objects using two different
constructors of the class.

class Student{
int id;
String name;
int age;
//creating two arg constructor
Student(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:

111 Karan 0
222 Aryan 25

c) Describe life cycle of thread with suitable diagram.


A thread is always in one of these 5 states.
1. Newborn state: When a thread object is created it is said to be in a new born state. When the
thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to runnable state.
2. Runnable State: It means that thread is ready for execution and is waiting for the availability
of the processor i.e. the thread has joined the queue and is waiting for execution. If all threads
have equal priority then they are given time slots for execution in round robin fashion. The thread
that relinquishes control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
3. Running State: It means that the processor has given its time to the thread for execution. The
thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.
4. Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
Suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
Wait(): If a thread requires to wait until some event occurs, it can be done using wait method and
can be scheduled to run again by notify().
Sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time is
in milliseconds. It re-enters the runnable state as soon as period has elapsed /over
5. Dead State: Whenever we want to stop a thread form running further we can call its stop().
The statement causes the thread to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop method may be used when the
premature death is required.

d) Write a program to copy content of one file into another file.

import java.io.*;
public class CopyFile
{

public static void main(String args[]) throws IOException


{
FileReader in = null;
FileWriter out= null;
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
in.close();
out.close();

}
}
}

Q.3) Attempt any THREE of the following. 12 Marks


a) Write a program to divide any positive even integer by 2 using bitwise shift operator.
import java.io.*;
import java.util.*;
class num_div_by_2
{
public static void main (String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Positive EVEN integer");
n=sc.nextInt();
int res= n >> 1;
System.out.println("result after division by 2 using Bitwise shift operator : "+ res);
}
}

b) State need of interface with suitable examples.


Java does not support multiple inheritance. Java uses Interface to implement multiple
inheritance.

interface vehicleone{
int speed=90;
public void distance();
}

interface vehicletwo{
int distance=100;
public void speed();
}

class Vehicle implements vehicleone, vehicletwo{


public void distance(){
int distance=speed*100;
System.out.println("distance travelled is "+distance);
}
public void speed(){
int speed=distance/100;
}
}

class Multiple{
public static void main(String args[]){
System.out.println("Vehicle");
obj.distance();
obj.speed();
}
}

c) Give usage of following methods :


i) drawOval()
ii) getFont()
iii) drawArc()
iv) getFamily()

(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 height to draw a circle or filled circle,
specify the same width and height the following program draws several ellipses and circle.
Example: g.drawOval(10,10,50,50);

(ii) getFont()
The getFont() method gets the font specified by the system property name. If name is not a valid
system property, null is returned.
Syntax: public static Font getFont (String name)
e.g. Font f=g.getFont();

(iii)drawArc( )
It is used to draw arc .
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle is starting angle of
arc sweep_angle is degree around the arc
Example: g.drawArc(10, 10, 30, 40, 40, 90);

iv) getFamily()
Returns the font family, as string, for which the font belongs.
Syntax: public String getFamily()
Font f1 = new Font("SansSerif", Font.ITALIC, 18);
String n= f1.getFamily();

d) Enlist types of stream classes and describe methods for reading and writing data for each
type.

Java defines two types of streams. They are,


1. Byte Stream: It provides a convenient means for handling input and output of byte.
2. Character Stream: It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes are in divided in two groups -


 InputStream Classes - These classes are subclasses of an abstract class, InputStream and they
are used to read bytes from a source(file, memory or console).
 OutputStream Classes - These classes are subclasses of an abstract class, OutputStream and
they are used to write bytes to a destination(file, memory or console).
 These methods are inherited by InputStream subclasses.
Methods Description
This method returns the number of bytes that can be read
int available()
from the input stream.
abstract int read() This method reads the next byte out of the input stream.
This method reads a chunk of bytes from the input stream and
int read(byte[] b)
store them in its byte array, b.
This method closes this output stream and also frees any
close()
resources connected with this output stream.

 These methods are inherited by InputStream subclasses.


Methods Description
This method flushes the output steam by forcing out buffered
flush()
bytes to be written out.
This method writes byte(contained in an int) to the output
abstract write(int c)
stream.
write(byte[] b) This method writes a whole byte array(b) to the output.
This method closes this output stream and also frees any
close()
resources connected with this output stream.

There are two kinds of Character Stream classes - Reader classes and Writer classes.

 Reader Classes - These classes are subclasses of an abstract class, Reader and they are used to
read characters from a source(file, memory or console).
 Writer Classes - These classes are subclasses of an abstract class, Writer and they used to write
characters to a destination(file, memory or console)

 These methods are of Reader class.
Methods Description
int read() This method reads a characters from the input stream.
int read(char[] This method reads a chunk of characters from the input stream and store them
ch) in its char array, ch.
This method closes this output stream and also frees any system resources
close()
connected with it.

These methods are of Writer class.


Methods Description
This method flushes the output steam by forcing out buffered
abstract void flush()
bytes to be written out.
This method writes a characters(contained in an int) to the
void write(int c)
output stream.
This method writes a whole char array(arr) to the output
void write(char[] arr)
stream.
This method closes this output stream and also frees any
abstract void close()
resources connected with this output stream.

Q.4) Attempt any THREE of the following. 12 Marks


a) Describe types of variables in Java with their scope.
Local Variables
 Local variables are declared in methods, constructors, or blocks.

 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.

 Access modifiers cannot be used for local variables.

 Local variables are visible only within the declared method, constructor, or block.

Instance Variables
 Instance variables are declared in a class, but outside a method, constructor or any block.

 When a space is allocated for an object in, a slot for each instance variable value is
created.

 Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.

 The instance variables are visible for all methods, constructors and block in the class.

 Instance variables can be accessed directly by calling the variable name inside the class.
Class/Static Variables
 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.

 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.

 Static variables are created when the program starts and destroyed when the program
stops.

 Static variables can be accessed by calling with the class name ClassName.VariableName.

b) Write a program to initialize object of a class student using parameterized constructor.

class Student{
int id;
String name;
int age;
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student s1 = new Student(222,"Aryan",25);
s1.display();
}
}

Output:

222 Aryan 25

c) Write a program to create package Math_s having two classes as addition and subtraction.
Use suitable methods in each class to perform basic operations.
package Mypack;
public class addition
{
public void add(int a, int b)
{
System.out.println("Addition is: "+(a+b));

}
}
package Mypack;
public class subtraction
{
public void subtract(int a, int b)
{
System.out.println("Subtraction is: "+(a-b));

}
}

import java.util.*;
import Mypack.*;
public class basic_operations
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter two integer numbers");
int a=sc.nextInt();
int b=sc.nextInt();
addition a1=new addition();
a1.add(a,b);
subtraction s1= new subtraction();
s1.subtract(a,b);
}
}
d) Differentiate between Java Application and Java Applet (any 4 points)
BASIS FOR APPLET APPLICATION
COMPARISON
Basic It is small program uses An application is the programs
another application program executed on the computer
for its execution. independently.
main() method Do not use the main method Uses the main method for execution
Execution Cannot run independently Can run alone but require JRE.
require API's (Ex. Web API).
Installation Prior installation is not needed Requires prior explicit installation on
the local computer.
Read and write The files cannot be read and Applications are capable of
operation write on the local computer performing those operations to the
through applet. files on the local computer.
Communication with Cannot communicate with Communication with other servers is
other servers other servers. probably possible.
Restrictions Applets cannot access files Can access any data or file available
residing on the local computer. on the system.
Security Requires security for the No security concerns are there.
system as they are untrusted.

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

import java.util.*;
import java.io.*;

public class wordcount


{
public static void main(String[] args) throws IOException
{
File file = new File("ABC.txt");
FileInputStream fin = new FileInputStream(file);
Scanner sc=new Scanner(fin);
int count=0;
while(sc.hasNext())
{
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
}

Q.5) Attempt any TWO of the following. 12 Marks


a) Write a step to declare and define two and three dimensional arrays of a class.

Two – dimensional Array (2D-Array)

Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional
array can be seen as an array of one – dimensional array for easier understanding.
Indirect Method of Declaration:
Declaration – Syntax:
data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];

Initialization – Syntax:
array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;

Direct Method of Declaration:


Syntax:

data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};

For example: int[][] arr = {{1, 2}, {3, 4}};

Three – dimensional Array (3D-Array)

Three – dimensional array is a complex form of a multidimensional array. A three – dimensional


array can be seen as an array of two – dimensional array for easier understanding.
Indirect Method of Declaration:
Declaration – Syntax:
data_type[][][] array_name = new data_type[x][y][z];
For example: int[][][] arr = new int[10][20][30];

Initialization – Syntax:
array_name[array_index][row_index][column_index] = value;
For example: arr[0][0][0] = 1;
Direct Method of Declaration:

Syntax:

data_type[][][] array_name = {
{
{valueA1R1C1, valueA1R1C2, ....},
{valueA1R2C1, valueA1R2C2, ....}
},
{
{valueA2R1C1, valueA2R1C2, ....},
{valueA2R2C1, valueA2R2C2, ....}
}
};

For example: int[][][] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };

c) Write a program to define two threads for displaying even and odd numbers respectively
with a delay of 500 ms after each number.

import java.io.*;
import java.lang.Thread;
class Even extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
System.out.println("Even Thread i="+i);
Thread. sleep(500);
}
}
System.out.println("Exit from Even");

}
}
class Odd extends Thread
{
public void run()
{
for(int j=1;j<=10;j++)
{
if(j%2!=0)
{
System.out.println("Odd Thread j="+j);
Thread. sleep(500);
}
}
System.out.println("Exit from Odd");
}
}
class ThreadTest
{
public static void main(String args[])
{
new Even().start();
Odd ThOdd=new Odd();
ThOdd.start();

}
}
Q.6) Attempt any TWO of the following. 12 Marks
a) Write a program to define class Employee with members as id and salary. Accept data for five
employees and display details of employees getting highest salary.

import java.util.Scanner;

public class Employee {

int empid;
String name;
float salary;

public void getInput() {

Scanner in = new Scanner(System.in);


System.out.print("Enter the empid :: ");
empid = in.nextInt();
System.out.print("Enter the name :: ");
name = in.next();
System.out.print("Enter the salary :: ");
salary = in.nextFloat();
}
public void display() {

System.out.println("Employee id = " + empid);


System.out.println("Employee name = " + name);
System.out.println("Employee salary = " + salary);
}

public static void main(String[] args) {

Employee e[] = new Employee[5];

for(int i=0; i<5; i++) {

e[i] = new Employee();


e[i].getInput();
}

System.out.println("**** Data Entered as below ****");

for(int i=0; i<5; i++) {

e[i].display();
}
}
}

b) Describe types of Errors and Exceptions in details.

THERE ARE THREE TYPES OF ERRORS IN JAVA

1.Compile-time errors

2.Run time errors

COMPILE TIME ERRORS:

These errors are errors which prevents the code from compiling because of error in the syntax
such as missing a semicolon at the end of a statement or due to missing braces, class not found,
etc. These errors will be detected by java compiler and displays the error onto the screen while
compiling.

RUN TIME ERROR:

These errors are errors which occur when the program is running. Run time errors are not
detected by the java compiler. It is the JVM which detects it while the program is running.
EXCEPTIONS:

Exception is a runtime error which can be handled or prevented and occurs during the execution
of the program.

Exceptions are classified as,

Compile time exceptions

Runtime exceptions.

COMPILE TIME EXCEPTIONS:

Can be found in the compile time itself. These exceptions are also called as Checked exceptions.

Checked exceptions occur due to the mistakes done by the programmer.

Example – ClassNotFoundException occurs when the programmer has not mentioned the proper
class name in the code, same way FileNotFoundException occurs when the program is trying to
acces the file whose path is given wrong or the name of the file is mentioned wrong.

Checked exceptions must be handled by the programmer either by using try, catch or by
specifying the throws keyword (try, catch, throws are explained in the upcoming topic).

The main thing which has to be remembered is that checked exceptions needs to be handled
(checked).

The compiler forces the programmer to specify ‘throws’ keyword or to handle the exception
(using try, catch), if it is a checked exception.

RUNTIME EXCEPTIONS:

Are the exceptions which cannot be found while compiling the code and occurs during the
execution of the program.

Examples of runtime exceptions are ArithmeticException which occurs due to the divide by zero
condition, ArrayIndexOutOfBoundException which occurs due to the access of element whose
index is out of the array size declared, NullPointerException when the code is trying to access a
null value when an object value is needed in its place.

Compiler does not forces the method to handle the exception, unlike compile time exceptions.
RunTimeException is a special subclass of Exception class, which need not have to be handled
(hence called as unchecked). The reason for this is that JVM will notify the exception to the user
(what made the program to terminate).

RunTime exception occurs due to the bug present in the application code and the programmer
has to fix it.

Errors and the RunTime Exceptions are collectively called as Unchecked Exceptions.

Before deciding the exception handling mechanism, the programmer has to think whether the
client could be able to handle the exception.

Sometimes, even a novice programmer finds the exception handling mechanism a nightmare.
One has to know the best practices to be followed to implement exception handling.

You might also like