0% found this document useful (0 votes)
13 views14 pages

Java (2023 24)

The document discusses various Java programming concepts including compile-time polymorphism, copy constructors, JButton subclasses, event delegation in AWT, the super keyword, string comparison methods, creating a package, user-defined exceptions, and thread life cycle. It provides explanations, examples, and code snippets for each topic. The content is aimed at enhancing understanding of Java programming principles and practices.

Uploaded by

Sona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views14 pages

Java (2023 24)

The document discusses various Java programming concepts including compile-time polymorphism, copy constructors, JButton subclasses, event delegation in AWT, the super keyword, string comparison methods, creating a package, user-defined exceptions, and thread life cycle. It provides explanations, examples, and code snippets for each topic. The content is aimed at enhancing understanding of Java programming principles and practices.

Uploaded by

Sona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Java(2023-24)

2(a) What is compile time polymorphism and its importance? Use the
compile time polymorphism in the Java program to create the objects

Answer:-

Compile-time polymorphism, also known as static polymorphism or early


binding, is a type of polymorphism in which the method or function to be
executed is determined at compile time. This is achieved through method
overloading, where multiple methods in the same class have the same name
but different signatures (different number or types of parameters).

Importance:

 Allows defining multiple behaviors for the same method name.


 Makes the program easier to understand and maintain.
 Enables cleaner code with reduced method naming clutter.

Example:-

