Java - QB

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

UNIT 1

Question - 1
The below array program finds the average of a set of numbers.

1. class Average {
2. public static void main(String args[]) {
3. double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
4. double result = 0;
5. int i;
6. for(___________________)
7. result = _____________
8. System.out.println("Average is " + _________________);
9. ______________
10. }
(i) Complete the Missing line of the above array code

(ii) Identify the default initial value of numeric elements in an array of type int in java

In Java, the default initial value of numeric elements in an array of type int is 0.
(iii) Predict the output of the above code

The output of the above code will be:

Average is 12.1

This is because the code calculates the average of the array elements {10.1, 11.2, 12.3,
13.4, 14.5}, which is (10.1 + 11.2 + 12.3 + 13.4 + 14.5) / 5 = 12.1.

Question - 2
_____myNum = 9;
________myFloatNum = 8.99f;
______myLetter = ‘A’;
_____myBool = false;
___________myText = “Hello World”;

ANSWER:

int myNum = 9;

float myFloatNum = 8.99f;

char myLetter = ‘A’;

boolean myBool = false;

String myText = “Hello World”;

Question - 3
Here is a program that uses an if-else-if ladder to determine which season a particular month is
in.
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}

Here is the output produced by the program:


April is in the Spring

(i) Modify the above program using switch case to display the same output mentioned in the scenario.

Here is the modified program using a switch statement:


(ii) Predicting what happens if there is no else block after an IF statement

ANSWER: If there is no else block after an if statement, the program will simply skip
the if block and continue executing the rest of the code. In this specific program, if the
month variable does not match any of the conditions, the season variable will not be

assigned a value, and the program will print a null value when trying to print the
season.

(iii) Which control statement runs faster?


ANSWER: When selecting among a large group of values, a switch statement is
generally faster than an if-else-if ladder. This is because a switch statement uses a
jump table to directly jump to the corresponding case, whereas an if-else-if ladder
requires sequential evaluation of each condition.

In the switch statement, the compiler creates a jump table that maps each possible
value of the month variable to the corresponding case label. When the program
executes the switch statement, it simply looks up the value of month in the jump table
and jumps to the corresponding case. This is a constant-time operation, regardless of
the number of cases.

In contrast, an if-else-if ladder requires the program to evaluate each condition


sequentially, which can take longer as the number of conditions increases. This is
because each condition must be evaluated in sequence, and the program must skip
over the intervening code until it finds a matching condition.

Therefore, when selecting among a large group of values, a switch statement is


generally faster and more efficient than an if-else-if ladder.

Question - 4
Suppose if you want to find the largest among three numbers i.e a=78,b=25,c=87
identify the expression using the ternary operator in a single statement (4),
Here is the expression using the ternary operator to find the largest among three
numbers in a single statement:
This expression uses nested ternary operators to compare the values of a, b, and c and
assigns the largest value to the largest variable.

Here's a breakdown of how it works:


1. (a > b) is evaluated first. If a is greater than b, then:
● (a > c)? a : c is evaluated. If a is greater than c, then a is assigned to
largest. Otherwise, c is assigned to largest.
2. If a is not greater than b, then:
● (b > c)? b : c is evaluated. If b is greater than c, then b is assigned to
largest. Otherwise, c is assigned to largest.

This expression is a concise way to find the largest among three numbers using the
ternary operator.

UNIT II
Question - 1

Let's consider a scenario as shown in figure-1, Father as parent class and Son as child class.
Son acquires the properties like color, a character from Father. Hence, it is called inheritance.

(i) Reorder the below code into an sequential executable manner

Reordering the Code:


(ii) Predict the happenings, if a class implements two interfaces with default methods of the same
name.

Default Methods and Conflicts:


