java 2024 (1)
java 2024 (1)
APRIL-2024
:- IIB (Instance Initialization Block): It is a block of code inside a class that runs
whenever an object of the class is created, before the constructor execution.
Private
Protected
import java.util.Scanner;
Static Import: Allows accessing static members directly without using the
class name.
Example:
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark!");
}
}
Here are the answers to the given questions:
Character Stream handles character data (text) and uses classes like FileReader and
FileWriter.
Byte Stream handles binary data (images, audio, etc.) and uses classes like
FileInputStream and FileOutputStream.
Daemon Thread: Runs in the background, supporting other threads (e.g., Garbage
Collector).
When no layout manager is used, components must be placed manually using absolute
positioning with setBounds(x, y, width, height). This approach is known as null layout.
The <applet> tag in HTML is used to embed Java applets in a web page. It specifies
parameters like code, width, and height for loading an applet.
Example:
<applet code=”MyApplet.class” width=”300” height=”200”></applet>
:-javax.swing
:-Lightweight components
import javax.swing.*;
public class TextFieldExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
JTextFieldtextField = new JTextField("Enter text here", 20);
frame.add(textField);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
1. JComboBox:
JComboBox is a drop-down menu in Swing that allows users to select one item
from a list.
Example:
import javax.swing.*;
public class ComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");
String[] options = {"Apple", "Banana", "Cherry"};
JComboBox<String>comboBox = new JComboBox<>(options);
frame.add(comboBox);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
Primitive data types are the most basic type of data in Java. They are predefined by the
language and represent simple values like numbers, characters, or booleans. There are
8 primitive data types in Java:
byte:
o Size: 1 byte (8 bits)
o Range: -128 to 127
o Example: byte a = 100;
short:
o Size: 2 bytes (16 bits)
o Range: -32,768 to 32,767
o Example: short b = 5000;
int:
o Size: 4 bytes (32 bits)
o Range: -2^31 to 2^31-1 (approximately -2 billion to +2 billion)
o Example: int c = 100000;
long:
o Size: 8 bytes (64 bits)
o Range: -2^63 to 2^63-1 (very large range)
o Example: long d = 10000000000L; (Note the "L" at the end)
float:
o Size: 4 bytes (32 bits)
o Range: ±3.40282347E+38F (7 decimal digits)
o Used for representing decimal numbers (single precision)
o Example: float e = 10.5f; (Note the "f" at the end)
double:
o Size: 8 bytes (64 bits)
o Range: ±1.7976931348623157E+308 (15 decimal digits)
o Used for representing decimal numbers (double precision)
o Example: double f = 3.14159;
char:
o Size: 2 bytes (16 bits)
o Range: 0 to 65,535 (Unicode characters)
o Used for storing single characters or symbols
o Example: char g = 'A';
boolean:
o Size: 1 bit (though JVM may use a byte for it)
o Values: true or false
o Example: boolean h = true;
2. Reference Data Types
Reference data types are more complex than primitive data types. They store
references (or memory addresses) to the actual data. These include objects, arrays,
and interfaces.
Objects: An object is an instance of a class. In Java, a class defines the
structure and behavior of an object. Reference types store the memory address
of the object.
o Example:
String str = "Hello, World!";
Arrays: An array is a collection of elements of the same type. The array itself is a
reference data type, which points to the memory location of the array elements.
o Example:
int[] numbers = {1, 2, 3, 4, 5};
Key Differences Between Primitive and Reference Data Types:
int a =
Example String str = "Hello";
10;
(2)1.Explain method overriding with example
Let's say we have a superclass called Animal, and a subclass called Dog. Both classes
have a method sound(), but we want the Dog class to implement its own version of
sound().
// Method in superclass
void sound() {
}
// Subclass (Child class)
@Override
void sound() {
System.out.println("Bark");
}
}
Output:
rust
Copy
Some generic animal sound
Bark
Bark
Explanation:
1. Superclass Method: In the Animal class, we define a method sound() that prints
"Some generic animal sound."
2. Subclass Method: In the Dog class, we override the sound() method. When
sound() is called on a Dog object, it prints "Bark" instead of the generic message
from Animal.
3. Using Reference of Superclass: In the Main class, when we use a reference of
type Animal but create an object of Dog, the overridden method in the Dog class
is called. This is an example of runtime polymorphism where the method call is
resolved at runtime based on the actual object type (Dog), not the reference type
(Animal).
Important Points:
Method Overloading vs. Method Overriding:
o Method overloading occurs when two or more methods have the same
name but different parameters (different number or type of parameters).
o Method overriding occurs when a method in the subclass has the same
signature as a method in the superclass and provides a new
implementation.
Super Keyword: If you want to call the overridden method in the superclass from
the subclass, you can use the super keyword.
o Example:
@Override
void sound() {
System.out.println("Bark");
}
Benefits of Method Overriding:
Dynamic Polymorphism: It allows different behaviors for the same method
depending on the type of object.
Code Reusability: You can reuse code from the superclass and modify its
behavior in the subclass as needed.
Flexibility: It provides flexibility to extend or modify behavior without altering the
existing superclass code.
Method overriding is fundamental for building flexible and maintainable object-oriented
programs where subclasses can provide specific behavior for inherited methods.
Example:
public class MathExample {
// Absolute Value
int a = -10;
double absValue = Math.abs(a);
double base = 2;
double exponent = 3;
System.out.println(base + " raised to the power of " + exponent + " is: " + power);
// Square Root
double number = 16;
double x = 5.5;
double y = 7.2;
// Round
When it occurs: A thread is in this state immediately after it is created using the
Thread class or implementing the Runnable interface.
How it happens: You create a thread instance but it hasn’t started running yet.
Example:
Key Point: The thread is just an object here, not yet executing any code.
2. Runnable State
When it occurs: After calling the start() method, the thread moves to the
runnable state. The thread is now ready to run but may not start immediately
because of thread scheduling by the OS.
How it happens: The thread is waiting for CPU time to execute.
Example:
t.start();
Key Point: The thread scheduler decides when the thread actually runs, based
on priority, CPU availability, etc.
3. Running State
When it occurs: The thread is actively executing its task. This is a subset of the
runnable state where the thread is actually running.
How it happens: The CPU assigns time to the thread, and the thread's run()
method executes.
Key Point: A thread may not run continuously—it can be preempted by other
threads.
4. Blocked State
synchronized (lock) {
// Critical section
}
Key Point: The thread cannot proceed until the lock is released.
5. Waiting State
Key Point: The thread remains in this state until another thread explicitly wakes
it up.
Key Point: After the specified time, the thread automatically moves back to the
runnable state.
7. Terminated (Dead) State
When it occurs: A thread has completed its execution or has been terminated
due to an exception.
How it happens: The run() method has finished executing, or an unhandled
error caused the thread to stop.
Key Point: The thread cannot be restarted once it has terminated.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
int bytesRead;
try (
){
} catch (IOException e) {
}
}
printf("enter %d number:")
scanf("%d",n)
getch();
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 150);
frame.setLayout(null);
// Create a button
@Override
});
frame.add(messageBox);
frame.add(displayButton);
frame.setVisible(true);
}
}
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
Example
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Output :
This animal eats food.
The dog barks.
Explanation:
Animal is the base class with a method eat().
Dog is the derived class that extends Animal and has its own
method bark().
In the main method, we create an instance of Dog and call
both the inherited method eat() and the bark() method
defined in the Dog class.
Java InheritanceTypes:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one
super class.
It inherits the properties and behavior of a single-parent
class. Sometimes, it is also known as simple inheritance.
2. Multilevel Inheritance
3. Hierarchical Inheritance
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
myDog.eat();
myDog.bark();
myCat.eat();
myCat.meow();
}
}
Output:
This animal eats food.
The dog barks.
This animal eats food.
The cat meows.
4. Multiple Inheritance
In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes.
Java does not support multiple inheritances with classes.
In Java, we can achieve multiple inheritances only through
Interfaces.
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance.
Since Java doesn’t support multiple inheritances with
classes, hybrid inheritance involving multiple inheritance is
also not possible with classes.
In Java, we can achieve hybrid inheritance only through
Interface if we want to involve multiple inheritance to
implement Hybrid inheritance.
inheritance does not necessarily require the use of Multiple
Inheritance exclusively.
It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes,
Hierarchical and Single Inheritance with classes.
Therefore, it is indeed possible to implement Hybrid
inheritance using classes alone, without relying on multiple
inheritance type.
Code Reusability
Abstraction
Class Hierarchy
Polymorphism
Complexity
Overriding Issues
2. Different Parameters:
3. Compile-Time Polymorphism:
Example:
class MathOperations {
int add(int a, int b) {
return a + b;
}
Code Clarity:
By using the same method name for similar operations, the
code becomes easier to read and understand.
Reduced Complexity:
It reduces the need for multiple method names, which can
clutter the codebase.
Flexibility:
We can create methods that handle various data types and
numbers of parameters, making the code more versatile.
Limitations of Method Overloading:
Ambiguity:
If not designed carefully, overloaded methods can lead to
ambiguity, especially if the parameters are of similar types.
1. Nested Class:
Example:
class Outer {
static int outerStaticVar = 100;
2. Inner Class:
Key Points:
Example:
interface Animal {
void eat();
void sleep();
}
interface Swim {
void swim();
}
dolphin.eat();
dolphin.sleep();
dolphin.swim();
}
}
Explanation:
Animal Interface: This interface defines two methods
eat() and sleep(). These are the behaviors common to
all animals.
Swim Interface: This interface defines the swim()
method, which specifies the swimming behavior
Conclusion:
Multiple inheritance is not supported directly via classes
in Java to avoid ambiguity.
At this point, the thread is not yet started, and the start()
method has not been called.
2. Runnable (Ready to run) State
In this state, the thread will wake up either after the specified
time has passed or when notified (depending on the method
used).
Key Notes:
3(2). Write a program to copy data of one file into another file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
int byteData;
fis.close();
fos.close();
GridLayout in Java
You can also specify the gap between components using the
constructor:
Example:
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
submitButton.setOnAction(e -> {
String username = userTextField.getText();
String password = passField.getText();
System.out.println("Username: " + username);
System.out.println("Password: " + password);
});
clearButton.setOnAction(e -> {
userTextField.clear();
passField.clear();
});
Output: