0% found this document useful (0 votes)
16 views30 pages

Java 5th Sem Exam

Java is a high-level programming language known for its simplicity, object-oriented nature, platform independence, security, robustness, multithreading capabilities, and high performance. It supports various features such as variable declaration, method overriding, exception handling, and the use of packages and threads. Java achieves multiple inheritance through interfaces and provides layout managers for organizing GUI components.

Uploaded by

manojkawale68
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)
16 views30 pages

Java 5th Sem Exam

Java is a high-level programming language known for its simplicity, object-oriented nature, platform independence, security, robustness, multithreading capabilities, and high performance. It supports various features such as variable declaration, method overriding, exception handling, and the use of packages and threads. Java achieves multiple inheritance through interfaces and provides layout managers for organizing GUI components.

Uploaded by

manojkawale68
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

Explain the features of java in details ?

Features of Java
Java is a powerful, high-level programming language designed to be simple, secure, portable,
and robust. Its main features are explained below:
1. Simple
Java is easy to learn and use because it has a clean and simple syntax. It does not use
complicated concepts like pointers and operator overloading (as in C++). Automatic memory
management using Garbage Collection also reduces programmer effort.
2. Object-Oriented
Java is fully object-oriented, which means it is based on concepts like class, object, inheritance,
polymorphism, abstraction, and encapsulation. This helps in writing reusable, modular, and
well-structured programs.
3. Platform Independent
Java follows the principle “Write Once, Run Anywhere (WORA)”. Java programs are compiled
into bytecode, which can run on any system that has a Java Virtual Machine (JVM), regardless
of hardware or operating system.
4. Secure
Java provides a high level of security. It does not allow direct access to memory through
pointers. Java programs run inside a sandbox environment, and features like bytecode
verification and security managers help protect systems from harmful programs.
5. Robust
Java is robust because it has strong exception handling, type checking, and automatic garbage
collection. These features help prevent runtime errors and improve program reliability.
6. Multithreaded
Java supports multithreading, which allows multiple tasks to run simultaneously within a single
program. This improves performance and makes efficient use of CPU resources, especially in
large applications.
7. High Performance
Although Java is interpreted, it uses Just-In-Time (JIT) compilation, which converts bytecode
into native machine code at runtime. This improves execution speed and overall performance.
Conclusion
Because of these features, Java is widely used for desktop applications, web applications,
mobile apps, and enterprise systems.
What are variables? Write rules for naming variables with example.

Variables

A variable is a name given to a memory location used to store data in a program. The value of a
variable can change during program execution, which is why it is called a variable.

Example:

If we store a number in a variable:

int age = 15;

Here, age is a variable that stores the value 15.

Rules for Naming Variables (with Examples)

1. A variable name must begin with a letter or an underscore (_).

✔ Valid: total, _count

✘ Invalid: 1total

2. Variable names can contain letters, digits, and underscores only.

✔ Valid: marks_1, student2

✘ Invalid: total-marks

3. A variable name must not start with a digit.

✔ Valid: score1

✘ Invalid: 1score

4. No spaces are allowed in variable names.

✔ Valid: totalMarks

✘ Invalid: total Marks

5. Variable names must not be keywords or reserved words.

✔ Valid: sum

✘ Invalid: int, while

6. Variable names are case-sensitive.


Age and age are treated as different variables.

7. Variable names should be meaningful and descriptive.

✔ Good: totalMarks

✘ Poor: tm

Example of Variable Declaration

float salary = 25000.50;

Describe the structure of java program. Give suitable example.

Structure of a Java Program

A Java program follows a well-defined structure. Each part has a specific purpose and helps the
program to compile and run correctly.

Parts of a Java Program

1. Documentation Section (Comments)

This section contains comments that describe the program. Comments improve readability and
do not affect execution.

Example:

// This program displays a message

2. Package Statement (Optional)

It is used to group related classes into a package.

Example:

package myprogram;

3. Import Statements (Optional)

These statements allow access to predefined classes in Java libraries.

Example:

import [Link];

4. Class Declaration
Every Java program must have at least one class. The class name should match the file name.

Example:

