Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Java Paper - Winter 2023

Uploaded by

PRABH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Java Paper - Winter 2023

Uploaded by

PRABH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

OOP –WINTER 2023

1Q(a) –03
Q: How java supports platform independency? What is the role of JVM in it?
ANS:
Java achieves platform independence through a combination of language features, bytecode compilation, and the
Java Virtual Machine (JVM).

1. Write Once, Run Anywhere (WORA):

• Java promotes the "Write Once, Run Anywhere" (WORA) philosophy, which means that Java code can be
written once and executed on any platform without modification.

2. Bytecode Compilation:

• When you compile a Java source file (.java), it is translated into an intermediate representation called
bytecode (.class files).
• Bytecode is a platform-independent binary representation of the source code.

3. Java Virtual Machine (JVM):

• The JVM is an abstract computing machine that provides a runtime environment for executing Java bytecode.
• It interprets the bytecode and translates it into native machine code at runtime, making it executable on any
platform that has a compatible JVM implementation.

Role of JVM in Platform Independence:

1. Bytecode Execution:

• The JVM executes Java bytecode, regardless of the underlying hardware and operating system.

• It abstracts the underlying platform-specific details and provides a consistent runtime environment
for Java applications.

2. Memory Management:

• The JVM manages memory allocation and deallocation, garbage collection, and other memory-
related tasks.

• It ensures that Java programs have consistent memory behavior across different platforms.

3. Platform-Specific Implementations:

• While the JVM itself is platform-independent, there are platform-specific implementations of the
JVM tailored for different operating systems and hardware architectures.

• These implementations ensure optimal performance and integration with the underlying platform
while maintaining Java's platform independence.

4. Execution Environment:

• The JVM provides an execution environment that shields Java programs from platform-specific
differences in hardware, OS, and system libraries.

• It abstracts away details such as memory management, threading, and I/O operations, providing a
uniform interface for Java applications.
1Q(c) –07
Q:Write a program which declare integer array of 10 elements? Initialize array and define following
methods with the specified header:
(i) public static int add(int [] array) print addition of all element of array.
(ii) public static int max(int [] array) print maximum element of array.
(ii) public static int search(int [] array, int key) search element key in array
and return index of it. If element is not found method will return -1.
ANS:
2Q(a) –03
Q: Describe the relationship between an object and its defining class?
ANS: The relationship between an object and its defining class in object-oriented programming can be described as
follows:
1. Class as a Blueprint: A class serves as a blueprint or template for creating objects. It defines the structure and
behavior of objects of that class.
2. Object as an Instance: An object is an instance of a class. When you create an object, you are creating a
specific instance of that class, with its own unique set of data values (properties) and behaviors (methods).
3. Inheritance Relationship: If one class inherits from another (subclass and superclass relationship), objects of
the subclass retain the properties and behaviors of the superclass and may also have additional attributes or
behaviors specific to the subclass.
4. Multiple Objects from One Class: Multiple objects can be created from the same class. Each object is
independent of the others, meaning changes to one object generally do not affect the others.
5. Encapsulation: Objects encapsulate both data (attributes or properties) and methods (behaviors or functions)
defined in their class. This encapsulation helps in keeping the data secure and provides a clear interface for
interacting with the object.
Overall, the relationship between a class and its objects is fundamental to object-oriented programming, enabling the
creation of modular, reusable, and maintainable code.

2Q(b) –04
Q:

There are a couple of issues in the code provided:


1. In the Circle constructor, the assignment radius = radius; is not correct. This assignment does
nothing because it assigns the parameter radius to itself, not to the instance variable this.radius.
This results in the radius property not being set properly.
2. In the B constructor, the assignment length = length; suffers from the same issue as above. It doesn't
assign the parameter length to the instance variable this.length. This also results in the length
property not being set properly.
3. In the B constructor, there is no call to the superclass constructor Circle(double radius), which is
needed because B extends Circle.
Here's the corrected code:

