0% found this document useful (0 votes)
3 views21 pages

JAVA Model Question Paper XkVmao

The document is a Java model question paper covering various topics such as constructors, interfaces, applets, events, threads, inheritance, layout managers, exception handling, access specifiers, classes, arrays, GUI components, switch-case statements, method overloading, I/O streams, generic programming, and collections. Each topic includes definitions, explanations, examples, and relevant code snippets to illustrate the concepts. The document serves as a comprehensive guide for understanding key Java programming concepts and practices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

JAVA Model Question Paper XkVmao

The document is a Java model question paper covering various topics such as constructors, interfaces, applets, events, threads, inheritance, layout managers, exception handling, access specifiers, classes, arrays, GUI components, switch-case statements, method overloading, I/O streams, generic programming, and collections. Each topic includes definitions, explanations, examples, and relevant code snippets to illustrate the concepts. The document serves as a comprehensive guide for understanding key Java programming concepts and practices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

JAVA MODEL QUESTION PAPER

1. What is a constructor?
Answer:
In Java, a constructor is a special type of method that is automatically called when
an object of a class is created. It is used to initialize the object's state or perform any
necessary setup. Constructors have the same name as the class and do not have a
return type
Example: A a=new A()
Here A() is the Constructor.

2. Differentiate interfaces and abstract classes


Answer:

3. What is an applet?
Answer:
An applet is a Java program that can be embedded into a web page. It runs inside the
web browser and works at client
side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and
hosted on a web server

4. What is an event? Mention types of events


Answer:
Changing the state of an object is known as an event. For example, clicking on a
button, dragging a mouse, keypress through keyboard or page scrolling, etc. The
java.awt event package provides many events. classes and Listener interfaces for
event handling. An event can be defined as changing the state of an object or
behavior by performing actions. Actions can be a button click, cursor movement,
keypress through keyboard or page scrolling, etc.
Types of Events:
1. Foreground Events
2. Background Events

5. Mention 2 ways to create a thread


Answer:
By extending the Tread class or by implementing the runnable interface.

6. What are packages in Java


Answer:
A package is a namespace that organizes a set of related classes and interfaces.
Packages are divided into two categories:

● Built-in Packages (packages from the Java API)

● User-defined Packages (create your own packages)

7. Explain method overloading and method over-riding.


Answer:
Method Overloading:
Method overloading is a concept in Java where multiple methods in the same class
can have the same name but different parameter lists.
Method Overriding:
Method overriding is a concept that allows a subclass to provide a specific
implementation for a method that is already defined in its superclass.

8. What is a thread? Explain life cycle of a thread.


Answer:
Thread in Java
In Java, a thread is the smallest unit of execution within a process. It allows a
program to perform multiple tasks concurrently, which is particularly useful for
applications that need to perform tasks in the background while the main program
continues to run.
The Life Cycle of Thread
A thread goes through several stages during its life cycle. Java provides methods to
control and manage the life cycle of threads using the Thread class and related
classes from the java.lang package.

• New: The thread is created but not yet started. At this stage, the thread is in
the NEW state.
• Runnable: The thread is ready to run and can be scheduled by the thread
scheduler. It moves to the RUNNABLE state.
• Running: The thread is currently executing its task. It moves to the RUNNING
state.
• Blocked/Waiting: The thread is waiting for a particular condition or resource
to be satisfied. It can be in a blocked state (waiting for I/O, synchronization,
etc.) or a waiting state (waiting for another thread to complete). The thread
moves to the BLOCKED or WAITING state.
• Timed Waiting: The thread is waiting for a specific amount of time before
resuming its execution. It moves to the TIMED_WAITING state.
• Terminated/Dead: The thread has completed its task or has been terminated.
Once terminated, it cannot be restarted. The thread moves to the
TERMINATED state.

9. What is inheritance? Explain types of inheritance in Java


Answer:
Inheritance in Java
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a new class (subclass or derived class) to inherit properties and behaviours
(fields and methods) from an existing class (superclass or base class). In Java, the
keyword ‘extends’ is used to indicate inheritance. The subclass inherits all the non-
private members (fields and methods) of the superclass.
Types of Inheritance in Java:

