Model QP Java July 2024
Model QP Java July 2024
2mark Questions
1. Write any 2 features of Java.
This means that a Java program written on one platform can be executed on another
without any modifications
This approach encourages modular and reusable code, making it easier to manage and
maintain complex software systems.
When a Java program is written, it is compiled by the Java compiler into an intermediate form
known as bytecode. This bytecode is a set of instructions that are platform-independent.
1. Class Loader
The class loader is like a librarian that finds and organizes the Java classes your
program needs, making sure everything is ready to go.
2. Runtime Data Area
The runtime data area serves as memory storage for different program execution
components, similar to a workspace that has multiple divisions.
1. Method Area
2. Heap Area
3. Stack Area
4. PC Register
5. Native Method Stack Area
3. Execution Engine
The execution engine acts as a skilled translator, converting your Java code into a
language that your computer can understand and execute. It does this through two
methods:
1. Interpreter
2. JIT Compiler
Instead, bytecode is executed by the Java Virtual Machine (JVM), which interprets or compiles it into
native machine code at runtime
The Java API(Java Application Program interface) is a collection of pre-written packages, classes, and
interfaces, along with their methods and fields, provided by the Java Development Kit (JDK).
Ex: classes from java.util package, classes from java.io for input/output operations
6.What is JIT Compiler
The Just-In-Time (JIT) compiler is a part of the Java Virtual Machine (JVM) , by compiling bytecode
into machine code, the JIT compiler optimizes execution speed and improves overall efficiency of Java
applications.
An abstract class in Java is a class that cannot be instantiated, it contains abstract methods,
which are declared without implementation,
For example:
8. What is an Identifier
An identifier in Java is a name given to various elements in a program such as variables, methods,
classes, and objects.
Identifiers must start with a letter (A-Z or a-z), a dollar sign ($), or an underscore (_),
followed by any combination of letters, digits (0-9), dollar signs, and underscores. Identifiers are
case-sensitive
Fields (variables) ;
Methods public;
}
Syntax to create a object
Keyword in Java:
A keyword in Java is a reserved word that has a predefined meaning in the language syntax
cannot be used as identifiers (e.g., variable names, class names, method names).
• Data Types: int, float, double, char, boolean, byte, short, long
• Control Flow: if, else, switch, case, default, while, do, for, break, continue,
return
• Access Modifiers: private, protected, public
• Class-Related: class, interface, extends, implements, abstract, final
• Exception Handling: try, catch, finally, throw, throws
• Object and Class: new, this, super, instanceof
• Others: static, void, volatile, package, import, enum
11.What is inheritance?
Inheritance in Java is concept where one class (child or subclass) inherits the properties and
behaviors (fields and methods) of another class (parent or superclass).
Syntax:
class ParentClass {
// Fields and methods
}
12.What is interface?
An interface in Java is a reference type contain only method signatures, default methods, static
methods, and nested types. Interfaces cannot contain instance fields or constructors.
EX:
interface InterfaceName
{
// Abstract method
void method1();
// Default method
default void method2()
{
System.out.println("Default implementation");
}
// Static method
static void method3()
{
System.out.println("Static implementation");
}
}
try {
// Code that may throw an exception
}
catch (ExceptionType1 e1)
{
// Code to handle exception of type ExceptionType1
}
catch (ExceptionType2 e2)
{
// Code to handle exception of type ExceptionType2
}
finally {
// Code that will always execute, whether exception is thrown or not
}
Key Components:
1. try: The block of code throw an exception is placed inside the try block.
2. catch: The catch block is used to handle the exception. It catches the exception
thrown by the try block and defines how to handle it.
3. finally: The finally block contains code that will always be executed, regardless of
whether an exception is thrown or not.
4. throw: The throw keyword is used to explicitly throw an exception.
5. throws: The throws keyword is used in the method signature to indicate that the
method might throw exceptions.
14. Define class and object
Class:
A class in Java is a blueprint or template for creating objects. It combines data and methods
as a single unit. A class encapsulates data and methods to manipulate that data.
Object:
An object is an instance of a class.Objects are created using the new keyword followed by the
class constructor.
The final keyword in Java is used to define an entity that cannot be changed or modified.
It can be applied to variables, methods, and classes.
Final Variables:
Ex:
final int a = 100;
Final Methods:
A final method cannot be overridden by subclasses. This is used to prevent altering the
method's implementation in subclasses.
// Method body
}
16. List the different types of comments in Java?
1. Single-Line Comments:
Single-line comments begin with // and extend to the end of the line
2.Multi-Line Comments:
Multi-line comments, also known as block comments, begin with /* and end with */
Separators in Java:
Separators in Java are special characters that are used to separate different parts of a program
Types
Parentheses ()
Braces {}
Brackets []
Semicolon ;
Comma ,
Period .
Colon :
An event is an object that represents an action by software, often generated as a result of user
interactions or other programmatic activities. They are used to trigger specific methods when
certain actions occur, such as : button click, mouse movement, or a key press.
High-level events.
ActionEvent:
ItemEvent:
FocusEvent:
Low-Level Events:
Low-level events are generated by low-level input devices such as the mouse and keyboard.
1. MouseEvent:
o Generated by mouse actions such as clicks, presses, releases, movements, and
drags.
2. KeyEvent:
3. WindowEvent:
Unicode is a universal character encoding standard that provides a unique number for every
character.
• 16-Bit Representation:
• Java uses 16-bit Unicode characters. This means each character is represented by a
16-bit (2-byte) value.
• This allows Java to support 65,536 unique characters.
• The char data type in Java is used to store a single Unicode character.
null is a literal in Java that represents the absence of a value or a reference to an object. It can be
assigned to any reference type variable (e.g., objects, arrays).
String str = null; // str does not reference any String object
if (str == null) {
true and false are boolean literals in Java that represent the two possible values of a
boolean type.
Dynamic loading in Java refers to the process of loading classes into the Java Virtual
Machine (JVM) at runtime rather than at compile time
Swing is a part of Java's standard library that provides a rich set of GUI components for building
graphical user interfaces (GUIs)
JavaBeans are reusable software components for Java that can be manipulated visually in a
builder tool.
JavaBeans have properties that can be accessed and modified using getter and setter methods.
JavaBeans can generate and listen to events.
Java programs that can be embedded in web pages and run in web browser using applet, providing
interactive features
BIG Questions
1. Explain lifecycle of a thread. ****
1.Thread States:
2.New
3.Runnable:
4.Blocked:
5.Waiting:
6.Terminated:
Advantages of Applets:
1. Platform Independence:
o Applets are written in Java, which is a platform-independent language. This means
they can run on any system that has a compatible Java Virtual Machine (JVM) and a
supporting web browser.
2. Rich User Interface:
o Applets can use the full power of the Java API, including Swing and AWT, to create
rich and interactive user interfaces.
3. Security:
o Applets run in a sandbox environment which restricts their ability to perform
potentially dangerous operations, such as file I/O on the client machine. This
sandboxing helps protect users from malicious code.
4. Easy to Deploy:
o Applets are easy to deploy since they can be embedded in HTML pages and loaded
over the network. Users do not need to install the applet explicitly; it is downloaded
and executed by the browser.
5. Automatic Updates:
o Since applets are loaded from a web server, updates to the applet can be made on
the server side. Users automatically get the latest version when they load the web
page.
Disadvantages of Applets:
1. Browser Support:
o Modern browsers have discontinued support for NPAPI (Netscape Plugin Application
Programming Interface), which is required for running Java applets. This has made it
difficult to run applets on most modern browsers.
2. Security Restrictions:
o The security restrictions of the applet sandbox can be limiting. Applets are not allowed
to perform many tasks that are necessary for advanced applications, such as accessing
the local file system or making network connections to arbitrary hosts.
3. Performance:
o Applets can suffer from performance issues, especially when compared to native
applications or other web technologies. This is due to the overhead of the JVM and
the browser plugin.
4. User Experience:
o The user experience with applets can be inconsistent. They require a JVM to be
installed on the client machine, which can be a barrier for users. Additionally, the
loading time for applets can be significant, leading to a poor user experience.
5. Compatibility Issues:
o Different versions of the JVM and browser can lead to compatibility issues. An applet
that works in one environment might not work in another, causing frustration for
developers and users alike.
6. Declining Usage:
o With the rise of modern web technologies such as HTML5, CSS3, and JavaScript
frameworks, the need for applets has significantly diminished. These newer
technologies offer better performance, security, and cross-browser compatibility.
Swing is a part of the Java Foundation Classes (JFC) and provides a rich set of components for building
graphical user interfaces (GUIs). Swing is built on top of the Abstract Window Toolkit (AWT) and
provides a more flexible and powerful framework for creating desktop applications.
• Lightweight Components: Swing components are written entirely in Java and do not rely
on native GUI components, making them platform-independent and lightweight.
• Pluggable Look and Feel: Swing allows developers to change the look and feel of the
application at runtime. You can use the default look and feel provided by the operating
system, or you can set a custom look and feel.
• Rich Set of Components: Swing provides a wide variety of components, including buttons,
checkboxes, radio buttons, text fields, text areas, tables, trees, and more.
• Customizable Components: Swing components are highly customizable. You can extend
existing components or create your own custom components by subclassing JComponent.
• Drag and Drop: Swing supports drag-and-drop functionality, making it easier to implement
interactive and intuitive user interfaces.
• Layout Managers:
Key Benefits:
1. Unified Architecture:
2. Reusability:
3. Interoperability:
Collections within the framework are designed to be interoperable. You can easily
convert from one type of collection to another (e.g., from a List to a Set), facilitating
flexible and efficient data handling.
5. Improved Performance:
The Collections class provides static methods for performing common operations,
such as sorting, searching, and shuffling, on collections.
1. Iterable<T> (Interface):
The root interface for all collection classes. It defines the iterator() method, which
returns an Iterator object to traverse the collection
public interface Iterable<T>
{
Iterator<T> iterator();
}
2. Collection<E> (Interface):
Extends Iterable. It is the root interface for the collection hierarchy, providing basic
operations like add, remove, size, and contains
a) Key Interfaces
5. Map<K, V> (Interface): Represents a collection of key-value pairs. Maps do not extend
Collection but are part of the framework. Each key maps to exactly one value.
b. Key Classes
ArrayList<E> (Class): Implements List. It uses a dynamic array to store the elements. It
allows random access and is good for frequent read operations.
LinkedList<E> (Class): Implements List, Deque. It uses a doubly-linked list to store the
elements. It is good for frequent insertions and deletions
HashSet<E> (Class): Implements Set. It uses a hash table to store the elements and provides
constant-time performance for basic operations.
TreeSet<E> (Class): Implements Set, NavigableSet. It uses a red-black tree to store the
elements in sorted order.
PriorityQueue<E> (Class): Implements Queue. It uses a priority heap to order the elements
and provides efficient access to the element with the highest priority.
HashMap<K, V> (Class): Implements Map. It uses a hash table to store key-value pairs and
provides constant-time performance for basic operations.
TreeMap<K, V> (Class): Implements Map, NavigableMap. It uses a red-black tree to store
key-value pairs in sorted order.
6. Explain the implementation of Multiple inheritance using interface
Java does not support multiple inheritance through classes to avoid complexity and ambiguity.
However, it allows multiple inheritance using interfaces.
Key Concepts:
1. Interface Declaration:
Interfaces are declared using the interface keyword. An interface can contain
abstract methods, default methods, and static methods.
2. Class Implementation:
A class implements an interface using the implements keyword. A class can
implement multiple interfaces by separating them with commas.
// Interface 1
interface Printable {
void print();
}
// Interface 2
interface Showable {
void show();
}
Let's consider an example where we have two interfaces, Printable and Showable, and a class
Document that implements both interfaces.
Explanation:
1. Interface Declaration:
o Printable and Showable are two interfaces, each with one abstract method:
print() and show(), respectively.
2. Class Implementation:
o Document implements both Printable and Showable interfaces.
o The class provides implementations for both print() and show() methods.
3. Using the Class:
o In the main method, an instance of Document is created.
o The print() and show() methods are called on the Document instance,
demonstrating that it can handle methods from both interfaces.
Interfaces define set of methods that a class must implement. An interface can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot contain
instance fields or constructors
An interface is defined using the interface keyword. It can include abstract methods (methods
without a body), default methods (methods with a default implementation), and static methods.
// Defining an interface
public interface Animal {
// Abstract method
void eat();
// Default method
default void sleep() {
System.out.println("Sleeping...");
}
// Static method
static void breathe() {
System.out.println("Breathing...");
}
}
Implementing an Interface
A class implements an interface using the implements keyword. A class can implement
multiple interfaces, providing concrete implementations for all abstract methods defined in the
interfaces.
Java provides a rich set of classes and interfaces for creating graphical user interfaces (GUIs) through
its Abstract Window Toolkit (AWT) and Swing libraries.
These libraries offer a wide range of GUI components, from basic ones like buttons and labels to more
complex ones like tables and trees.
Swing is a more advanced GUI toolkit that builds on AWT but provides a richer set of
components, better look and feel, and more powerful features.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
Byte streams are classified into two main categories: Input Streams and Output Streams
• FileInputStream:
o Reads bytes from a file.
ByteArrayInputStream:
BufferedInputStream:
• Allows an application to read primitive Java data types from an underlying input
stream in a machine-independent way.
• FileOutputStream:
o Writes bytes to a file.
ByteArrayOutputStream:
BufferedOutputStream:
charAt(int index)
length()
• Returns a new string that is a substring of this string starting from beginIndex.
• Returns a new string that is a substring of this string from beginIndex to endIndex
(exclusive).
indexOf(char ch)
lastIndexOf(char ch)
toLowerCase()
toUpperCase()
trim()
}
}
The method in the subclass should have the same name, return type, and parameters as the method
in the superclass.
// Base class
class Animal {
// Method in the superclass
public void sound() {
System.out.println("Some generic animal sound");
}
}
In the above example dog override the method in dog class , so we will get a output bark
instead of some generic animal sound
• When we create an Animal object and call sound, it uses the method in the Animal class.
• When we create a Dog object and call sound, it uses the overridden method in the Dog class.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
1. Single Inheritance
Single inheritance is when a class inherits from only one superclass. This is the most
straightforward form of inheritance.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
Multilevel Inheritance
Multilevel inheritance is when a class is derived from another derived class, forming a chain
of inheritance.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
Hierarchical Inheritance
Hierarchical inheritance is when multiple classes inherit from a single superclass. This forms
a tree structure of classes.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
1. Default Constructor
A default constructor is a constructor that does not take any arguments. If no constructor is
defined in a class, Java provides a default constructor automatically.
class Animal {
String name;
// Default constructor
public Animal() {
name = "Unknown";
}
void display() {
System.out.println("Animal name: " + name);
}
}
Parameterized Constructor
A parameterized constructor is a constructor that takes one or more arguments. This allows
the object to be initialized with specific values at the time of creation.
class Animal {
String name;
// Parameterized constructor
public Animal(String name) {
this.name = name;
}
void display() {
System.out.println("Animal name: " + name);
}
}
By using the this keyword, we ensure that the instance variable name is correctly assigned
the value of the parameter name passed to the constructor.
class Student {
String name;
// Constructor that takes a parameter 'name'
public Student(String name) {
// Using 'this' to refer to the instance variable 'name'
this.name = name;
}
• try: The block of code that is likely to throw an exception is placed inside the try block.
• catch: The catch block is used to handle the exception. It catches the exception thrown by
the try block and defines how to handle it.
• finally: The finally block contains code that will always be executed, regardless of
whether an exception is thrown or not. It is typically used for cleanup activities, like closing
resources.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Code to handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle exception of type ExceptionType2
} finally {
// Code that will always execute, whether exception is thrown or not
}
The above program will throw an exception and caught in catch block with the message
ArithmeticException caught
Selection statements are used to choose different paths of execution based on the outcome of
an expression or condition.
if (condition) {
// code to be executed if condition is true
}
if-else Statement: Executes one block of code if a specified condition is true and another block of code
if it is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
if-else-if Ladder: Checks multiple conditions sequentially and executes a block of code for the first true
condition.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
switch Statement: Selects one of many blocks of code to be executed, based on the value of an
expression.
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// other cases
default:
// code to be executed if expression doesn't match any case
}
iteration statements are used to repeatedly execute a block of code as long as a specified
condition is true.
while Loop: Repeatedly executes a block of code as long as a specified condition is true.
while (condition) {
// code to be executed
}
do-while Loop: Similar to the while loop, but it guarantees that the block of code is executed at
least once
do {
// code to be executed
} while (condition);
3. Jump Statements
Jump statements are used to transfer control to another part of the program.
continue Statement: Skips the current iteration of the nearest enclosing loop and proceeds with the
next iteration.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // skip the rest of this loop iteration
}
// code to be executed for each iteration
}
Summary
If else
switch Statement
The switch statement selects one of many blocks of code to be executed based on the value
of an expression.
Syntax
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// other cases
default:
// code to be executed if expression doesn't match any case
}
In the above example particular case will be executed based on the condition. If any condition is not matching
the control will transfer to default statement
Looping statements are used to repeatedly execute a block of code as long as a specified
condition is true. There are three main types of looping statements:
1. for Loop
2. while Loop
3. do-while Loop
1. for Loop
The for loop is used when the number of iterations is known beforehand. It consists of three
parts: initialization, condition, and update.
Syntax:
while Loop
The while loop is used when the number of iterations is not known beforehand, and it
depends on a condition. The loop continues to execute as long as the condition is true.
Syntax:
while (condition) {
// code to be executed
}
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
}
}
do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the loop's body will be
executed at least once, regardless of the condition.
Syntax:
do {
// code to be executed
} while (condition);
Summary
• for Loop: Used when the number of iterations is known. It consists of initialization,
condition, and update parts.
• while Loop: Used when the number of iterations is not known and depends on a condition.
The loop executes as long as the condition is true.
• do-while Loop: Similar to the while loop but ensures that the loop body is executed at
least once, regardless of the condition.
The conditional operator, also known as the ternary operator, is a shorthand way of expressing
conditional statements.
1. Simple
Java is designed to be easy to learn and use. Its syntax is clean and easy to understand, making
it an excellent choice for beginners. It also removes complex features of other languages like
pointers and multiple inheritance, making it more straightforward to work with.
2. Object-Oriented
Java follows the object-oriented programming (OOP) paradigm, which means it uses objects
and classes to organize code. This approach promotes code reuse, modularity, and scalability.
The four main principles of OOP in Java are:
• Encapsulation: Bundling data (attributes) and methods (functions) that operate on the data
into a single unit called a class.
• Inheritance: Creating new classes from existing ones, inheriting attributes and behaviors.
• Polymorphism: Allowing methods to do different things based on the object it is acting upon.
• Abstraction: Hiding complex implementation details and showing only the essential features
of the object.
3. Platform-Independent
Java is platform-independent at both the source and binary levels, which means that Java
programs can run on any device that has the Java Virtual Machine (JVM) installed. This feature
is often summarized by the phrase "write once, run anywhere."
4. Secure
Java provides a secure environment for developing applications. It has built-in security features
such as bytecode verification, access control, and a robust exception-handling mechanism.
Java's security manager and various APIs help in creating secure applications by protecting
against viruses and tampering.
5. Robust
Java is designed to be reliable and robust. It has strong memory management, automatic
garbage collection, exception handling, and type checking at compile time. These features help
in developing applications that are less prone to crashes and bugs.
6. Multithreaded
Java supports multithreading, which allows concurrent execution of two or more threads
(smallest unit of a process). This feature is useful for performing multiple tasks simultaneously
within a program, leading to efficient use of CPU resources.
7. Architectural Neutral
Java's bytecode is not specific to any processor or operating system, which makes Java
programs highly portable. The Java compiler generates an intermediate bytecode that can be
executed on any machine equipped with a JVM.
8. High Performance
While Java is not as fast as compiled languages like C or C++, it achieves high performance
through the use of Just-In-Time (JIT) compilers. The JIT compiler compiles bytecode into
native machine code at runtime, which improves the execution speed of Java applications.
9. Distributed
Java provides built-in support for networked (distributed) applications. It includes a rich set of
APIs for handling TCP/IP protocols, enabling developers to create applications that can access
resources across a network seamlessly. Java RMI (Remote Method Invocation) and CORBA
(Common Object Request Broker Architecture) are examples of APIs that support distributed
computing.
10. Dynamic
Java is dynamic in nature due to its ability to load classes at runtime. This means that new
methods and fields can be added to classes and objects without affecting the existing code. The
reflection feature in Java allows inspection of classes, interfaces, fields, and methods at runtime
without knowing their names at compile time.
Access control modifiers, also known as access specifiers, in Java are keywords that set the
accessibility (visibility) of classes, methods, and other members
Types:
• Public
• Protected
• Private
Public
Protected
• Scope: The member is accessible within the same package and by subclasses (even if they
are in different packages).
package mypackage;
package mypackage;
package otherpackage;
import mypackage.ProtectedExample;
Summary
• Public: Members are accessible from any other class. Use the public keyword.
• Protected: Members are accessible within the same package and by subclasses. Use the
protected keyword.
• Private: Members are accessible only within the same class. Use the private keyword.
These access specifiers help in encapsulating the details of the implementation and exposing
only the necessary parts of the code, enhancing the modularity and maintainability of the
software.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Unary Operators
• Ternary Operator
Arithmetic operators
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Modulus (%)
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before operators with lower precedence. If
operators have the same precedence, their associativity (left-to-right or right-to-left)
determines the order of evaluation.
27. Explain Wild card in generics
Wildcards in Java Generics provide a way to handle different types more flexibly while still
maintaining type safety. They are used when you want to relax the restrictions on a variable
that uses generics. There are three types of wildcards in Java:
The unbounded wildcard represents an unknown type. It can be used when the specific type is
not important. This wildcard is useful when you want to write a method that can operate on
collections of any type.
The upper bounded wildcard restricts the unknown type to be a specific type or a subtype of
that type. This is useful when you want to read items from a data structure.
The lower bounded wildcard restricts the unknown type to be a specific type or a supertype of
that type. This is useful when you want to write items into a data structure.
printList(intList);
printList(strList);
}
}
Output
1
2
3
One
Two
Three