2Q(c) –07
Q: Design a java class Rectangle which contains following field and methods:
(i) Field: length, width: int
(ii) Default Constructor: initialize all fields with 0 value
(iii) Method: int getArea() will return area of rectangle.
ANS:
2Q(c) –07
Q: Answer in brief(within two lines):
(i) If a method defined in a subclass has the same signature as a method in its superclass with the
same return type, is the method overridden or overloaded?
ANS: Overridden.
(ii) How do you invoke an overridden superclass method from a subclass?
ANS: By using the super keyword followed by the method name and parameters.
(iii) What is the purpose of "this" keyword?
ANS: It refers to the current instance of the class and is used to access instance variables and methods.
(iv) Differentiate between following statements:
int a=3;
Integer b=new Integer(3);
ANS: int a=3; is a primitive variable declaration, while Integer b=new Integer(3); creates an Integer
object with value 3.
(v) Which java keyword is used to prevent inheritance (prevent class to be extended)?
ANS: final keyword.
(vi) Can we create reference of interface. If we can create, then what is the use of it?
ANS: Yes, we can create references of interfaces. They provide a way to achieve abstraction and define
contracts for implementing classes.
(vii) What is the difference between a String in Java and String in C/C++?
ANS:
String in Java String in C/C++
In Java, String is an object type with its own set of in C/C++, it is a character array terminated by a
methods and behaviors null character.

3Q(a) –03
Q: Discuss benefits of multithreading?
Ans:
1. Improved Performance and Responsiveness: By allowing multiple threads to execute
concurrently, applications can perform tasks in parallel, which can significantly improve
performance, especially on multi-core processors.
2. Resource Sharing: Threads within the same process share the same memory space and resources,
which makes it easier to share data and resources without the need for complex inter-process
communication mechanisms.
3. Efficient Utilization of System Resources: Multithreading can lead to better utilization of CPU
resources. While one thread is waiting (for example, for I/O operations), another thread can utilize
the CPU, leading to higher efficiency and throughput.
4. Scalability: Multithreading allows applications to scale more effectively with the increasing number
of cores in modern CPUs. Applications designed with multithreading in mind can benefit directly
from hardware advancements.
5. Concurrency and Parallelism: Multithreading enables true concurrency (where multiple tasks start,
run, and complete in overlapping time periods) and can achieve parallelism on multi-core systems,
where multiple threads actually execute simultaneously on different cores.

3Q(b) –04
Q:Develop a program which stores name of districts in Gujrat in array of String.The array specified
capacity to store 5 districts. The user will be able to print name of district based on array index e.g. (0
will print Ahemdabad). If the specified index is out of bounds, program will display the message Out
of Bounds.
ANS:
3Q(c) –07

Q: Characterize the two ways of implementing thread in Java? Illustrate each method by example?
ANS: In Java, there are two primary ways to implement threads:
1. Extending the Thread class
2. Implementing the Runnable interface
1. Extending the Thread Class
To create a thread by extending the Thread class, you need to create a new class that extends Thread and
override its run method. The run method contains the code that defines the thread's behavior.
Example:

2. Implementing the Runnable Interface


To create a thread by implementing the Runnable interface, you need to create a class that implements
Runnable and override its run method. You then pass an instance of this class to a Thread object and start the
thread.
Example:
3Q(a)OR –03
Q: Explain the use of finally. Show the type of code usually kept in finally?
ANS:
• Finally block:
o Java finally block is a block used to execute important code such as closing the connection,
etc.
o Java finally block is always executed whether an exception is handled or not.
o Therefore, it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.
o Code:

3Q(b)OR –04

Q:Distinguish unchecked exception and checked exception? Give example of each type of exception?

ANS:DONE IN SUMMER PAPER


3Q(c) OR–04

Implement java code to take some (say 10) Strings from users. Put all the input Strings in an array
(String name[]). Provide implementation of following methods:
(i)search(String s) will return index of String passed in method if String S is found in name, otherwise
return -1.
(ii)sort() will print sorted String array to user
ANS:
4Q(a) –03
Q: Write a program to find out whether the given number is palindrome or not?
ANS:

4Q(b) –04
Q: Outline the use of throw in exception handling with example.
ANS: DONE IN SUMMER PAPER