If a class implements two interfaces with default methods of the same name, the following
happens:
● Compilation Error: You'll get a compilation error if the default method signatures (name,
parameters) are identical. The compiler doesn't know which default method to use.
● Resolution: To resolve this, you have three options:
1. Provide a Specific Implementation: In your class, implement the method with the
same name and signature, overriding the default methods from both interfaces.
2. Explicitly Call a Default Method: In your class's method, explicitly call the default
method you want using the interface name (e.g.,
InterfaceName.defaultMethodName();).
3. Inheritance: If one of the interfaces inherits from another, the inherited interface's
default method will be overridden by the inheriting interface's default method.
(iii) Identify from the following options, which of the following is used to access a static method of
an interface?
The correct answer is:
a) Using the interface name - Using the interface name: InterfaceName.staticMethodName();
You access a static method of an interface by using the interface name, followed by the method
name. For example:

Question - 2
fill the missing part of the single inheritance code
import java.lang.*;
class Father { // Base class
void work() {
System.out.println(“working…”);
}
}
class Son extends Father { // Derived class
void play() {
System.out.println(“playing…”);
}
}
class Inheritance {
public static void main(String args[]) {
Son s = new Son();
s.play(); // inherited from derived class
s.work(); // inherited from base class
}
}

Question - 3
Consider the code of Multilevel inheritance
import java.lang.*;
class Grandfather
void sleep() {
System.out.println("sleeping...");
}
}
class Father extends Grandfather
void work[ ] {
System.out.println(working);
}
}
class Son extends Son
void play() {
System.out.println("playing");
}
}
class Inheritance{
public static void main(String args[]) {
Son s = enum Son();
s.sleep(); // inherited from base class
s.work(); // inherited from derived class 1
s.work // inherited from derived class 2
}
}

(i) Spot the error in the given multilevel code snippet


There are several errors in the code:
1. In the Grandfather class, the method sleep() is not enclosed in a class body.
2. In the Father class, the method work[] is declared with square brackets [], which is not
valid. It should be void work().
3. In the Son class, it extends Son itself, which is not possible. It should extend Father.
4. In the main() method, enum Son() is not a valid way to create an instance of the Son
class. It should be Son s = new Son();.
5. In the main() method, s.work is missing parentheses to call the method. It should be
s.work();.

(ii) Find the base class and derived classes from the above code
Base class: Grandfather Derived classes: Father (derived from Grandfather), Son (derived from
Father)
(iii) Based on the scenario, Sketch the representation of multilevel inheritance

Here is the corrected code and a diagram representing the multilevel inheritance:

In this diagram, Grandfather is the base class, Father is the derived class 1, and Son is the
derived class 2. The inheritance relationship is shown by the arrows, where each derived class
inherits from its parent class.

UNIT-III
Question - 1
Java brings various Streams with its I/O package as shown in Figure-1 that helps the user to
perform all the input-output operations. These streams support all the types of objects,
data-types, characters, files etc to fully execute the I/O operations.

(ii) In java, assess how you can check if a file or directory exists using the ‘file’ class?

The File class in Java provides a method called exists() to check if a file or directory
exists. You can use it like this:

(iii) State true or false and justify.


Both InputStream and OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes.
True.
Both InputStream and OutputStream classes are abstract classes in Java. They serve as the
base classes for all input and output stream classes, respectively.
Here's why they are abstract:
● Abstraction: They define a common interface for handling data streams but leave the
actual implementation to concrete subclasses.
● No Direct Instantiation: Abstract classes cannot be directly instantiated. You need to use
their concrete subclasses, like FileInputStream, FileOutputStream, BufferedInputStream,
etc., to perform actual input or output operations.

It's important to note that OutputStream is not the superclass of all classes representing an
output stream of bytes. Instead, it is the superclass of all byte-oriented output streams. There
are other types of output streams, like Writer, which handles character-oriented data.

Question - 2
Say true or false: Scanner class is used to read text from the console in Java (2m)
True
The Scanner class in Java is used to read text from various sources, including the console, files,
and strings. It provides a way to break the input into tokens, such as integers, strings, and other
types, using regular expressions.

You can use the Scanner class to read text from the console by creating a Scanner object and
passing System.in as an argument,

Question - 3

Consider the code of CharArrayReader