class Sample

5. Main Method

The main() method is the entry point of a Java program. Program execution starts from here.

Syntax:

public static void main(String[] args)

6. Statements and Expressions

These are the instructions written inside the main method that perform specific tasks.

Example:

[Link]("Welcome to Java");

7. Closing Braces

Curly braces { } are used to mark the beginning and end of classes and methods.

Example of a Java Program

// Simple Java program

class HelloWorld

public static void main(String[] args)

[Link]("Hello, Java!");

Conclusion
The structure of a Java program includes comments, package statement, import statement,
class definition, main method, and program statements. Understanding this structure is
essential for writing correct Java programs.

Differentiate between applet and application.

Difference between Applet and Application

1. Definition:

Applet: A small program that runs inside a web browser.

Application: A standalone program that runs directly on the computer.

2. Execution:

Applet: Runs in a browser or applet viewer.

Application: Runs independently on the operating system.

3. Entry Point:

Applet: Uses init(), start(), stop(), destroy() methods.

Application: Uses main() method.

4. Access & Security:

Applet: Limited access to system resources (sandboxed).

Application: Full access to system resources.

5. Purpose:

Applet: Provides interactive content for web pages (like animations or forms).

Application: Performs general-purpose computing tasks (like calculators or text editors).

6. Size:

Applet: Small and lightweight.

Application: Can be large and complex.

7. Deployment:

Applet: Embedded in HTML pages.


Application: Run as standalone programs or .jar files.

List the operators supported by java. Explain bitwise operators with example.

1. Operators Supported by Java

Java has the following operators:

1. Arithmetic Operators: + - * / %

2. Relational Operators: == != > < >= <=

3. Logical Operators: && || !

4. Bitwise Operators: & | ^ ~ << >> >>>

5. Assignment Operators: = += -= *= /= %= &= |= ^= <<= >>= >>>=

6. Unary Operators: + - ++ -- !

7. Ternary Operator: condition ? value_if_true : value_if_false

8. Type Comparison Operator: instanceof

2. Bitwise Operators

Bitwise operators work on the binary form of integers.

Operator​ Meaning

&​ AND

`​ `

^​ XOR

~​ NOT

<<​ Left shift

>>​ Right shift

>>>​ Unsigned right shift

Example:
int a = 5; // 0101 in binary

int b = 3; // 0011 in binary

[Link](a & b); // 1 (0101 & 0011 = 0001)

[Link](a | b); // 7 (0101 | 0011 = 0111)

[Link](a ^ b); // 6 (0101 ^ 0011 = 0110)

[Link](~a); // -6 (in two’s complement)

[Link](a << 1); // 10 (0101 << 1 = 1010)

[Link](a >> 1); // 2 (0101 >> 1 = 0010)

Write Short notes on : 1. JDK 2. JVM

1. JDK (Java Development Kit)

Definition: JDK is a software development kit used to develop Java programs.

Components:

1. JVM – to run Java programs

2. JRE (Java Runtime Environment) – to provide runtime libraries

3. Development tools – javac (compiler), jar, javadoc, etc.

Purpose: Allows programmers to write, compile, and run Java programs.

2. JVM (Java Virtual Machine)

Definition: JVM is an abstract machine that executes compiled Java bytecode.

Functions:

1. Converts bytecode into machine code using Just-In-Time (JIT) compiler

2. Provides platform independence (write once, run anywhere)

3. Manages memory using heap and stack

Key Point: JVM is part of JRE and is platform-specific.


What are packages in java? Explain how to create user defined package.

Packages in Java

Definition: A package is a collection of related classes, interfaces, and sub-packages that helps
in organizing code, avoiding name conflicts, and reusing code.

Types of Packages:

1. Built-in packages (e.g., [Link], [Link])

2. User-defined packages

Creating a User-Defined Package

Steps:

1. Create a package

package mypackage; // define package name