4Q(c) –07
Q: Give Definitions: static, finalize, final.
ANS: Static and final done in question bank
• finalize:
o The finalize method in Java is called by the garbage collector before an object is removed
from memory. It is intended for cleanup activities like releasing system resources.
o Example:
4Q(a)OR –03
Q: Elaborate the role of java garbage collector.
ANS: The role of java garbage collector are:
1. Automatic Memory Management:
• The garbage collector automatically manages memory allocation and deallocation, relieving
developers from manual memory management tasks.
2. Object Lifecycle Management:
• Allocation: When a new object is created using the new keyword, memory is allocated for it
in the heap.
• Tracing Reachability: The garbage collector tracks which objects are reachable and which
are not.
3. Garbage Collection Phases:
• Marking: The GC starts by marking all reachable objects. It traverses the object graph
starting from "root" references (e.g., local variables, static fields) and marks all objects that
are reachable.
• Sweeping: After the marking phase, the GC identifies the unmarked objects (those that are
not reachable) and considers them for collection.

4Q(b)OR –04
Q: State four similarities between Interfaces and Classes.
4Q(c)OR –07
Q: Differentiate between ArrayList and LinkedList? Which list should you use to insert and delete
elements at the beginning of a list? What methods are in LinkedList but not in ArrayList?
ANS: DIFF ALREADY DONE IN SUMMER PAPER
• LinkedList is preferred for inserting and deleting elements at the beginning of the list. It provides
efficient addFirst() and removeFirst() methods to perform these operations in constant time.
• Methods in LinkedList but not in ArrayList:
o addFirst(E e): Inserts the specified element at the beginning of the list.
o addLast(E e): Inserts the specified element at the end of the list.
o getFirst(): Retrieves the first element in the list.
o getLast(): Retrieves the last element in the list.
o removeFirst(): Removes and returns the first element in the list.
o removeLast(): Removes and returns the last element in the list.
o offerFirst(E e): Inserts the specified element at the beginning of the list, returning true if
successful.
o offerLast(E e): Inserts the specified element at the end of the list, returning true if successful.

5Q(a) –03
Q:List various classes for Binary Input Output?
ANS: ALREADY DONE IN SUMMER PAPER

5Q(b) –04
Q: Characterize the role of Iterator interface?
Ans:
• The Iterator interface in Java plays a crucial role in providing a uniform way to traverse collections
of objects, regardless of their underlying data structure.
• Here are some key characteristics and roles of the Iterator interface:
1. Traversal of Collections: The primary role of the Iterator interface is to enable traversal of
elements in a collection sequentially.
2. Uniform Interface: Iterator provides a uniform interface for iterating over different types of
collections such as lists, sets, and maps.
3. Iterator Pattern: The Iterator interface is a fundamental part of the Iterator design pattern,
which separates the traversal of a collection from the collection itself.
4. Fail-Safe Iteration: Iterators in Java are designed to handle concurrent modifications to the
underlying collection gracefully
5. Removal of Elements: Iterator provides methods for safely removing elements from the
underlying collection during iteration using the remove() method.
6. Support for Enhanced for-loop: The Iterator interface is used internally by the enhanced
for-loop (for-each loop) in Java to iterate over collections.
7. Immutable Collections: Iterators can be used to traverse immutable collections, providing a
read-only view of the elements. This ensures that the original collection remains unchanged
while allowing efficient traversal and processing of its elements.
5Q(c) –07
Q: Explain DataInputStream and DataOutputStream Classes? Implement a java program to
demonstrate any one of them?
ANS:
• DataInputStream:
o Java DataInputStream class allows an application to read primitive data from the input stream
in a machine-independent way.
o Example:

• DataOutputStream:
o Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.
o Java application generally uses the data output stream to write data that can later be read by a
data input stream.
o Example:

o
5Q(a)OR –03
Q: What do you understand by JavaFX? How it is different from AWT?
ANS:
• JavaFX:
o JavaFX is a modern, rich client application framework for Java. Here are some key
features and characteristics:
▪ Modern and Rich UI: JavaFX provides a wide range of UI controls, including
charts, tables, and web views. It supports modern UI elements and advanced graphics
features.
▪ FXML: JavaFX allows the use of FXML, an XML-based language, to define the user
interface. This separates the design from the application logic, making it easier to
manage and update.
▪ CSS Styling: JavaFX uses CSS for styling the UI components, similar to web
development, providing a familiar and powerful way to design the look and feel of
applications.
▪ Cross-Platform: JavaFX applications can run on various platforms, including
Windows, macOS, and Linux.
• Key Differences
o Modernity and Richness: JavaFX is a more modern toolkit with support for rich UIs,
advanced graphics, animations, and modern design principles. AWT is basic and outdated.
o Component Design: JavaFX components are more feature-rich and versatile. AWT
components are basic and heavyweight.
o Styling and Layout: JavaFX uses CSS for styling and FXML for UI layout, while AWT uses
Java code for both, making JavaFX more flexible and easier to design with.
o Graphics and Animation: JavaFX has extensive support for graphics and animations, which
AWT lacks.
o Property Binding: JavaFX supports property binding for dynamic and responsive UIs, a
feature not available in AWT.
o Cross-Platform Consistency: JavaFX offers better cross-platform consistency in terms of UI
look and feel compared to AWT.
5Q(b)OR –04