import java.io.*;
public class CharArrayReaderDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length[]
char c[] = new char[width];
exp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 5);
int i:
System.out.println("input1 is:");
while((i = input1.read()) != -1) {
System.out.print((char)i);
}
System.out.println();
System.out.println("input2 is:")
while((i = input2.read()) != -1) {
System.out.print((char)i);
}
System.out.println();
}
]
(ii) Find the output of the rectified code question (i)

The output of the rectified code is:

(iii) State True or False and justify.


CharArrayReader(char array[ ], int start, int numChars) constructor creates a Reader from a
subset of your character array that begins with the character at the index specified by start and is
numChars long.
True
JUSTIFICATION: The CharArrayReader(char array[], int start, int

numChars) constructor creates a Reader from a subset of the character array that begins with

the character at the index specified by start and is numChars long. This means that the

CharArrayReader will read numChars characters from the array starting from the start

index. In the code, input2 is created with start = 0 and numChars = 5, so it will read the
first 5 characters of the array, which are "abcde".

(i) Spot the errors in the above code and rectify it

There are three errors in the code:

1) int length = tmp.length[]; should be int length = tmp.length; (remove the square brackets)
2) char c[] = new char[width]; should be char c[] = new char[length]; (replace width with length)
3) exp.getChars(0, length, c, 0); should be tmp.getChars(0, length, c, 0); (replace exp with tmp

RECTIFIED CODE:

Question - 4

Is it necessary to implement a Serializable interface if you want to serialize any object?


It is not necessary to implement the Serializable interface to serialize an object in Java. The
Serializable interface is a marker interface that indicates that a class can be serialized, but it
does not provide any implementation for serialization.

In Java, any object can be serialized as long as it implements the Serializable interface or its
superclass implements it. If a class does not implement Serializable, it will throw a
NotSerializableException when you try to serialize it.

However, if you want to customize the serialization process, you can implement the Serializable
interface and provide your own implementation of the writeObject() and readObject() methods.

So, while implementing the Serializable interface is not strictly necessary, it is required for an
object to be serializable, and it provides a way to customize the serialization process.

UNIT-IV
Question - 1

Consider the program.

public class Main{byte b=5; short s=10; int i=20; long l=30; float f=50.0F; double d=60.0D; char
c='f'; boolean b2=true; }

(i) Convert the above primitives into objects using auto-boxing wrapper class.
Here is the conversion of the primitives into objects using auto-boxing wrapper classes:
Question - 2

class Main {
public static void main(String[] args) {

// create first string


String first = Java :
System.out.println("First String: " - first);

// create second
String second = "Programming";
System.out.println("Second String: " - second);

// join two strings


String joinedString = first concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Output
First String: Java
Second String: Programming
Joined String: Java Programming

(i) Spot the error in the above program

There are several errors in the above program:

1) The string initialization for first is incorrect. It should be String first = "Java"; instead of
String first = Java ;.
2) The System.out.println statements are using the subtraction operator - instead of the
concatenation operator + to concatenate the string literals with the variables. It should be
System.out.println("First String: " + first); and System.out.println("Second String: " +
second);.
3) The concat method is not a valid method for concatenating strings in Java. Instead, you
can use the + operator or the concat method of the String class. It should be String
joinedString = first + second; or String joinedString = first.concat(second);.

CORRECTED PROGRAM:
Question - 3

The below program shows toUpperCase() and toLowerCase()


class ChangeCase {
public static void main(String args[])
{

}
}
The output produced by the program is
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.

(i) Fill the block of the above code to get the output given in the above scenario

(ii) Identify the methods that can be used to find the length and capacity of the string
In Java, you can use the following methods to find the length and capacity of a string:
● Length: length() method is used to find the length of a string. It returns the number of
characters in the string.

● Capacity: There is no direct method to find the capacity of a string in Java. The String
class in Java does not have a fixed capacity; it can grow dynamically as you add
characters to it. However, if you're referring to the capacity of a StringBuilder or
StringBuffer, you can use the capacity() method.

