Java Paper Summer-2023
Java Paper Summer-2023
1Q(a) --03
Q: What is the Java bytecode, and what is the extension of Java bytecode file? Which software is needed
to run Java bytecode?
ANS:
• Java Bytecode:
o Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code (JAVA Program).
o This intermediate code makes Java a platform-independent language.
o Compiler converts the source code or the Java program into the Byte Code (or machine code),
and
o secondly, the Interpreter executes the byte code on the system. The Interpreter can also be
called JVM (Java Virtual Machine).
o The byte code is the common piece between the compiler (which creates it) and the Interpreter
(which runs it).
• Extension of Java bytecode file:
o The extension of a Java bytecode file is .class. After you compile a Java source file (e.g.,
MyProgram.java), the compiler generates a bytecode file (e.g., MyProgram.class).
• Software Needed to Run Java Bytecode:
o To run Java bytecode, you need the Java Virtual Machine (JVM). The JVM is part of the Java
Runtime Environment (JRE). Here are the key components involved:
▪ Java Development Kit (JDK): This includes tools needed for developing Java
applications, such as the Java compiler (javac) and the JRE. The JDK is used by
developers to compile Java source code into bytecode.
▪ Java Runtime Environment (JRE): This includes the JVM and other libraries necessary
to run Java bytecode. The JRE is what you need if you only want to run Java programs
without developing them.
1Q(b) --04
Q: Describe syntax errors (compile errors), runtime errors, and logic errors by giving suitable
examples?
ANS:
1. Syntax errors:
a. Syntax errors occur when the code does not conform to the rules of the programming language.
These errors are detected by the compiler during the compilation process.
b. Example:
c. Error Explanation:
i. Missing closing parenthesis ) in the System.out.println statement.
ii. The compiler will generate an error message indicating a syntax error.
2. Runtime errors:
a. Runtime errors occur while the program is running. These errors are typically not detected by
the compiler but cause the program to terminate abnormally during execution.
b. Example:
c. Error Explanation:
i. ArrayIndexOutOfBoundsException: The code attempts to access an index (5) that does
not exist in the array numbers.
ii. The program compiles successfully but throws a runtime exception when executed.
3. Logic errors:
a. Logic errors occur when the program compiles and runs, but the output is not what was
intended. These errors are due to mistakes in the algorithm or logic of the program.
b. Example:
c. Error Explanation:
i. The intention is to add number1 and number2, but the code mistakenly subtracts
number2 from number1.
ii. The program runs without errors, but the output (The sum is: -10) is incorrect.
1Q(c) –07
Q: Answer in brief (within 50 words):
I. Justify Java enables high performance.
II. Differentiate between while and do while loop?
III. How many times is the println statement executed?
for (int i = 0; i < 10; i++)
for (int j = 0; j < i; j++)
System.out.println(i * j);
IV. If the value of variable x is 1 then what will be returned by the
following expression: x % 2 = = 0
I. Justify Java enables high performance.
ANS: Java enables high performance through:
1. Just-In-Time (JIT) Compilation: Converts bytecode to native machine code at runtime, optimizing
frequently executed code paths.
2. Efficient Memory Management: Uses garbage collection to reclaim unused memory, reducing
memory leaks and fragmentation.
3. Adaptive Optimization: JVM dynamically optimizes code execution based on runtime behavior.
II. Differentiate between while and do while loop?
ANS:
Feature while Loop do-while Loop
Syntax while (condition) { } do { } while (condition);
First Execution Condition is checked before the loop Loop block is executed at least once
block is executed. before checking the condition.
III. How many times is the println statement executed? for (int i = 0; i < 10; i++)
for (int j = 0; j < i; j++)
System.out.println(i * j);
ANS: The println statement is executed 45 times.
Explanation:
• For i = 0, the inner loop does not run.
• For i = 1, the inner loop runs 0 times.
• For i = 2, the inner loop runs 1 time.
• For i = 3, the inner loop runs 2 times.
• ...
• For i = 10,the inner loop runs 9 times.
ANS:
• Use of this keyword: The this keyword in Java is used to refer to the current instance of the class.
• Example:
this() can be used to call another constructor in the super() is used to call a constructor in the
same class. superclass.
Q2(b)
Q: (i) Given that Thing is a class, how many objects and how many reference variables are created by
the following code?
Thing item, stuff;
item = new Thing();
Thing entity = new Thing();
ANS:
• Reference variables: In this code, the following reference variables are created:
1. item
2. stuff
3. entity
So, three reference variables are created.
• Objects: the following objects are created:
1. item = new Thing(); creates one object of type Thing.
2. Thing entity = new Thing(); creates another object of type Thing.
So, two objects are created.
(ii) Examine following code. Write and justify output.
public class MyClass
{
public static void main(String[] args) {
C c = new C();
System.out.println(c.max(12, 29));
}
}
class A {
int max(int x, int y) { if (x>y) return x; else return y; }
}
class B extends A{
int max(int x, int y) { return super.max(y, x) - 10; }
}
class C extends B {
int max(int x, int y) { return super.max(x+10, y+2); }
}
ANS:
1. C c = new C();
• An object c of class C is created.
2. System.out.println(c.max(12, 29));
• The method max in class C is called with arguments 12 and 29.
3. Method max in Class C:
• This calls super.max(22, 31), as x + 10 is 22 and y + 2 is 31.
4. Method max in Class B:
• This calls super.max(31, 22) because y is 31 and x is 22.Then, subtracts 10 from the result.
5. Method max in Class A:
• Here, max(31, 22) is called.
• Since 31 > 22, it returns 31.
6. Back to Method max in Class B:
• The result from super.max(31, 22) is 31.
• So, 31 - 10 results in 21.
7. Back to Method max in Class C:
• The result from super.max(22, 31) is 21.
8. Output:
• System.out.println(c.max(12, 29)); prints 21.
Q2(c)
Write a program that defines class named StopWatch. The class contains:
• Private data fields startTime and endTime with getter methods.
• no-arg constructor that initializes startTime with the current time.
• A method named start() that resets the startTime to the current time.
• A method named stop() that sets the endTime to the current time.
• A method named getElapsedTime() that returns the elapsed time for
the stopwatch in milliseconds.
• Declare object of StopWatch to demonstrate stop watch.
Hint: Use System.currentTimeMillis() to get current time in milliseconds.
ANS:
Q2(c)OR
Q:Create a class called Employee that includes:
I. Three instance variables— id (type String), name (type String) and
monthly_salary (double).
II. A default constructor that initializes the three instance variables.
III. A setter and a getter method for each instance variable (for example
for id variable void setId(String id), String getId( )).
IV. displayEmployee() method for displaying employee details.
Write a driver class named EmployeeTest that demonstrates class Employee’scapabilities. Create two
Employee objects and display each object’s yearly salary. Then give each Employee a 10% raise and
display each Employee’s yearly salary again.
ANS:
Q3(a)
Q: Differentiate between checked and unchecked exception?
ANS:
Checked Exception Unchecked Exception
1.Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
2.The compiler checks a checked exception. The compiler does not check these types of exceptions.
3.These types of exceptions can be handled at These types of exceptions cannot be a catch or handle at
the time of compilation. the time of compilation, because they get generated by
the mistakes in the program.
4.They are the sub-class of the exception They are runtime exceptions and hence are not a part of
class. the Exception class.
5.Here, the JVM needs the exception to catch Here, the JVM does not require the exception to catch
and handle. and handle.
Examples of Checked exceptions: Examples of Unchecked Exceptions:
• throws
o throws keyword is used in the method signature to declare an exception which might be
thrown by the function while the execution of the code.
o Example:
Q3(a) OR
Q: Describe thread life cycle with block diagram?
ANS:
Q3(b) OR
Q: Differentiate between Thread class and Runnable interface for implementing Threads?
ANS:
Thread class Runnable interface
Involves inheritance. Your class directly extends Involves composition. Your class implements
Thread. Runnable and is used by a Thread instance.
Limits your class as it cannot extend any other Allows your class to extend another class, offering
class. more design flexibility.
Less flexible if you need to use inheritance for More flexible and reusable, especially in large and
other purposes. complex applications.
Each Thread object is associated with a separate Multiple Thread objects can share the same
instance of your class. Runnable instance, making it easier to share
resources.
Q3(c) OR
Q: Write a program to make calculator that accepts input from commandline? Use java’s exception handling
mechanism to handle abnormal situation?
ANS:
Q4(a)
Q: Define Queue interface of java collection classes?
ANS:
• Queue interface:
o The Queue interface of the Java collections framework provides the functionality of the
queue data structure.
o It extends the Collection interface.
• Classes that Implement Queue
o Since the Queue is an interface, we cannot provide the direct implementation of it.
o In order to use the functionalities of Queue, we need to use classes that implement it:
▪ ArrayDeque
▪ LinkedList
▪ PriorityQueue
• OUTPUT:
Q4(b)
Q: Explain types of polymorphism?
ANS:
Compile-time
Polymorphism
Types of
polymorphism
Runtime
Polymorphism
• Runtime Polymorphism:
o Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
o Method Overridding:
▪ If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
▪ Example:
Q4(c)
Q: What are the differences between ArrayList and LinkedList? Demonstrates use of ArrayList with
example?
ANS:
ArrayList LinkedList
1. This class uses a dynamic array to store the This class uses a doubly linked list to store the
elements in it. With the introduction elements in it. Similar to the ArrayList, this class
of generics, this class supports the storage of also supports the storage of all types of objects.
all types of objects.
2. Manipulating ArrayList takes more time due Manipulating LinkedList takes less time
to the internal implementation. Whenever we compared to ArrayList because, in a doubly-
remove an element, internally, the array is linked list, there is no concept of shifting the
traversed and the memory bits are shifted. memory bits. The list is traversed and the
reference link is changed.
3. Inefficient memory utilization. Good memory utilization.
4. It can be one, two or multi-dimensional. It can either be single, double or circular
LinkedList.
5. Insertion operation is slow. Insertion operation is fast.
6. This class implements a List interface. This class implements both the List interface
Therefore, this acts as a list. and the Deque interface. Therefore, it can act as
a list and a deque.
7. This class works better when the application This class works better when the application
demands storing the data and accessing it. demands manipulation of the stored data.
8. Data access and storage is very efficient as it Data access and storage is slow in LinkedList.
stores the elements according to the indexes.
9. Deletion operation is not very efficient. Deletion operation is very efficient.
10. It is used to store only similar types of data. It is used to store any types of data.
11. Less memory is used. More memory is used.
12. This is known as static memory allocation. This is known as dynamic memory allocation.
• ArrayList example:
Q4(a) OR
o Example:
Q4(b) OR
Q: What are the differences between text I/O and binary I/O?
text I/O binary I/O
1. Text I/O handles data as a sequence of characters. 1. Binary I/O handles data as raw bytes.
2.It reads and writes data in a human-readable 2. It reads and writes data in a binary format, which
format, such as plain text. is not human-readable.
3. For text input, Java typically uses 3.For binary input, Java typically uses
BufferedReader or FileReader. BufferedInputStream or FileInputStream.
3.For text output, Java uses BufferedWriter or 4. For binary output, Java uses
FileWriter. BufferedOutputStream or FileOutputStream.
5.Text I/O involves character encoding (e.g., UTF- 5. Binary I/O does not involve character encoding.
8, ASCII). When reading, it decodes bytes into It reads and writes bytes directly.
characters, and when writing, it encodes characters
into bytes.
6. Reading and writing text files, configuration 6.Reading and writing binary files, such as images,
files, logs, and other human-readable data. videos, and serialized objects.
7.Example: Writing a string to a text file. 7. Example: Writing binary data to a file.
Q4(c) OR
Q: Describe and demonstrate Binary I/O classes of java?
ANS:
• Binary I/O classes:
o binary I/O classes are used to read and write binary data, which is data represented in bytes
rather than characters.
o This makes them suitable for handling non-text data such as images, audio files, and
serialized objects.
o Here are some of the key binary I/O classes in Java:
▪ InputStream Classes
• InputStream: The abstract superclass for all byte-oriented input streams. It
provides basic methods like read() and close().
• FileInputStream: A subclass of InputStream used for reading data from a file
in a file system.
• BufferedInputStream: A wrapper around an InputStream that buffers the input
for efficient reading.
▪ OutputStream Classes
• OutputStream: The abstract superclass for all byte-oriented output streams. It
provides basic methods like write() and close().
• FileOutputStream: A subclass of OutputStream used for writing data to a file
in a file system.
• BufferedOutputStream: A wrapper around an OutputStream that buffers the
output for efficient writing.
•
o Writing Binary Data to a File:
Q5(a)
Q: Answer in one line:
(i) Write the name of package in which all collection classes and interface are grouped.
ANS: java.util
(ii) Write the name of collection interface or abstract class which store and process object in a first-in,
first-out fashion.
ANS: Queue
(iii) Write the name of method that checks whether the collection contains the specified element.
ANS: contains()
Q5(b)
Q: List JavaFX UI controls?
ANS:
SN Control Description
1 Label Label is a component that is used to define a simple text on the screen. Typically, a
label is placed with the node, it describes.
2 Button Button is a component that controls the function of the application. Button class is
used to create a labelled button.
3 RadioButton The Radio Button is used to provide various options to the user. The user can only
choose one option among all. A radio button is either selected or deselected.
4 CheckBox Check Box is used to get the kind of information from the user which contains
various choices. User marked the checkbox either on (true) or off(false).
5 TextField Text Field is basically used to get the input from the user in the form of text.
javafx.scene.control.TextField represents TextField
6 PasswordField PasswordField is used to get the user's password. Whatever is typed in the
passwordfield is not shown on the screen to anyone.
7 HyperLink HyperLink are used to refer any of the webpage through your application.
8 Slider Slider is used to provide a pane of options to the user in a graphical form where the
user needs to move a slider over the range of values to select one of them.
9 ProgressBar Progress Bar is used to show the work progress to the user.
10 ProgressIndicator Instead of showing the analogue progress to the user, it shOws the digital progress
so that the user may know the amount of work done in percentage.
11 ScrollBar JavaFX Scroll Bar is used to provide a scroll bar to the user so that the user can scroll
down the application pages.
12 Menu JavaFX provides a Menu class to implement menus. Menu is the main component
of any application.
13 ToolTip JavaFX ToolTip is used to provide hint to the user about any component.
Q5(a)OR
Q: Enlist various Layout panes available in JavaFX?
ANS:
Class Description
BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.
FlowPane Organizes the nodes in the horizontal rows according to the available horizontal spaces. Wraps
the nodes to the next line if the horizontal space is less than the total width of the nodes
GridPane Organizes the nodes in the form of rows and columns.
HBox Organizes the nodes in a single row.
Pane It is the base class for all the layout classes.
StackPane Organizes nodes in the form of a stack i.e. one onto another
VBox Organizes nodes in a vertical column.
Q5(b)OR
Q: Discuss JavaFX benefits?
ANS:
1. Rich Set of UI Controls
o JavaFX provides a comprehensive set of UI controls, such as buttons, tables, trees, menus, and
more. These controls are highly customizable and can be styled extensively using CSS.
2. CSS Styling
o JavaFX supports CSS for styling the UI components, which allows for a separation of design and
functionality. This makes it easier to design visually appealing and consistent interfaces.
3. Modern Graphics Library
o JavaFX provides a modern graphics library with support for 2D and 3D graphics.
o It uses hardware-accelerated graphics rendering, which ensures high performance and smooth
animations.
4. Event Handling
o JavaFX provides a flexible and powerful event handling mechanism, making it straightforward to
handle user interactions like mouse clicks, key presses, and other events.
5. Cross-Platform Support
o JavaFX applications are cross-platform, meaning they can run on various operating systems like
Windows, macOS, and Linux without modification
6. Media Support
o JavaFX includes APIs for playing audio and video, which can be used to develop multimedia
applications.
7. Community and Documentation
o JavaFX has a robust community and extensive documentation, which can help developers find
resources, examples, and support for their projects.
Q5(c)OR
Q: Illustrate basic structure of JavaFX program?
ANS:
A basic JavaFX program consists of the following main components:
1. Main Application Class: This class extends javafx.application.Application and overrides the start
method.
2. Start Method: This method is the entry point for JavaFX applications. It sets up the primary stage
(window) and the scene (the content inside the window).
3. Stage: The primary window of the JavaFX application.
4. Scene: The container for all content in a JavaFX application.
5. Nodes: Elements inside the scene, like UI controls, shapes, images, etc.