Q: Explain ArrayList Class with its methods?


ANS:
• ArrayList:
o ArrayList class uses a dynamic array for storing the elements.
o It is like an array, but there is no size limit.
o We can add or remove elements anytime.

• Methods of ArrayList:

Method Description

void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified
c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void ensureCapacity(int It is used to enhance the capacity of an ArrayList instance.


requiredCapacity)
E get(int index) It is used to fetch the element from the particular position of
the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.

Iterator()

listIterator()

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.
Object[] toArray() It is used to return an array containing all of the elements in
this list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in
this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It returns true if the list contains the specified element.

int indexOf(Object o) It is used to return the index in this list of the first occurrence
of the specified element, or -1 if the List does not contain this
element.
E remove(int index) It is used to remove the element present at the specified
position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified
element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that satisfies
filter) the given predicate.

protected void removeRange(int It is used to remove all the elements lies within the given
fromIndex, int toIndex) range.

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the
operator) specified element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present
in the specified collection.

E set(int index, E element) It is used to replace the specified element in the list, present
at the specified position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the
specified comparator.
Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list.

List<E> subList(int fromIndex, int It is used to fetch all the elements that lies within the given
toIndex) range.
int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be


the list's current size.

• Eample:
EXTRA QUESTION:
Q: Discuss BufferedInputStream and BufferedOutputStream classes with
an example.
ANS:
• BufferedInputStream:
o Java BufferedInputStream class is used to read information from
stream.
o It internally uses buffer mechanism to make the performance fast.
o The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal
buffer automatically refilled from the contained input stream, many
bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is
created.
o Java BufferedInputStream class declaration
▪ public class BufferedInputStream extends FilterInputStream
o Example:
• BufferedOutputStream:
o BufferedOutputStream class is used for buffering an output stream.
o It internally uses buffer to store data.
o It adds more efficiency than to write data directly into a stream.
o Java BufferedOutputStream class declaration
▪ public class BufferedOutputStream extends FilterOutputStream
o Example:
Q: Discuss fileWriter and fileReader classes with an example.
Ans:
• fileWriter:
o Java FileWriter class is used to write character-oriented data to a file.
o It is character-oriented class which is used for file handling in java.
o Java FileWriter class declaration
▪ public class FileWriter extends OutputStreamWriter
o Example:

• fileReader:
o Java FileReader class is used to read data from the file. It returns data
in byte format like FileInputStream class.
o It is character-oriented class which is used for file handling in java.
o Java FileReader class declaration
▪ public class FileReader extends InputStreamReader
o Example:
Q: Discuss fileInputStream and fileOutputStream classes with an example.
Ans:
• fileInputStream:
o Java FileInputStream class obtains input bytes from a file. It is used
for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc. You can also read character-stream data. But,
for reading streams of characters, it is recommended to use
FileReader class.
o Java FileInputStream class declaration
▪ public class FileInputStream extends InputStream
o example:

• fileOutputStream
o Java FileOutputStream is an output stream used for writing data to a
file.
o FileOutputStream class declaration
▪ public class FileOutputStream extends OutputStream
o Example:
Q:Diff b/w Abstract class & Interface

Ans:
Abstract class Interface
1) Abstract class can have abstract Interface can have only
and non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support Interface supports multiple
multiple inheritance. inheritance.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
5) The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
6) An abstract class can extend An interface can extend another Java
another Java class and implement interface only.
multiple Java interfaces.
7) An abstract class can be An interface can be implemented
extended using keyword "extends". using keyword "implements".
8) A Java abstract class can have Members of a Java interface are
class members like private, public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

You might also like