public class MyClass {

public void display() {

[Link]("Hello from mypackage");

2. Compile the class

javac -d . [Link]

-d . creates a folder structure for the package.

3. Use the package in another class

import [Link];

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

[Link]();
}

4. Compile and run

javac [Link]

java Test

What is Thread? Describe the complete life cycle of thread.

Thread in Java

Definition: A thread is a smallest unit of execution within a program.

Purpose: Threads allow concurrent execution of two or more tasks in a program, improving
performance.

Life Cycle of a Thread

A thread in Java can exist in five states, managed by the Thread class:

1. New (Created) State

When a thread object is created using Thread t = new Thread().

The thread is not yet started.

2. Runnable (Ready) State

When [Link]() is called.

The thread is ready to run and waiting for CPU allocation.

3. Running State

When the thread scheduler picks the thread from the Runnable state.

The thread executes its run() method.

4. Blocked/Waiting State

When a thread is waiting for a resource or another thread to complete.

Examples: sleep(), wait(), join().

5. Terminated (Dead) State


After the thread finishes execution or is stopped.

Cannot be restarted once dead.

Thread Life Cycle Diagram:

New

Runnable <--> Running

| |

v v

Waiting/Blocked

Terminated

Explain the concept of multithreading. How threads can be synchronized?

Multithreading in Java

Definition: Multithreading is the concurrent execution of two or more threads within a program.

Purpose:

1. Improves CPU utilization.

2. Makes programs faster and responsive.

3. Useful in simultaneous tasks like file I/O, GUI, network operations.

Example: A music player playing music while downloading files.

Thread Synchronization

Problem: When multiple threads access shared resources simultaneously, it can cause data
inconsistency.

Solution: Synchronization ensures only one thread accesses a resource at a time.


Ways to synchronize threads:

1. Synchronized Method:

class Counter {

int count = 0;

synchronized void increment() {

count++;

2. Synchronized Block:

class Counter {

int count = 0;

void increment() {

synchronized(this) {

count++;

Key Point: Synchronization prevents race conditions and ensures thread safety.
Explain thread priorities?

Thread Priorities (7 marks)

1. Definition:

Thread priority is a numeric value assigned to a thread to indicate its importance relative to
other threads. It helps the scheduler decide which thread to execute first.

2. Priority Range:

Typically, priority ranges from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY).

Default priority is 5 (NORM_PRIORITY).

3. Purpose:

Higher-priority threads are more likely to be executed before lower-priority threads.

Useful for managing critical tasks in a program.

4. Setting and Getting Priority:

setPriority(int p) → Assigns a priority to thread.

getPriority() → Returns the current priority of a thread.

5. Important Notes:

Priority does not guarantee exact execution order; it depends on the scheduler and operating
system.

Threads with the same priority are generally executed in a round-robin manner.

6. Example (Java):

Thread t1 = new Thread();

[Link](Thread.MAX_PRIORITY); // set highest priority

[Link]([Link]()); // prints 10

7. Summary:

Thread priorities guide scheduling and improve efficiency for critical tasks, but execution order is
not strictly guaranteed.
What is method overriding? Explain with an example.

Method Overriding

1. Definition:

Method overriding occurs when a subclass (child class) provides its own implementation of a
method that is already defined in its superclass (parent class) with the same method name,
return type, and parameters.

It is used for runtime polymorphism.

2. Rules for Overriding:

The method in the child class must have the same name, return type, and parameters as in the
parent class.

Access level in child class cannot be more restrictive than in the parent class.

Only inherited methods can be overridden.

3. Purpose:

Allows a subclass to provide a specific behavior while reusing the parent class structure.

Supports dynamic method dispatch (runtime polymorphism).

4. Example (Java):

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

[Link]("Dog barks");

}
}

public class Test {

public static void main(String[] args) {

Animal a = new Dog();

[Link](); // Calls Dog's overridden method: "Dog barks"

5. Explanation of Example:

Animal has a method sound().

Dog overrides sound() to provide its own implementation.

At runtime, the Dog’s method is called even though the reference type is Animal.

6. Key Point:

Overriding happens at runtime, not at compile time.

Achieves runtime polymorphism.

7. Summary:

Method overriding allows a child class to change or extend the behavior of a parent class
method, enabling flexible and dynamic programming.
How is multiple inheritance achieved in Java? Explain with an example.

Multiple Inheritance in Java

1. Definition:

Multiple inheritance is when a class inherits features from more than one parent class.

2. Java Restriction:

Java does not support multiple inheritance with classes to avoid the “Diamond Problem”
(ambiguity if two parent classes have the same method).

3. How It Is Achieved in Java:

Through interfaces.

A class can implement multiple interfaces, effectively achieving multiple inheritance of behavior.

4. Rules:

A class can implement multiple interfaces separated by commas.

Interfaces can contain abstract methods (and default methods).

The implementing class must provide implementations for all abstract methods.

5. Example (Java):

interface Printable {

void print();

interface Showable {

void show();

class Document implements Printable, Showable {

public void print() {

[Link]("Printing document");

}
public void show() {

[Link]("Showing document");

public class Test {

public static void main(String[] args) {

Document doc = new Document();

[Link](); // Printing document

[Link](); // Showing document

6. Explanation:

Document class implements two interfaces, Printable and Showable.

Provides concrete implementations for all methods.

Achieves multiple inheritance without the problems of multiple class inheritance.

7. Summary:

Java achieves multiple inheritance through interfaces.

This allows a class to inherit behavior from multiple sources safely, avoiding ambiguity.
What is exception? How can exceptions be handled in Java?

Exception in Java

1. Definition:

An exception is an unexpected event or error that occurs during the execution of a program,
disrupting the normal flow of instructions.

Example: division by zero, file not found, array index out of bounds.

2. Types of Exceptions:

Checked Exceptions: Must be handled at compile time (e.g., IOException, SQLException).

Unchecked Exceptions: Occur at runtime (e.g., ArithmeticException, NullPointerException).

3. Handling Exceptions:

Exceptions in Java are handled using try-catch-finally blocks or throws/throw keywords.

4. Using try-catch:

try {

int result = 10 / 0; // may cause ArithmeticException

} catch (ArithmeticException e) {

[Link]("Cannot divide by zero");

} finally {

[Link]("This block always executes");

5. Using throws keyword:

Declares that a method may throw an exception, passing responsibility to the caller:

void readFile() throws IOException {

FileReader file = new FileReader("[Link]");

6. Key Points:
try block: code that may cause an exception.

catch block: handles the exception.

finally block: optional, always executes.

throw keyword: used to throw an exception manually.

throws keyword: used in method declaration to indicate potential exceptions.

7. Summary:

Exceptions help in gracefully handling runtime errors, ensuring that the program does not crash
and can recover or exit safely.

Explain layout manager in detail. Flow manager, grid manager.

Layout Manager in Java

1. Definition:

A layout manager is an object that controls the arrangement of components (buttons, labels,
text fields, etc.) in a container (like a JFrame or Panel).

It helps automatically organize components without manually setting their positions.

2. Purpose:

To manage the size and position of components in a container.

Ensures a GUI is responsive and looks good on different screen sizes.

3. Types of Layout Managers:

Java provides several layout managers, including FlowLayout, GridLayout, BorderLayout,


CardLayout, etc.

1. FlowLayout

1. Definition:

Arranges components in a row, left to right, like words in a paragraph.

When the row is full, components flow to the next line.

2. Characteristics:

Default alignment: center


Can be set to left or right alignment.

Components maintain their preferred size.

3. Example:

import [Link].*;

import [Link].*;

public class FlowExample {

public static void main(String[] args) {

JFrame f = new JFrame("FlowLayout Example");

[Link](new FlowLayout([Link]));

[Link](new Button("Button 1"));

[Link](new Button("Button 2"));

[Link](new Button("Button 3"));

[Link](300, 100);

[Link](true);

2. GridLayout

1. Definition:

Arranges components in a grid of rows and columns.

All cells have equal size, and components fill the entire cell.

2. Characteristics:

You can specify number of rows and columns.

Components are added row-wise (left to right, top to bottom).

3. Example:
import [Link].*;

import [Link].*;

public class GridExample {

public static void main(String[] args) {

JFrame f = new JFrame("GridLayout Example");

[Link](new GridLayout(2, 2)); // 2 rows, 2 columns

[Link](new Button("Button 1"));

[Link](new Button("Button 2"));

[Link](new Button("Button 3"));

[Link](new Button("Button 4"));

[Link](300, 200);

[Link](true);

Summary

Layout Manager​ Arrangement​ Key Feature

FlowLayout​ Row-wise, left to right. ​ Components flow to next line if space is full

GridLayout​ Grid of rows and columns​ All cells same size; components fill cell

Conclusion:

Layout managers like FlowLayout and GridLayout make GUI design flexible and organized,
avoiding manual positioning of components.
Write a program in Java to draw and fill a rectangle , polygons,line,using graphics class.

Here’s a Java program that uses the Graphics class to draw and fill a rectangle, polygon, and
line.

import [Link].*;

import [Link].*;

public class DrawShapes extends JPanel {

@Override

public void paintComponent(Graphics g) {

[Link](g);

// 1. Draw and Fill Rectangle

[Link]([Link]); // Set color for rectangle

[Link](50, 50, 150, 100); // Filled rectangle (x, y, width, height)

[Link]([Link]);

[Link](50, 50, 150, 100); // Outline rectangle

// 2. Draw Line

[Link]([Link]);

[Link](50, 200, 200, 300); // Line from (x1,y1) to (x2,y2)

// 3. Draw and Fill Polygon (Triangle)

int[] xPoints = {250, 300, 350};

int[] yPoints = {50, 150, 50};

[Link]([Link]);

[Link](xPoints, yPoints, 3); // Fill polygon

[Link]([Link]);

[Link](xPoints, yPoints, 3); // Outline polygon

}
public static void main(String[] args) {

JFrame frame = new JFrame("Draw Shapes Example");

DrawShapes panel = new DrawShapes();

[Link](panel);

[Link](500, 400);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

Explanation:

1. Rectangle

fillRect() → Fills a rectangle with color.

drawRect() → Draws the rectangle border.

2. Line

drawLine(x1, y1, x2, y2) → Draws a straight line between two points.

3. Polygon

fillPolygon(int[] x, int[] y, n) → Fills a polygon with n points.

drawPolygon(int[] x, int[] y, n) → Draws polygon outline.

4. JPanel and paintComponent

All drawing is done inside paintComponent(Graphics g) of a JPanel.

[Link](g) ensures proper repainting.


Write a short note on Java API packages.

Java API Packages

1. Definition:

A package in Java is a collection of related classes and interfaces grouped together.

The Java API (Application Programming Interface) provides a large set of pre-defined packages
for developers.

Packages help organize code, avoid name conflicts, and promote reusability.

2. Purpose of Packages:

Group related classes and interfaces.

Simplify program development by providing ready-to-use classes.

Help manage large applications efficiently.

Avoid naming conflicts by using package namespaces.

3. Types of Java Packages:

Built-in (Predefined) Packages: Provided by Java API.

User-defined Packages: Created by programmers to organize their own classes.

4. Common Java API Packages:

Package​ Purpose / Classes Example

[Link]​ Fundamental classes like String, Math, Object (automatically imported)

[Link]​ Utility classes like ArrayList, HashMap, Date

[Link]​ Input/Output classes like File, BufferedReader

[Link]​ Database handling classes like Connection, ResultSet

[Link]​ GUI classes like JButton, JFrame, JPanel

5. Importing Packages:

To use classes from a package, we import them:

import [Link];
import [Link].*;

6. Example:

import [Link];

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter your name:");

String name = [Link]();

[Link]("Hello, " + name);

Here, Scanner is from the [Link] package.

7. Summary:

Java API packages save development time, promote reusability, and organize code.

Using packages properly leads to cleaner, more manageable programs.

What is interface? How it is defined and used ?

Interface in Java

1. Definition:

An interface is a collection of abstract methods (methods without a body) and constants.

It is used to define a contract that a class must follow.

Interfaces are used to achieve multiple inheritance in Java.

2. Key Features:

All methods in an interface are implicitly public and abstract`.

All variables are implicitly public, static, and final.


A class implements an interface and provides concrete implementations of its methods.

3. Defining an Interface:

interface Drawable {

void draw(); // abstract method

4. Implementing an Interface in a Class:

class Circle implements Drawable {

public void draw() { // provide implementation

[Link]("Drawing a circle");

class Test {

public static void main(String[] args) {

Circle c = new Circle();

[Link](); // Output: Drawing a circle

5. Rules:

A class can implement multiple interfaces, e.g., class A implements X, Y.

If a class implements an interface, it must override all abstract methods.

6. Purpose / Advantages:

Achieves multiple inheritance safely.

Ensures standardization across classes.

Supports polymorphism; a reference of interface type can point to any implementing class.
7. Summary:

An interface is a blueprint of methods without implementation.

Defined using interface keyword and used by implementing classes to provide specific behavior.

Different types of container ( Frame,Dialog,Panel).

Containers in Java

1. Definition:

A container is a component that holds and organizes other GUI components like buttons, text
fields, and labels.

Containers can be top-level (like windows) or intermediate (like panels inside a window).

2. Types of Containers:

Java provides several container classes, including Frame, Dialog, and Panel.

1. Frame

Definition: A top-level window with a title, border, and close button.

Features:

Can hold menus, buttons, text fields, etc.

Can be resized, minimized, and maximized.

Example:

import [Link].*;

public class MyFrame {

public static void main(String[] args) {

Frame f = new Frame("My Frame");

[Link](400, 300);

[Link](true);

}
2. Dialog

Definition: A pop-up window used to take input or display messages.

Features:

Can be modal (blocks parent window) or non-modal.

Often used for alerts, confirmations, or forms.

Example:

import [Link].*;

public class MyDialog {

public static void main(String[] args) {

Frame f = new Frame();

Dialog d = new Dialog(f, "My Dialog", true); // modal dialog

[Link](200, 150);

[Link](true);

3. Panel

Definition: A lightweight container used to organize components inside other containers.

Features:

Cannot exist alone; must be added to a frame or dialog.

Supports layout managers for organizing components.

Example:

import [Link].*;

public class MyPanel {

public static void main(String[] args) {


Frame f = new Frame("Panel Example");

Panel p = new Panel();

Button b = new Button("Click Me");

[Link](b); // add button to panel

[Link](p); // add panel to frame

[Link](300, 200);

[Link](true);

Summary Table

Container​ Type​ Key Feature

Frame​ Top-level​ Main window, resizable, can hold menus

Dialog​ Top-level​ Pop-up window, can be modal or non-modal

Panel​ Intermediate. Organizes components, cannot exist alone


Explain AWT in Java?

AWT (Abstract Window Toolkit) in Java

1. Definition:

AWT is a Java package ([Link]) used to create Graphical User Interfaces (GUI).

It provides classes for windows, buttons, text fields, labels, menus, and other GUI components.

It is platform-dependent, meaning it uses the native GUI of the operating system.

2. Purpose of AWT:

To build GUI applications in Java.

To handle user interactions through events like clicks, key presses, or mouse movements.

3. AWT Components:

Containers: Frame, Dialog, Panel

Controls/Components: Button, Label, TextField, Checkbox, Choice

Layouts: FlowLayout, GridLayout, BorderLayout

Menus: MenuBar, Menu, MenuItem

4. Event Handling in AWT:

AWT supports event-driven programming.

Events are handled using listener interfaces like ActionListener, MouseListener, etc.

5. Advantages:

Easy to use for basic GUI applications.

Provides ready-to-use components.

6. Limitations:

Platform-dependent (looks different on Windows, Linux, Mac).

Less flexible and limited compared to Swing or JavaFX.

7. Example (AWT Button in Frame):


import [Link].*;

public class MyAWT {

public static void main(String[] args) {

Frame f = new Frame("AWT Example");

Button b = new Button("Click Me");

[Link](b); // add button to frame

[Link](300, 200);

[Link](true);

Summary:

AWT is Java’s original GUI toolkit.

Provides windows, controls, layouts, and event handling.

Useful for simple GUI applications, but less flexible than modern frameworks like Swing or
JavaFX.

You might also like