Question - 4

Consider the program.

public class Main{


public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c=‘a’;
boolean b2=true;
}

(i) Convert the above primitives into objects using auto-boxing wrapper class.

Here is the converted code using auto-boxing wrapper classes:


In this code, we've used the corresponding wrapper classes for each primitive type:
● byte -> Byte
● short -> Short
● int -> Integer
● long -> Long (note the L suffix for long literals)
● float -> Float (note the F suffix for float literals)
● double -> Double (note the D suffix for double literals)
● char -> Character
● boolean -> Boolean
UNIT-V
Question - 1

Consider the following figure-1 of applet

Fig-1-Applet
(i) Identify the missing parts of applet lifecycle from figure-1
(ii) Identify the valid declaration of an applet from the following
1. public class MyApplet extends java.applet.Applet {
2. public Applet MyApplet {
3. public class MyApplet extends applet implements Runnable {
4. abstract class MyApplet extends java.applet.Applet {
ANSWER:
1. public class MyApplet extends java.applet.Applet {

This declaration correctly defines a class named MyApplet that extends java.applet.Applet,
indicating that MyApplet is an applet class.

(iii) Identify the method that will be invoked when an applet window is closed
ANSWER:
The method that will be invoked when an applet window is closed is destroy(). In Java applets,
the destroy() method is called when the applet's window is closed or when the browser
tab/window containing the applet is closed. This method can be overridden in the applet's class
to perform any necessary cleanup or resource releasing operations before the applet is
terminated.

(iv) If you want to assign a value of 88 to the variable year, then which of the following lines can be used
within the <applet> tag.
1. number =getParameter(88)
2. <number=99>
3. <Param=radius value=88>
4. <Param name = number value =88>

ANSWER:
4.<Param name = number value =88>

This line uses the <Param> tag with the name attribute set to "year" and the value attribute set
to "88", which means it will pass the value 88 to the variable year when the applet is initialized.

Question - 2

When an applet is terminated, which of the following sequence of methods calls take place?

a. stop(),paint(),destroy()

b. destroy(),stop(),paint()

c. destroy(),stop()

d. stop(),destroy()

ANSWER: c. destroy(),stop()
Question - 3

The following figure -2 depicts the Java Database Connection (JDBC)

Fig:2 -Java Database Connection (JDBC)


(i) Arrange the given steps in the correct order to create a database connection
1. Process the resultset
2. Close the resultset
3. Load and register the JDBC driver
4. Import JDBC package
5. Open a connection to the database
6. Execute the statement object and return a query resultset
7. Close the connection
8. Create a statement object to perform a query

Flow : 4->3->5->8->6->1->2->7

State true or false and justify


JDBC type 2 drivers connect the native API of the DBMS

ANSWER:

False.

Justification: JDBC Type 2 drivers do not directly connect to the native API of the DBMS
(Database Management System). Instead, they use a native API client library provided by the
DBMS vendor to connect to the database. These drivers convert JDBC calls into calls specific
to the DBMS's native protocol, allowing Java applications to interact with the database using
JDBC. Therefore, while Type 2 drivers do interact with the native API through the native client
library, they do not directly connect to it.
Write the JDBC code to insert the values in the database.

ANSWER:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertData {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, username, password)) {


String sql = "INSERT INTO my_table (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);

// Set values for the parameters in the prepared statement


statement.setString(1, "value1");
statement.setInt(2, 123);
statement.setDouble(3, 45.67);

// Execute the statement to insert the data


int rowsAffected = statement.executeUpdate();
System.out.println(rowsAffected + " row(s) inserted successfully.");
} catch (SQLException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Question - 4

What is the Message is displayed in the applet made by the following Java program?

import java.awt.*;

import java.applet.*;

public class myapplet extends Applet{

public void paint(Graphics g){

g.drawString("A Simple Applet, 20, 20);

}}

a Simple Applet

b. A Simple Applet 20 20
c. Compilation Error

d. Runtime Error

ANSWER:

c) Compilation Error

You might also like