• Single Inheritance:
Java supports single inheritance, where a class can inherit from only one superclass.
This means that a class can have only one immediate parent.
class Animal {
// Members and methods related to animals
}

class Dog extends Animal {


// Members and methods specific to dogs
}

• Multilevel Inheritance:
In multilevel inheritance, a class is derived from another class, which is itself
derived from yet another class.
class Vehicle {
// Members and methods related to vehicles
}

class Car extends Vehicle {


// Members and methods specific to cars
}

class SportsCar extends Car {


// Members and methods specific to sports cars
}
• Hierarchical Inheritance:
Hierarchical inheritance involves multiple subclasses inheriting from a common
superclass.
class Shape {
// Members and methods related to shapes
}

class Circle extends Shape {


// Members and methods specific to circles
}

class Square extends Shape {


// Members and methods specific to squares
}

• Multiple Inheritance
Single child class will have two or more parent class or base class.

• Hybrid Inheritance
It is the combination of multiple and Hierarchical inheritance.

10. What is the use of layout manager in Java? Explain all the layouts briefly.
Answer:
Java Layout Manager
The Layout manager is used to layout (or arrange) the GUI Java components inside a
container. There are many layout managers, but the most frequently used are-

• Java BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and
center. It is the default layout manager for every java JFrame
Example:
import java.awt.*;
class BorderLayoutExample extends Frame
{
BorderLayoutExample()
{
setLayout(new BorderLayout());
add(new Button("NORTH"),BorderLayout.NORTH);
add(new Button("SOUTH"),BorderLayout.SOUTH);
add(new Button("EAST"),BorderLayout.EAST);
add(new Button("WEST"),BorderLayout.WEST);
add(new Button("CENTER"),BorderLayout.CENTER);
}
}
class BorderLayoutJavaExample
{
public static void main(String args[])
{
BorderLayoutExample frame = new BorderLayoutExample();
frame.setTitle("BorderLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}
}

• Java FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out
components in a single row one after the other.
Constructors
FlowLayout() : Creates a default FlowLayout manager: centered alignment,
horizontal spacing and 5 vertical units.
FlowLayout(int) : Creates a FlowLayout manager with alignment and given horizontal
and vertical spacing of 5 units.
FlowLayout(int, int, int) : Creates a FlowLayout manager with alignment, horizontal
and vertical spacing data.
Example:
import java.awt.*;
class FlowLayoutExample extends Frame
{
FlowLayoutExample()
{
Button[] button =new Button[10];
setLayout(new FlowLayout());
for(int i=0;i<button.length;i++)
{
button[i]=new Button("Button "+(i+1));
add(button[i]);
}
}
}
class FlowLayoutJavaExample
{
public static void main(String args[])
{
FlowLayoutExample frame = new FlowLayoutExample();
frame.setTitle("FlowLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}}

• Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them
within a grid of cells, allowing components to span more than one cell.
GridLayout ()
Creates a GridLayout manager with a default row and a column.
GridLayout (int, int)
Creates a GridLayout manager with the number of rows and columns specified.
GridLayout (int, int, int, int)
Creates a GridLayout manager with the number of specified rows and columns and
alignment, horizontal and vertical spacing data.
Example:
import java.awt.*;
class GridLayoutExample extends Frame
{
GridLayoutExample()
{
Button[] button =new Button[12];
setLayout(new GridLayout(4,3));
for(int i=0; i<button.length;i++)
{
button[i]=new Button("Button "+(i+i));
add(button[i]);
}
}
}
class GridLayoutJavaExample
{
public static void main(String args[])
{
GridLayoutExample frame = new GridLayoutExample();
frame.setTitle("GridLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}
}

11. Explain any 4 methods of math class.


Answer:

• Math.abs(x) - Absolute Value:


This method returns the absolute value of the given number x, which is the distance
of x from zero on the number line. The result is always a non-negative value.

• Math.sqrt(x) - Square Root:


This method returns the square root of the given positive number x. If x is negative, it
returns a special value NaN (Not-a-Number).

• Math.random() - Random Number Generator:


This method returns a random double value between 0.0 (inclusive) and 1.0
(exclusive). It is often used to generate random numbers for various applications.

• Math.pow(x, y) - Power Function:


This method raises x to the power of y and returns the result. It can be used to
perform exponential calculations.

12. What is exception handling in Java? Explain try-catch-finally with an example


Answer:

• Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The
technical term for this is: Java will throw an exception (throw an error).
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
Output :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)

The try statement allows you to define a block of code to be tested for errors while it
is being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The try and catch keywords come in pairs:

• Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

• Example of try and catch:


public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Output :
Something went wrong.

13. (a) Explain all the access specifiers in Java.


(b) Explain Applet life cycle with a neat diagram.
Answer:
(a):
Access Specifiers in Java:
In Java, access specifiers determine the visibility and accessibility of classes,
methods, and fields within a class or across different classes. There are four main
access specifiers:

• Public:
Members declared as public are accessible from any class and package.
There are no access restrictions.
• Protected:
Members declared as protected are accessible within the same class, subclasses
(even if they are in different packages), and classes within the same package.
Outside the package, protected members are not accessible.

• Default (package-private):
Members with no explicit access specifier (default) are accessible only within the
same package.
They are not accessible outside the package, even if the classes are subclasses.

• Private:
Members declared as private are only accessible within the same class.
They are not accessible in subclasses or from other classes.

(b)
In this diagram, the arrows indicate the flow of control as the applet progresses
through its life cycle. The applet starts with start() and paint() while in view, pauses with
stop() when not visible, and eventually terminates with destroy().
14. (a) What is a class? Explain object-creation in Java. (Give Example)
(b) What is an array? Explain arrays in Java with example.
Answer:
(a):

• Class:
In Java, a class is a blueprint or template for creating objects. It defines the
structure and behavior of objects that will be created based on the class. A class
defines fields (variables) to store data and methods (functions) to perform actions on
the data. Objects are instances of a class, and they can have their own unique data
while sharing the methods and behavior defined by the class.

• Object-Creation:
Creating an object in Java involves two main steps: defining a class and then
instantiating (creating) an object based on that class. To create an object, you use the
new keyword followed by the class constructor
Example:
Class BCA{
Public static void main(String[] args)
{
BCA a=new BCA();
System.out.println(HI BCA);
}
Here a class with name BCA is created and an object with a name a is created in
the class BCA

(b):
Arrays in Java:
An array is a user defined datatype that can multiple value of same datatype.
Syntax of initialization:
dataType[] arrayName = {element1, element2, ...};
example:
int[] numbers = {10, 20, 30, 40, 50};

15.
(a) Mention any 6 GUI components in Java.
(b) Explain Switch-case with syntax and example.
Answer:
(a):

• JButton:
• JTextField:
• JLabel:
• JComboBox:
• JCheckBox:
• JRadioButton:
(b):
The switch statement in Java provides a way to simplify decision-making based
on the value of an expression. It allows you to select and execute one block of
code from a list of possibilities, improving the readability and efficiency of your
code when dealing with multiple conditions.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// ... more cases ...
default:
// Code to execute if no cases match
}
Example:
public class SwitchExample {
public static void main(String[] args) {
int day = 2;
String dayName;

switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
}

System.out.println("The day is: " + dayName);


}
}
16.
(a) Write a program in Java to add 2 floats add 2 integers using method
overloading.
(b) What are I/O stream in Java?
Answer:
(a):
public class MethodOverloadingExample {

// Method to add two floats


public static float add(float num1, float num2) {
return num1 + num2;
}

// Method to add two integers


public static int add(int num1, int num2) {
return num1 + num2;
}

public static void main(String[] args) {


float floatResult = add(3.5f, 4.7f);
int intResult = add(5, 7);

System.out.println("Sum of floats: " + floatResult);


System.out.println("Sum of integers: " + intResult);
}
}
(b):
In Java, I/O (Input/Output) streams provide a way to handle the flow of data
between a program and external sources or destinations, such as files, network
connections, or other input/output devices. Streams are used to read data from input
sources and write data to output destinations, making it possible to interact with
various types of data in a uniform and efficient manner.
Java's I/O stream classes are organized into two main categories: byte streams and
character streams.

• Byte Streams:
Byte streams are used for handling raw binary data, such as images, audio files, and
non-text files. They are represented by classes that end with InputStream or
OutputStream.

• Character Streams:
Character streams are used for handling character data, such as text files, where
character encoding matters. They are represented by classes that end with Reader or
Writer.

17.
Write short notes on:
(a) Generic programming
(b) Collections
Answers:
(a):
Generic Programming in Java:
Generic programming in Java allows you to create classes, interfaces, and methods that
work with various data types while maintaining type safety.
Advantages of Generic Programming:

• Type Safety: Generics ensure that data types are checked at compile time,
reducing the risk of type-related errors at runtime.
• Code Reusability: Generic classes and methods can be reused with different
data types, reducing code duplication.
• Performance: Generics can improve performance by avoiding the need for type
casting and allowing the compiler to optimize code.

Example:
class Test<T> {
T obj;
Test(T obj) { this.obj = obj; }
public T getObject() { return this.obj; }
}class Main {
public static void main(String[] args)
{
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());
Test<String> sObj= new Test<String>("Hi BCA");
System.out.println(sObj.getObject());
}
}
Output:
15
Hi BCA

(b):
Collections in Java:
Collections in Java provide classes and interfaces to store, manage, and manipulate
groups of objects.
Advantages of Collections:

• Abstraction: Collections provide a higher-level abstraction for managing


data, making it easier to focus on application logic.
• Efficiency: Collections offer optimized data structures and algorithms for
common operations like insertion, deletion, and searching.
• Type Safety: Generics are extensively used in collections, ensuring type
safety and reducing the need for type casting.
• Flexibility: Collections can store elements of different types, allowing you to
create versatile data structures.
Example:
import java.util.ArrayList;
import java.util.List;

public class CollectionsExample {


public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

for (String name : names) {


System.out.println(name);
}
}
}

18.
(a) Explain all object-oriented concepts supported by Java.
(b) What is the difference between String Class and String Buffer Class. Give
examples.
Answers:
(a):

• Class and Object: A class is a blueprint for creating objects, while an


object is an instance of a class. Classes define attributes (fields) and
behaviors (methods) that objects of that class will have.
• Encapsulation: Encapsulation is the practice of bundling data (fields) and
methods that operate on that data into a single unit (class). Access to the
data is controlled through methods, allowing better control over data
integrity and access.
• Inheritance: Inheritance allows a class (subclass/derived class) to inherit
properties and behaviors from another class (superclass/base class). It
promotes code reuse and establishes a hierarchical relationship.
• Polymorphism: Polymorphism allows objects of different classes to be
treated as objects of a common superclass. It enables dynamic method
binding and method overriding, making code more flexible and extensible.
• Abstraction: Abstraction involves focusing on essential characteristics
while ignoring unnecessary details. Abstract classes and interfaces
define a contract of methods that concrete classes must implement
• Overloading and Overriding: Overloading allows multiple methods in the
same class to have the same name but different parameters. Overriding
involves providing a new implementation of a method in a subclass,
modifying its behavior.
(b):
The main difference between the `String` class and the `StringBuffer` class
in Java is how they handle modifications to strings:

• String Class:
- Strings created with the `String` class are immutable, which means their
content cannot be changed after creation.
- When you modify a `String`, a new `String` object is created, which can be
inefficient for frequent modifications.
- Suitable when you need a fixed, unchanging text.

• StringBuffer Class:
- `StringBuffer` objects are mutable, allowing you to modify their content
without creating new objects.
- This makes `StringBuffer` more efficient for frequent string modifications,
as it avoids unnecessary memory overhead.
- Suitable when you need to manipulate strings frequently.

In simple terms, if you need to frequently modify a string's content, use


`StringBuffer`. If you don't need to change the content, or if you're dealing
with smaller strings, you can use the `String` class.

You might also like