Class Calculator {

// Method to add two integers

Int add(int a, int b) {

Return a + b;

// Method to add three integers

Int add(int a, int b, int c) {

Return a + b + c;

// Method to add two doubles

Double add(double a, double b) {

Return a + b;

Public class Main {


Public static void main(String[] args) {

Calculator calculator = new Calculator();

// Calls the add(int, int) method

Int sum1 = calculator.add(2, 3);

System.out.println(“Sum of 2 and 3: “ + sum1);

// Calls the add(int, int, int) method

Int sum2 = calculator.add(1, 2, 3);

System.out.println(“Sum of 1, 2, and 3: “ + sum2);

// Calls the add(double, double) method

Double sum3 = calculator.add(2.5, 3.5);

System.out.println(“Sum of 2.5 and 3.5: “ + sum3);

2(c) Why can’t we pass an object by value to copy a constructor? Explain


with example

Answer :-

A copy constructor in Java is used to create a new object as a copy of an


existing object of the same class. It’s not possible to pass an object by value
to a copy constructor because it would lead to infinite recursion.

When an object is passed by value, a copy of the object is created. In the


context of a copy constructor, this would mean that to call the copy
constructor, a copy of the object needs to be created first, which in turn calls
the copy constructor again, and so on, leading to an infinite loop and
eventually a stack overflow error.
Instead, a copy constructor accepts a reference to an object of the same
class. This allows the constructor to access the original object’s data without
creating a new copy, thus avoiding the infinite recursion problem.

Example:-

Class MyClass {

Int value;

Public MyClass(int value) {

This.value = value;

// Copy constructor

Public MyClass(MyClass other) {

This.value = other.value;

Public static void main(String[] args) {

MyClass obj1 = new MyClass(10);

MyClass obj2 = new MyClass(obj1); // Calling the copy constructor

System.out.println(obj1.value); // Output: 10

System.out.println(obj2.value); // Output: 10

In this example, the copy constructor MyClass(MyClass other) takes a


reference to MyClass object, allowing obj2 to be created as a copy of obj1
without causing recursion.
(D)What are the subclasses of jbutton class of Swing package. Give an
example

Answer:-

The direct known subclasses of JButton in the Swing package are


BasicArrowButton and MetalComboBoxButton. AbstractButton is the parent
class of both JButton and other button types like JToggleButton, JCheckBox,
and JRadioButton.

Example:-

Import javax.swing.JButton;

Import javax.swing.JFrame;

Import javax.swing.JPanel;

Import javax.swing.JLabel;

Import java.awt.BorderLayout;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;

Public class ButtonExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“JButton Example”);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Frame.setSize(300, 200);

Frame.setLayout(new BorderLayout());

JPanel panel = new JPanel();

JButton button = new JButton(“Click Me”);

// Add action listener to the button

Button.addActionListener(new ActionListener() {
@Override

Public void actionPerformed(ActionEvent e) {

// Code to execute when the button is clicked

System.out.println(“Button clicked!”);

JLabel label = new JLabel(“Button clicked”);

Frame.add(label, BorderLayout.SOUTH);

Frame.revalidate();

Frame.repaint();

});

Panel.add(button);

Frame.add(panel, BorderLayout.CENTER);

Frame.setVisible(true);

In this example:

 JButton button = new JButton(“Click Me”); creates a JButton with the


text “Click Me”.
 Button.addActionListener(new ActionListener() { ... }); adds an action
listener to the button. When the button is clicked, the code within the
actionPerformed method will be executed.
 The JFrame displays the JButton in a simple window.

This example demonstrates the basic usage of JButton and how to handle
button clicks using an ActionListener

(E) Write an AWT program to create a Frame and close the frame using event Delegation model.
Answer:-

Import java.awt.*;

Import java.awt.event.*;
Public class FrameClose extends Frame {

Public FrameClose() {

setTitle(“Frame Close Example”);

setSize(300, 200);

setVisible(true);

addWindowListener(new WindowAdapter() {

@Override

Public void windowClosing(WindowEvent e) {

Dispose(); // Close the frame

System.exit(0); // Terminate the application

});

Public static void main(String[] args) {

New FrameClose();

(F) With the help of Java programs, explain the different use of 'super
keyword.

Answer:-

The super keyword in Java is used to refer to the superclass (parent class) of
the current class. It’s primarily used in three scenarios: accessing superclass
members (variables and methods), calling superclass constructors, and
resolving naming conflicts between superclass and subclass members.

1. Accessing Superclass Members: When a subclass has a member


(variable or method) with the same name as its superclass, super can
be used to access the superclass's version.
e.g:-
class Animal {
String name = "Animal";
void eat() {
System.out.println("Animal is eating");
}
}

cplass Dog extends Animal {


String name = "Dog";
void eat() {
System.out.println("Dog is eating");
}
void display() {
System.out.println("Name from superclass: " + super.name); //
Accessing superclass variable
System.out.println("Name from subclass: " + name);
super.eat(); // Accessing superclass method
eat(); // Accessing subclass method
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.display();
}
}
2. Calling Superclass Constructor s: super() is used to call the superclass’s
constructor from a subclass constructor. It’s crucial for initializing
inherited members. If a subclass constructor doesn’t explicitly call
super(), Java automatically inserts a call to the superclass’s no-
argument constructor.
e.g:-
class Vehicle {

String model;

Vehicle(String model) {

This.model = model;

System.out.println(“Vehicle constructor called”);

Class Car extends Vehicle {

String color;

Car(String model, String color) {

Super(model); // Calling superclass constructor

This.color = color;

System.out.println(“Car constructor called”);

Void display() {

System.out.println(“Model: “ + model + “, Color: “ + color);

Public class Main {

Public static void main(String[] args) {

Car car = new Car(“Sedan”, “Red”);

Car.display();

}
3. Resolving Naming Conflicts: super helps differentiate between
members of the superclass and subclass when they have the same
name, preventing ambiguity. This is particularly useful when a subclass
overrides a method from its superclass.
e.g:-
class A {
void display() {
System.out.println(“Class A display”);
}
}

Class B extends A {
Void display() {
System.out.println(“Class B display”);
}
Void show() {
Super.display(); // Calling superclass method
Display(); // Calling subclass method
}
}

Public class Main {


Public static void main(String[] args) {
B b = new B();
b.show();
}
}

(G) Discuss the methods of string comparsion with eexample


Answer:-
String comparison in Java involves evaluating the relationship between two strings. Several
methods facilitate this, each with distinct functionalities:
 equals(): This method checks for exact equality between two strings, considering case
sensitivity.
e.g:- String str1 = “Hello”;
String str2 = “Hello”;
String str3 = “hello”;

System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // false
 equalsIgnoreCase(): Similar to equals(), but ignores case differences.
e.g:- String str1 = “Hello”;
String str3 = “hello”;

System.out.println(str1.equalsIgnoreCase(str3)); // true
 compareTo(): Compares two strings lexicographically (based on Unicode values).
o It returns:0 if the strings are equal.
o A negative value if the first string is lexicographically less than the second.
o A positive value if the first string is lexicographically greater than the second.
e.g:- String str1 = “apple”;
String str2 = “banana”;
String str3 = “apple”;

System.out.println(str1.compareTo(str2)); // Negative value


System.out.println(str2.compareTo(str1)); // Positive value
System.out.println(str1.compareTo(str3)); // 0
 compareToIgnoreCase():Performs a lexicographical comparison, ignoring case
differences.
e.g:- String str1 = “Apple”;
String str3 = “apple”;

System.out.println(str1.compareToIgnoreCase(str3)); // 0
 regionMatches():Compares specific regions of two strings. It offers flexibility with case
sensitivity.
e.g:- String str1 = “Hello World”;
String str2 = “World”;

System.out.println(str1.regionMatches(6, str2, 0, 5)); // true (case-sensitive)


System.out.println(str1.regionMatches(true, 6, str2, 0, 5)); // true (case-insensitive)
 startsWith() and endsWith(): These methods check if a string begins or ends with a
specified prefix or suffix, respectively.
e.g:- String str1 = “Hello World”;

System.out.println(str1.startsWith(“Hello”)); // true
System.out.println(str1.endsWith(“World”)); // true

(H) Develop a java package named 'envelope package' with a class Even containing a static
method that checks whether the number is even or not and returns that information. Import this
package in an another class and used to check a number is Even or odd
Answer:-
Step 1: Create the Package and Class

File: Even.java (inside folder envelopepackage)


Package envelopepackage;

Public class Even {


// Static method to check if a number is even
Public static boolean isEven(int number) {
Return number % 2 == 0;
}
}
Step 2: Create Another Class to Use the Package

File: TestEven.java

Import envelopepackage.Even; // Importing the custom package

Public class TestEven {


Public static void main(String[] args) {
Int num = 15;

If (Even.isEven(num)) {
System.out.println(num + “ is Even”);
} else {
System.out.println(num + “ is Odd”);
}
}
}

(I) Create a user defined exception as ‘InvalidAgeException’. Write Java program that
takes a does a common line argument.Raise the Exception “InvalidAgeException’ if
age is less than 18
Answer:-
Step 1: Create the Custom Exception
// File: InvalidAgeException.java
Public class InvalidAgeException extends Exception {
Public InvalidAgeException(String message) {
Super(message);
}
}
Step 2: Main Program to Use the Exception
// File: AgeCheck.java
Public class AgeCheck {
Public static void main(String[] args) {
Try {
If (args.length == 0) {
System.out.println(“Please provide age as a command-line argument.”);
Return;
}

Int age = Integer.parseInt(args[0]);

If (age < 18) {


Throw new InvalidAgeException(“Age is less than 18 — Not allowed.”);
} else {
System.out.println(“Valid age: “ + age);
}
} catch (InvalidAgeException e) {
System.out.println(“Exception: “ + e.getMessage());
} catch (NumberFormatException e) {
System.out.println(“Please enter a valid number.”);
}
}
}

(J) What do youunderstand by thread? Describe the complete life cycle of a thread.
Answer:-
What is a Thread in Java?

A thread is a lightweight subprocess, the smallest unit of execution in a program. Java allows
concurrent execution of two or more threads, enabling multitasking. Each thread runs
independently but shares the same memory space of the process.

You can create threads in Java by:

Extending the Thread class

Implementing the Runnable interface


Life Cycle of a Thread in Java
A thread goes through the following states during its lifetime:

1. New

The thread is created using new Thread().

It is not yet started.

Thread t = new Thread();


2. Runnable

The thread is ready to run after start() is called.

It may be waiting in the queue for CPU time.

t.start();

3. Running

The thread is actually executing.

The scheduler picks it from the Runnable pool and executes it.

4. Blocked/Waiting

The thread is waiting for a resource (e.g., I/O, lock, or condition).

It cannot proceed until some other thread notifies or releases the resource.

5. Timed Waiting

The thread is waiting for a specified time using methods like:

Sleep(time)

Join(time)
Wait(time)

6. Terminated (Dead)

The thread has finished execution or has been stopped due to an exception.
e.g:-
class MyThread extends Thread {
public void run() {
System.out.println(“Thread is running...”);
}
}

Public class ThreadExample {


Public static void main(String[] args) {
MyThread t1 = new MyThread(); // New
T1.start(); // Runnable → Running
}
}

You might also like