Java Programming / U20CSCJ05
UNIT-1
PART-A
The JVM has these key functions:
- Loads Java bytecode: Reads
.classfiles and loads them into memory.
- Executes Java programs: Converts bytecode to native machine code via the Just-In-Time (JIT) compiler.
- Memory management: Handles garbage collection and memory allocation.
- Platform independence: Ensures Java programs run identically across platforms.
- Exception handling: Provides runtime error-handling mechanisms.
2. Object and Class in Java
- Object: An instance of a class containing state (attributes) and behavior (methods).
- Class: A blueprint or template for creating objects. Example:
3. Anonymous Object
- An object without a reference. Used when the object is needed only once.
Example: - new Car().drive(); // Calls the drive() method without storing the object reference.
equals() vs == in Java5. Check Perfect Square (Java Program)
import java.util.Scanner;
public class PerfectSquare {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sqrt = (int)Math.sqrt(num);
if (sqrt * sqrt == num) {
System.out.println(num + " is a perfect square.");
} else {
System.out.println(num + " is not a perfect square.");
}
}
}
6. Features of Java Programming
- Platform Independent: Code runs anywhere via JVM.
- Object-Oriented: Supports principles like encapsulation, inheritance, etc.
- Robust: Provides strong memory management and error handling.
- Secure: Includes runtime checks and no explicit pointer access.
- Multithreaded: Allows concurrent execution of threads.
7. Instance Variable in Java
- A variable declared in a class but outside any method.
- Unique to each object and initialized with default values.
Example: - class Student {
- int rollNo; // Instance variable
}
8. Ways to Initialize an Object in Java
9. Constructors vs Methods in Java
10. Static Method Example
class MathUtil {
static int square(int num) {
return num * num;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Square of 5: " + MathUtil.square(5));
}
}
UNIT-1
PART-B
1. Explain history of Java in detail.
History of Java in Detail
Java is one of the most influential programming languages, with its development rooted in the goal of creating a platform-independent language. Below is a detailed timeline of its history:
Early Beginnings (1990–1991)
- Initiated by Sun Microsystems: A project called "The Green Project" was started by a team led by James Gosling, along with Mike Sheridan and Patrick Naughton.
- Objective: The goal was to create a language for embedded devices like set-top boxes and televisions.
- Initial Language: They first created a language called Oak (named after an oak tree outside Gosling’s office).
- Oak failed to gain traction in the embedded systems market due to hardware limitations and competition.
Renaming to Java (1994)
- Rebranding: The team realized that their language could be better utilized for internet programming. Oak was renamed Java, inspired by Java coffee, reflecting energy and innovation.
- Shift in Focus: With the rise of the World Wide Web, they focused on developing a platform-independent language that could run on any machine with a browser.
Java Today
- Applications: Java powers applications across domains like banking, e-commerce, mobile (via Android), and big data (Apache Hadoop).
- Community Support: It remains one of the most popular languages, supported by a vast community and numerous libraries/frameworks.
Why Java Remains Important
- Platform Independence: Enabled by the JVM.
- Security: Features like sandboxing and runtime checks.
- Enterprise Ready: Frameworks like Spring and Hibernate.
- Adaptability: Evolved to support modern programming paradigms.
2 .Demonstrate the creation of an object and class in Java
Code Explanation
Class Declaration:
- A class is a blueprint for creating objects.
- It can contain:
- Fields (attributes): Variables to hold data.
- Methods: Define the behavior.
Object Creation:
- An object is an instance of a class, created using the
newkeyword.
o/p:
Brand: Toyota
Color: Red
Speed: 120 km/h
3. Show a program to find duplicate characters in a string.
import java.util.HashMap;
public class DuplicateCharacters {
public static void main(String[] args) {
// Input string
String input = "programming";
// Convert the string to lowercase to ensure case insensitivity
input = input.toLowerCase();
// Create a HashMap to store character counts
HashMap<Character, Integer> charCountMap = new HashMap<>();
// Loop through the string to count occurrences of each character
for (char c : input.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Display characters that occur more than once
System.out.println("Duplicate characters in the string:");
for (HashMap.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " -> " + entry.getValue() + " times");
}
}
}
}
4. Method Overloading
i) By Changing the Number of Arguments
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of 2 numbers: " + calc.add(5, 10));
System.out.println("Sum of 3 numbers: " + calc.add(5, 10, 15));
}
}
ii) By Changing the Data Type of Arguments
class Calculator {
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Product of integers: " + calc.multiply(5, 10));
System.out.println("Product of doubles: " + calc.multiply(5.5, 10.5));
}
}
5. Differences Between Predefined and User-Defined Methods
public static void main(String[] args) {
// Predefined method
System.out.println("Square root of 16: " + Math.sqrt(16));
// User-defined method
int length = 5, width = 10;
System.out.println("Area of rectangle: " + calculateArea(length, width));
}
static int calculateArea(int length, int width) {
return length * width;
}
}
6. Instance Method Example
7. String Class Methods
i) compareTo()
public class StringCompare {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
System.out.println(str1.compareTo(str2)); // Output: Negative value
}
}
ii) concat()
public class StringConcat {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";
System.out.println(str1.concat(str2)); // Output: Hello World
}
}
8. Static Method Example
10. Demonstrate Java String Class Methods with an Example
The String class in Java provides many useful methods for string manipulation. Some commonly used methods are length(), substring(), toUpperCase(), toLowerCase(), charAt(), and replace().
Example
1. Explain JVM Architecture with a Neat Sketch
The Java Virtual Machine (JVM) is a critical part of the Java Runtime Environment (JRE). It acts as an abstract machine to execute Java bytecode.
Detailed Components of JVM Architecture:
Class Loader Subsystem:
- Loads
.classfiles into the JVM. - Performs linking (verification, preparation, resolution) and initialization.
- Loads
Method Area:
- Stores metadata of loaded classes, constants, static variables, and the code for methods.
Heap:
- The runtime data area where objects and their related instance variables are stored.
Stack:
- Each thread gets its own JVM stack to store frames (method call information).
Program Counter (PC) Register:
- Holds the address of the current instruction being executed.
Native Method Stack:
- Manages native methods written in languages like C/C++.
Execution Engine:
- Executes bytecode.
- Includes:
- Interpreter: Executes bytecode line by line.
- JIT Compiler: Converts frequently executed bytecode into native code for faster execution.
Java Native Interface (JNI):
- Enables interaction between Java applications and native libraries.
Native Libraries:
- Provides native code implementations required for the execution of Java programs.
Advantages of JVM:
- Platform independence.
- Automatic memory management via garbage collection.
Sketch of JVM Architecture:
2. Demonstrate the Constructor Types in Detail
i) Default Constructor
A no-argument constructor provided by Java if no constructor is defined.
ii) Parameterized Constructor
iii) Copy Constructor
3. Illustrate the 3 Ways of Initializing an Object in Java
new Keyword and Dot Notation: Assign values to fields manually.4. Outline String Handling in Java
String handling in Java involves manipulating strings using the String class and its methods. Strings are immutable objects in Java.
Common String Methods:
- length(): Returns the length of the string.
- substring(): Extracts a portion of the string.
- toUpperCase() and toLowerCase(): Converts the case of the string.
- replace(): Replaces characters or substrings.
- charAt(): Returns a character at a specific index.
- concat(): Concatenates two strings.
5. Show the Use of Overloading Methods in Detail
- Number of parameters.
- Type of parameters.
- Order of parameters.
Use of Overloading:
- Improves code readability by providing a consistent method name for similar tasks.
- Reduces the need to use separate method names for related operations.
- Enhances flexibility for developers to define methods for different use cases.
Key Points:
- Method overloading is determined during compile-time.
- It only works within the same class or inherited classes.
- Return type alone cannot distinguish overloaded methods (must vary in parameters).
i) Pass by Value
1. Pass by Value
- Java always uses pass by value for method parameters.
- The method receives a copy of the variable’s value, and changes inside the method do not affect the original variable.
ii) Pass by Reference
*Changes made to the object inside the method are reflected outside the method because both the original and the method parameter point to the same object in memory.
7. Explain Methods in Java with Examples
In Java, methods are blocks of code designed to perform specific tasks. They enhance code reusability, modularity, and readability. A method is executed when it is called or invoked.
Types of Methods in Java
1. Instance Methods
- Belong to an object of the class.
- Require an instance of the class to be invoked.
Example:
class InstanceMethodExample {
// Instance method
void greet() {
System.out.println("Hello from an instance method!");
}
public static void main(String[] args) {
InstanceMethodExample obj = new InstanceMethodExample();
obj.greet(); // Calling the instance method
}
}
o/p:
Hello from an instance method!
2. Static Methods
- Belong to the class, not a specific object.
- Can be called directly using the class name without creating an object.
3. Parameterized Methods
- Accept parameters to provide input for the method’s operation.
Example:class ParameterizedMethodExample {
// Method with parameters
void add(int a, int b) {
System.out.println("Sum: " + (a + b));
}
public static void main(String[] args) {
ParameterizedMethodExample obj = new ParameterizedMethodExample();
obj.add(10, 20); // Passing arguments to the method
}
}
4. Method with Return Value
- A method can return a value using the
returnkeyword.
Example:class ReturnMethodExample {
// Method that returns a value
int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
ReturnMethodExample obj = new ReturnMethodExample();
int result = obj.multiply(5, 4);
System.out.println("Product: " + result);
}
}
5. Overloaded Methods
- Same method name but different parameter lists (either by type, number, or order of parameters).
Example:
Example:class Animal { }
class Dog extends Animal { }
Multilevel Inheritance: A class inherits from a subclass, forming a chain.
Example:class Animal { }
class Dog extends Animal { }
class Puppy extends Dog { }
Hierarchical Inheritance: Multiple classes inherit from a single superclass.
Example:class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
Multiple Inheritance (via Interface): A class implements multiple interfaces.
Example:interface Animal { void sound(); }
interface Mammal { void walk(); }
class Dog implements Animal, Mammal {
public void sound() { System.out.println("Dog barks"); }
public void walk() { System.out.println("Dog walks"); }
}
Answer: Polymorphism is the ability of an object to take many forms. It allows one entity to be represented in multiple ways. There are two main types of polymorphism in Java:
Compile-time Polymorphism (Method Overloading): Occurs when multiple methods have the same name but different parameter lists (number or type of parameters).
Example:class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
Runtime Polymorphism (Method Overriding): Occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Example:class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}
- An abstract class is a class that cannot be instantiated on its own. It can have abstract methods (without implementation) and concrete methods (with implementation).
- Rules for abstract class:
- It can contain abstract methods (methods without a body).
- It can also contain non-abstract methods (methods with a body).
- If a class contains abstract methods, it must be declared as abstract.
- A subclass of an abstract class must provide implementations for all abstract methods unless the subclass is also abstract.
Example:abstract class Animal {
// Abstract method (no implementation)
abstract void sound();
// Regular method
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
// Providing implementation for abstract method
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class TestAbstractClass {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Dog barks
dog.eat(); // This animal eats food
}
}
Advantages of Object Cloning
Deep Copy Creation:
Object cloning creates an exact replica of the original object. This includes the copying of the object’s fields, which can be useful when you need to preserve the state of an object at a specific point in time.Convenience:
Implementingclone()through theCloneableinterface in Java, for instance, avoids repetitive coding. Instead of manually copying each field, you can use theclone()method for quick duplication.Performance:
Cloning can be faster than manually creating a new object and copying all field values, especially for objects with many fields or nested objects.Reduces Error Risk:
When an object is cloned, the exact state is copied, reducing the chance of missing fields during a manual copy operation.Preserves Encapsulation:
Cloning ensures that internal implementation details (private fields) are not exposed, unlike when a copy constructor or method is used where field values might need to be explicitly passed.
Disadvantages of Object Cloning
Shallow Copy Issues:
Default cloning in Java (viaObject.clone()) creates a shallow copy. This means that if the object contains references to other objects, those references are copied, not the actual objects, which can lead to shared mutable state issues.Complexity with Deep Copy:
Implementing a deep copy via cloning requires significant effort. If the object has nested references or collections, you need to ensure that all referenced objects are also cloned.Fragile and Error-Prone:
TheCloneableinterface andclone()method are considered poorly designed in Java. They can lead to subtle bugs if not used carefully, such as failing to callsuper.clone()in subclass overrides.Performance Overhead:
Object cloning can be slower compared to custom copy constructors, particularly for objects with complex or large graphs of fields.Dependency on
Cloneable:
The object must implement theCloneableinterface; otherwise,clone()throws aCloneNotSupportedException. This dependency can make design rigid and inflexible.No Constructor Invocation:
Cloning bypasses the constructor, so initialization logic in the constructor is not executed, potentially leading to objects in an inconsistent state.
Key Features of Java Interfaces
Abstract Methods:
An interface can have methods that are implicitlypublicandabstract. Starting with Java 8, it can also have:- Default methods: Methods with a body, which can be overridden by implementing classes.
- Static methods: Methods with a body, callable using the interface name.
Fields:
Fields in an interface are implicitlypublic,static, andfinal(constants).Multiple Inheritance:
A class can implement multiple interfaces, overcoming the limitation of single inheritance in Java.interface Flyable {
void fly();
}
interface Swimable {
void swim();
}
class Bird implements Flyable, Swimable {
public void fly() {
System.out.println("Bird flies");
}
public void swim() {
System.out.println("Bird swims");
}
}
public class MultipleInterfaces {
public static void main(String[] args) {
Bird bird = new Bird();
bird.fly();
bird.swim();
}
}
Polymorphism:
Interfaces support dynamic method dispatch, enabling polymorphic behavior.interface InterfaceName {
// abstract method
void abstractMethod();
// default method
default void defaultMethod() {
System.out.println("This is a default method.");
}
// static method
static void staticMethod() {
System.out.println("This is a static method.");
}
// constant
int CONSTANT_VALUE = 100; // public, static, final
}
UNIT-2PART-C1.Explain the different types of inheritance with neat structure.Types of Inheritance in Java
Inheritance is a key concept in object-oriented programming that allows one class (child class) to inherit the properties and methods of another class (parent class). It helps in code reusability and method overriding.
Types of Inheritance
- Single Inheritance
A child class inherits from a single parent class.
Structure:
Parent Class↑Child ClassExample:class Parent {void display() {System.out.println("This is the Parent class.");}}class Child extends Parent {void show() {System.out.println("This is the Child class.");}}public class SingleInheritanceExample {public static void main(String[] args) {Child child = new Child();child.display();child.show();}}Output: This is the Parent class.This is the Child class.Multilevel Inheritance- A class inherits from another class, which is itself a child of another class.
Structure:
Grandparent Class↑Parent Class↑Child Classcode:class Grandparent {void greet() {System.out.println("Hello from Grandparent!");}}class Parent extends Grandparent {void welcome() {System.out.println("Hello from Parent!");}}class Child extends Parent {void hello() {System.out.println("Hello from Child!");}}public class MultilevelInheritanceExample {public static void main(String[] args) {Child child = new Child();child.greet();child.welcome();child.hello();}}o/p:Hello from Grandparent!Hello from Parent!Hello from Child!- Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
Structure:
Parent Class↑ ↑Child1 Child2Example:class Parent {void commonMethod() {System.out.println("This is the Parent class.");}}class Child1 extends Parent {void uniqueMethod1() {System.out.println("This is Child1.");}}class Child2 extends Parent {void uniqueMethod2() {System.out.println("This is Child2.");}}public class HierarchicalInheritanceExample {public static void main(String[] args) {Child1 child1 = new Child1();Child2 child2 = new Child2();child1.commonMethod();child1.uniqueMethod1();child2.commonMethod();child2.uniqueMethod2();}}Output:This is the Parent class.This is Child1.This is the Parent class.This is Child2.- Multiple Inheritance (Not supported directly in Java)
Java does not support multiple inheritance with classes to avoid ambiguity issues (Diamond Problem). However, it can be achieved using interfaces.
Structure:
Interface1 Interface2↑ ↑Implementing ClassExample:interface Interface1 {void method1();}interface Interface2 {void method2();}class ImplementingClass implements Interface1, Interface2 {public void method1() {System.out.println("This is method1 from Interface1.");}public void method2() {System.out.println("This is method2 from Interface2.");}}public class MultipleInheritanceExample {public static void main(String[] args) {ImplementingClass obj = new ImplementingClass();obj.method1();obj.method2();}}Output:This is method1 from Interface1.This is method2 from Interface2.- Hybrid Inheritance (Not supported directly in Java)
A combination of two or more types of inheritance. Hybrid inheritance is supported in Java only through interfaces.
2.Outline the concept of hierarchical and multilevel inheritance with an example program.1. Hierarchical Inheritance
In hierarchical inheritance, a single parent class is inherited by multiple child classes. Each child class has access to the properties and methods of the parent class.
Structure:
Parent Class
↑ ↑
Child1 Child2
code:// Parent classclass Parent {void showParent() {System.out.println("This is the Parent class.");}}// First child classclass Child1 extends Parent {void showChild1() {System.out.println("This is Child1.");}}// Second child classclass Child2 extends Parent {void showChild2() {System.out.println("This is Child2.");}}// Main classpublic class HierarchicalInheritanceExample {public static void main(String[] args) {Child1 child1 = new Child1();Child2 child2 = new Child2();child1.showParent();child1.showChild1();child2.showParent();child2.showChild2();}}o/p:This is the Parent class.This is Child1.This is the Parent class.This is Child2.2. Multilevel Inheritance
In multilevel inheritance, a child class inherits from a parent class, and another class inherits from that child class. The chain can continue to multiple levels.
Structure:
Grandparent Class
↑Parent Class↑Child Classcode:// Grandparent classclass Grandparent {void showGrandparent() {System.out.println("This is the Grandparent class.");}}// Parent class (inherits from Grandparent)class Parent extends Grandparent {void showParent() {System.out.println("This is the Parent class.");}}// Child class (inherits from Parent)class Child extends Parent {void showChild() {System.out.println("This is the Child class.");}}// Main classpublic class MultilevelInheritanceExample {public static void main(String[] args) {Child child = new Child();child.showGrandparent();child.showParent();child.showChild();}}output:This is the Grandparent class.This is the Parent class.This is the Child class.3.Illustrate the concept of an abstract class in detail.Abstract Class in Java
An abstract class in Java is a class that cannot be instantiated on its own and is designed to be inherited by other classes. It can contain both abstract methods (methods without a body) and concrete methods (methods with a body). Abstract classes provide a blueprint for other classes to follow.
Key Points of Abstract Classes:
- An abstract class cannot be instantiated directly (i.e., you cannot create an object of an abstract class).
- It can have abstract methods (methods without implementation) and concrete methods (methods with implementation).
- The child class is required to provide an implementation for the abstract methods.
- An abstract class can have constructors, fields, and concrete methods just like any regular class.
Syntax:
abstract class ClassName {// Abstract method (does not have a body)abstract void abstractMethod();// Concrete method (has a body)void concreteMethod() {System.out.println("This is a concrete method.");}}Example:
In this example, we will create an abstract class
Shapethat has one abstract methodarea()and one concrete methoddisplay().Program:
// Abstract classabstract class Shape {// Abstract method (no implementation)abstract void area();// Concrete method (has implementation)void display() {System.out.println("This is a shape.");}}// Derived class (Child class)class Circle extends Shape {// Implementing the abstract methodvoid area() {double radius = 5;double area = Math.PI * radius * radius;System.out.println("Area of Circle: " + area);}}// Derived class (Child class)class Rectangle extends Shape {// Implementing the abstract methodvoid area() {double length = 10;double breadth = 5;double area = length * breadth;System.out.println("Area of Rectangle: " + area);}}// Main classpublic class AbstractClassExample {public static void main(String[] args) {// Cannot create an instance of abstract class Shape// Shape shape = new Shape(); // Error// Creating objects of concrete classesShape circle = new Circle();Shape rectangle = new Rectangle();// Calling the concrete methodcircle.display();rectangle.display();// Calling the abstract method via child classescircle.area();rectangle.area();}}output:This is a shape.This is a shape.Area of Circle: 78.53981633974483Area of Rectangle: 50.04.Demonstrate method overriding with a simple Java program.5.Show a Java program for single and multiple inheritance.Single and Multiple Inheritance in Java
1. Single Inheritance in Java
In single inheritance, a class inherits from one parent class. This is the most basic form of inheritance, where a single child class derives properties and behavior from one parent class.
Example of Single Inheritance:
// Parent classclass Animal {void eat() {System.out.println("This animal eats food.");}}// Child classclass Dog extends Animal {void bark() {System.out.println("The dog barks.");}}public class SingleInheritanceExample {public static void main(String[] args) {// Creating an object of Dog classDog dog = new Dog();// Calling method from parent classdog.eat();// Calling method from child classdog.bark();}}o/p:This animal eats food.The dog barks.2. Multiple Inheritance in Java (Through Interfaces)
Java does not support multiple inheritance directly through classes due to ambiguity issues (e.g., if two parent classes have a method with the same name, which one should be called). However, multiple inheritance can be achieved through interfaces. A class can implement multiple interfaces.
Example of Multiple Inheritance (Through Interfaces):
// First interfaceinterface Animal {void eat();}// Second interfaceinterface Sound {void makeSound();}// Child class implements both interfacesclass Dog implements Animal, Sound {public void eat() {System.out.println("The dog eats food.");}public void makeSound() {System.out.println("The dog barks.");}}public class MultipleInheritanceExample {public static void main(String[] args) {// Creating an object of Dog classDog dog = new Dog();// Calling methods from both interfacesdog.eat();dog.makeSound();}}o/p:The dog eats food.The dog barks.Key Points:
- Single Inheritance: A class inherits from only one parent class. This is the standard inheritance in Java.
- Multiple Inheritance (through Interfaces): Java does not support multiple inheritance through classes but allows a class to implement multiple interfaces, thus achieving multiple inheritance.
6.Explain the concept of a package in Java with an example program.Concept of Package in Java
A package in Java is a way to organize classes, interfaces, and sub-packages into namespaces, making it easier to manage large projects. Packages provide a mechanism for grouping related classes and interfaces, which enhances code modularity, reuse, and access control.
Benefits of Using Packages:
- Namespace management: Avoids class name conflicts by grouping classes into separate namespaces.
- Access control: Java provides different access levels (e.g.,
public,protected,private, and package-private) that control the visibility of classes and their members. - Modularity: Helps in organizing classes and interfaces based on their functionality.
- Reusability: Makes it easier to reuse code and organize large programs efficiently.
Types of Packages in Java:
- Built-in Packages: These are predefined packages provided by the Java API, such as
java.util,java.io, andjava.lang. - User-defined Packages: Packages created by the programmer to organize their own classes and interfaces.
Example:
In this example, we will create a user-defined package to organize related classes.
Steps:
- Create a package: We'll create a package named
shapes. - Create a class within the package: Inside the
shapespackage, we'll define a classCirclethat calculates the area of a circle. - Use the package: In the main program, we'll import the
shapespackage and use theCircleclass.
Step 1: Define the Package (
Circle.java)// File: Circle.java in the "shapes" packagepackage shapes;public class Circle {double radius;// Constructorpublic Circle(double radius) {this.radius = radius;}// Method to calculate the areapublic double calculateArea() {return Math.PI * radius * radius;}}Step 2: Use the Package in Main Program (TestCircle.java)// File: TestCircle.javaimport shapes.Circle; // Importing the Circle class from shapes packagepublic class TestCircle {public static void main(String[] args) {// Creating an object of Circle class from the shapes packageCircle circle = new Circle(5); // radius = 5// Calculating and displaying the area of the circledouble area = circle.calculateArea();System.out.println("The area of the circle is: " + area);}}Directory Structure:project-folder/│├── shapes/ (Package folder)│ └── Circle.java (Class in the package)│└── TestCircle.java (Main class using the package)7.Outline how to import and inherit different packages in an application program. Provide an example.Importing and Inheriting Classes from Different Packages in Java
In Java, you can import and inherit classes or interfaces from different packages in your application.
Importing classes: You use the
importstatement to import classes or interfaces from other packages into your program. This allows you to access their methods and fields.Inheriting classes from different packages: In Java, you can inherit classes from other packages by using the
extendskeyword. This allows a subclass to inherit methods and fields from a superclass defined in another package.
Steps to Import and Inherit from Different Packages:
Define Classes in Separate Packages:
- Create two different packages.
- Define a class in one package that can be inherited by a class in another package.
Use the
importStatement:- Use
importto access the class or interface from another package.
- Use
Inherit from Another Class:
- Use
extendsto inherit from the class in another package.
- Use
Example Program:
Step 1: Define the Superclass in One Package (
shapesPackage)// File: shapes/Rectangle.javapackage shapes;public class Rectangle {double length;double width;// Constructorpublic Rectangle(double length, double width) {this.length = length;this.width = width;}// Method to calculate areapublic double calculateArea() {return length * width;}}Step 2: Define the Subclass in Another Package (mainPackage)// File: mainPackage/Square.javapackage mainPackage;import shapes.Rectangle; // Importing the Rectangle class from shapes packagepublic class Square extends Rectangle { // Inheriting Rectangle class// Constructorpublic Square(double side) {super(side, side); // Passing side length to Rectangle constructor}public void displayArea() {System.out.println("The area of the square is: " + calculateArea());}}Step 2: Define the Subclass in Another Package (mainPackage)// File: mainPackage/Square.javapackage mainPackage;import shapes.Rectangle; // Importing the Rectangle class from shapes packagepublic class Square extends Rectangle { // Inheriting Rectangle class// Constructorpublic Square(double side) {super(side, side); // Passing side length to Rectangle constructor}public void displayArea() {System.out.println("The area of the square is: " + calculateArea());}}Directory Structure:project-folder/│├── shapes/ (Package for Rectangle class)│ └── Rectangle.java (Class inside shapes package)│└── mainPackage/ (Package for Square and TestSquare classes)├── Square.java (Class inheriting Rectangle)└── TestSquare.java (Main class using both packages)UNIT-3PART-A1.Identify any two Java built-in exceptions
Arithmeti
cException:This exception occurs when there is an arithmetic error, such as dividing by zero.
- Single Inheritance
NullPointerException:
This exception occurs when the JVM attempts to use a
nullobject reference where an object is require- Invalid operations (e.g., dividing by zero).
- Incorrect input (e.g., entering non-numeric data when expecting a number).
- Null reference (e.g., trying to call a method on a null object).
- Array index out of bounds (e.g., accessing an index that does not exist in an array).
- File not found (e.g., attempting to open a file that doesn't exist).
- try block: Contains the code that might throw an exception.
- catch block: Handles the exception if it occurs.
- finally block: Executes code regardless of whether an exception occurred, often used for cleanup.
- Graceful Error Handling: It allows the program to recover from errors without terminating.
- Separation of Error-Handling Code: Code related to error handling is separated from the normal business logic, making the code cleaner.
- Propagating Exceptions: Exceptions can be passed up the call stack, allowing the program to handle them at an appropriate level.
- Maintainability: Exception handling helps in writing more maintainable and readable code by using
try-catch-finallyblocks. - Better CPU Utilization: Multithreading allows multiple threads to execute concurrently, making better use of the CPU.
- Increased Performance: Multithreading can improve performance in programs that are I/O bound or need to perform many tasks simultaneously.
- Responsiveness: Multithreading improves the responsiveness of applications, especially in GUI-based applications.
- Efficient Resource Sharing: Threads share the same memory and resources, which is more efficient than using multiple processes.
- Parallel execution of tasks: For example, downloading multiple files at the same time.
- GUI applications: Keeping the UI responsive while performing background tasks.
- Real-time processing: In applications that require real-time data processing, like gaming or stock trading systems.
2.Construct the difference between multi-threading and multi-tasking.
3.Make use of Exception in Java.
In Java, exceptions are used to handle errors or abnormal conditions in the program. The try-catch block is used to catch exceptions and handle them gracefully without terminating the program
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
4.Identify the reason for the occurrence of an exception in the program.
Exceptions in Java occur due to:
5.Interview the Exception handling in Java.
Exception handling in Java is done using the try-catch-finally block:
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup code executed.");
}
6.Construct the advantages of using exception handling in Java.
7.Identify the advantages of multithreading.
8.Make use of multithreading.
Multithreading is used to perform multiple tasks simultaneously, often used in scenarios like:
9.Construct the difference between a process and a thread.
10.Identify the purpose of the wait() method in Java
The wait() method is used in synchronization. It causes the current thread to release the lock and enter the waiting state until another thread sends a notification (via notify() or notifyAll()).
Example:
synchronized (obj) {
while (condition) {
obj.wait(); // The thread waits until notified
}
}
A thread in Java goes through various states during its execution. The Java Thread class defines these states, and the thread moves between these states based on actions like starting, waiting, or finishing. The thread states are defined in the `Thread.State` enum and are crucial for understanding how threads are scheduled and executed.
Here are the different states in the lifecycle of a thread in Java:
---
### 1. **New (Born State)**:
- **Description**: This is the initial state of a thread. A thread is in the "new" state when it has been created but not yet started.
- **Example**: When you instantiate a `Thread` object, it is in the "new" state.
- **Transition**: The thread will transition to the **runnable** state when the `start()` method is called.
```java
Thread thread = new Thread(); // The thread is in the "new" state
```
---
### 2. **Runnable**:
- **Description**: A thread is in the **runnable** state when it is ready to run but the operating system's thread scheduler has not yet selected it for execution. It is either running or ready to run, waiting for the CPU to be allocated.
- **Note**: A thread in this state is not necessarily running; it simply means it is eligible to run.
- **Transition**: The thread can be moved to the **running** state when it is chosen by the thread scheduler for execution. A thread can also return to the **runnable** state after it finishes waiting or sleeping.
```java
thread.start(); // The thread enters the "runnable" state
```
---
### 3. **Blocked**:
- **Description**: A thread enters the **blocked** state when it wants to access a synchronized resource but cannot because another thread is currently using that resource. This state occurs when a thread is trying to acquire a lock on an object but is unable to.
- **Transition**: Once the lock becomes available (when the currently holding thread releases it), the thread moves back to the **runnable** state.
```java
synchronized (someObject) {
// Code that causes the thread to block until it acquires the lock
}
```
---
### 4. **Waiting**:
- **Description**: A thread is in the **waiting** state when it is waiting indefinitely for another thread to perform a particular action, such as notifying or interrupting it. The thread enters this state when it calls the `wait()` method (without a timeout), `join()`, or `LockSupport.park()`.
- **Transition**: The thread will move from the **waiting** state to the **runnable** state when another thread calls `notify()`, `notifyAll()`, or when the thread has been interrupted.
```java
synchronized (someObject) {
someObject.wait(); // Thread enters "waiting" state
}
```
---
### 5. **Timed Waiting**:
- **Description**: A thread enters the **timed waiting** state when it is waiting for a specified period. This state is typically reached when the thread calls `sleep()`, `join(long millis)`, or `wait(long millis)` with a timeout.
- **Transition**: After the specified time elapses, the thread moves to the **runnable** state.
```java
thread.sleep(1000); // Thread enters the "timed waiting" state for 1000 milliseconds
```
---
### 6. **Terminated (Dead)**:
- **Description**: A thread enters the **terminated** state when it has completed its execution, either because it has finished executing its `run()` method or because it has been terminated due to an exception. Once a thread reaches this state, it cannot be restarted.
- **Transition**: No further transitions occur once a thread enters the **terminated** state.
```java
// The thread has finished its work and is terminated
```
---
### Summary of Thread States:
---
### Example of Thread Lifecycle:
```java
class MyThread extends Thread {
public void run() {
try {
System.out.println("Thread started.");
Thread.sleep(2000); // Timed waiting state for 2 seconds
System.out.println("Thread finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadLifecycleExample {
public static void main(String[] args) {
MyThread thread = new MyThread(); // New state
thread.start(); // Moves to Runnable state
}
}
```
In the above example:
- Initially, the thread is in the **New** state.
- When the `start()` method is called, the thread moves to the **Runnable** state.
- After calling `sleep()`, the thread enters the **Timed Waiting** state.
- Once the sleep time is over, the thread will move back to the **Runnable** state and then complete, entering the **Terminated** state.
### **Difference Between Multitasking and Multithreading in Java**
In Java, **multitasking** and **multithreading** are two concepts related to executing multiple tasks or processes, but they differ in how they are implemented and managed. Here’s a detailed comparison between the two:
---
### **1. Multitasking:**
**Definition:**
Multitasking refers to the ability of an operating system (OS) to execute more than one task simultaneously. These tasks can either be **processes** (independent programs) or **threads** (sequences of execution within a program). In multitasking, the OS manages the allocation of resources like CPU time, memory, and I/O devices for different processes.
**Key Characteristics:**
- **Process-based**: Multitasking involves multiple processes that run concurrently.
- **Types of Multitasking**:
- **Process-based Multitasking** (used for executing multiple independent programs).
- **Thread-based Multitasking** (more focused on multithreading within a single process).
- **Context Switching**: The OS switches between processes or threads to give the illusion that all tasks are executing simultaneously.
- **Requires OS support**: The operating system handles the management of processes and resources.
#### Example of Multitasking:
In a multitasking environment, you can run different applications like a browser, an email client, and a word processor simultaneously.
```java
// Running two different programs (processes) in multitasking
// Process 1: Java program A
public class ProgramA {
public static void main(String[] args) {
// Task A
System.out.println("Running Program A");
}
}
// Process 2: Java program B
public class ProgramB {
public static void main(String[] args) {
// Task B
System.out.println("Running Program B");
}
}
```
Here, the OS runs `ProgramA` and `ProgramB` as two independent processes, achieving multitasking.
---
### **2. Multithreading:**
**Definition:**
Multithreading is a specific form of multitasking where multiple threads (smaller units of a process) are executed concurrently within the same process. All threads in a multithreaded program share the same memory and resources, but they run independently.
**Key Characteristics:**
- **Thread-based**: Multithreading involves running multiple threads within a single process.
- **Resource Sharing**: All threads share the same resources (memory, file handles, etc.), making it easier for threads to communicate.
- **Concurrency within a process**: Multiple threads in a process can perform different tasks concurrently.
- **Requires thread management**: Java provides classes like `Thread`, `Runnable`, and `ExecutorService` for creating and managing threads.
#### Example of Multithreading:
```java
// Multithreading in Java using Thread class
class Task1 extends Thread {
public void run() {
System.out.println("Task 1 is running");
}
}
class Task2 extends Thread {
public void run() {
System.out.println("Task 2 is running");
}
}
public class MultithreadingExample {
public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2();
t1.start(); // Starting Task 1 in a separate thread
t2.start(); // Starting Task 2 in a separate thread
}
}
```
In this example, two threads (`Task1` and `Task2`) are created, and both run concurrently in the same program. This is an example of multithreading.
---
---
While Java primarily focuses on multithreading, multitasking can still be achieved by running multiple independent programs (processes) using Java's `Runtime` or `ProcessBuilder` classes. However, managing multitasking via Java is typically not as common as with operating system-level multitasking.
### **Multithreading in Java:**
Java provides built-in support for multithreading, where you can create and manage multiple threads using classes like `Thread` and `Runnable`. This allows Java programs to perform tasks concurrently, improving performance for CPU-bound or I/O-bound operations.
UNIT-4
PART-A
2. Discover an Action Event?
ActionEvent is generated. This event is handled by an ActionListener, and the event object can be used to determine which component was involved in the action. The event can also carry information about the event type, such as the action command.Example:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
An EventListener interface in Java defines methods for handling specific types of events. It is implemented by a class to receive event notifications. The EventAdapter class provides a default implementation of the EventListener interface, allowing the developer to override only the necessary methods instead of implementing all methods.
- EventListener Interface: Defines methods for handling events. Example:
ActionListener,MouseListener. - Event Adapter: Provides default (empty) implementations for the methods of an EventListener. Example:
MouseAdapter,KeyAdapter.
Developers typically use Event Adapters when they only need to implement a few methods from the EventListener interface, simplifying the code.
4. Discover the three main components of Event handling?The three main components of event handling in Java are:
Event Source: The component that generates the event. Examples include buttons, text fields, or windows.
Event Object: An object that encapsulates the details of the event, such as the source of the event and any relevant data.
Event Listener: An interface that listens for specific types of events and provides methods to handle them. For example,
ActionListener,MouseListener,KeyListener.
Event Listener: An interface in Java that defines the methods for handling specific types of events. Examples include
ActionListener,MouseListener, andKeyListener.Event Handler: The method or the block of code that processes the event when it occurs. In Java, event handlers are usually implemented in event listener methods (e.g.,
actionPerformedforActionListener).
Difference:
- Event Listener is an interface used to declare the methods that will respond to events, while the Event Handler is the method that implements the logic for responding to events.
The delegation event model is the foundation of event handling in Java. In this model, the event source (such as a button or text field) generates an event when an action occurs. The event is then passed to an event listener, which is responsible for handling the event.
In the delegation model:
- Event source (e.g., button) generates an event.
- The event is passed to the appropriate event listener (e.g.,
ActionListener). - The listener handles the event by executing an appropriate method (e.g.,
actionPerformed).
The delegation model allows separation of concerns, where the source component doesn't need to know what happens after the event, and the listener focuses on the event handling logic.
7. Examine MouseMotionListener?MouseMotionListener is an interface that listens for mouse motion events, such as mouse movements or dragging. It has two methods:
mouseMoved(MouseEvent e): This method is called when the mouse is moved.mouseDragged(MouseEvent e): This method is called when the mouse is dragged with a button pressed.
Example:
public class MouseMotionExample implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved at: " + e.getPoint());
}
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse dragged at: " + e.getPoint());
}
}
To register a KeyListener, you use the addKeyListener() method on the component you want to monitor for key events. The KeyListener interface defines three methods:
- keyPressed(KeyEvent e): Called when a key is pressed.
- keyReleased(KeyEvent e): Called when a key is released.
- keyTyped(KeyEvent e): Called when a key is typed (a character is entered).
Example of registering a KeyListener:
public class KeyListenerExample extends JFrame {
public KeyListenerExample() {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
setFocusable(true); // Make sure the component can gain focus
}
public static void main(String[] args) {
KeyListenerExample frame = new KeyListenerExample();
frame.setSize(300, 300);
frame.setVisible(true);
}
}
If a Scrollbar is manipulated (e.g., the user adjusts the position of the scrollbar), a AdjustmentEvent is generated. The event is handled by an AdjustmentListener.
Methods in the AdjustmentListener interface:
- adjustmentValueChanged(AdjustmentEvent e): This method is called whenever the scrollbar value changes.
Example:
Scrollbar scrollbar = new Scrollbar();
scrollbar.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Scrollbar value changed: " + e.getValue());
}
});
When an applet’s window is closed, a WindowEvent is generated. The event can be handled by a WindowListener, specifically the windowClosing() method.
Methods in the WindowListener interface:
- windowClosing(WindowEvent e): Called when the user attempts to close the window (e.g., by clicking the close button).
- windowClosed(WindowEvent e): Called after the window is closed.
Example:
window.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
}
});
java.net package. It supports functionalities like sending and receiving data over the internet using protocols like TCP/IP and UDP.Loaded from the local file system. It does not require network access and runs directly from the user's computer.
Loaded from a remote web server. It requires network access and is often embedded in a webpage.
- Standalone Applet: Runs independently of a browser using an applet viewer.
- Web-based Applet: Runs within a web browser, often embedded in HTML files.
Socket programming is essential for enabling communication between devices over a network. It allows:
- Real-time data exchange.
- Building networked applications like chat systems, file transfer services, and online games.
- Platform-independent and runs on any Java-supported browser.
- Secure as it runs in a sandbox environment.
- Easy to integrate with web pages for interactive features.
init(): Called once during the applet’s initialization.start(): Called to start or resume execution.stop(): Called to pause execution.destroy(): Called to release resources before termination.paint(Graphics g): Called to draw graphics on the applet.
- TCP ensures reliable data transmission.
- IP is responsible for addressing and routing packets to their destinations.



0 Comments