java ia2 answer
java ia2 answer
Module 3-bcs306A
Answer:class Box {
Width = w;
Height = h;
Depth = d;
Double volume() {
Double weight;
Super(w, h, d);
Weight = m;
Double cost;
Super(w, h, d, m);
Cost = c;
Class Mainclass{
Public static void main(String args[]){
Double vol;
Vol = shipment1.volume();
System.out.println();
2. What is the importance of the super keyword in inheritance? Illustrate with a suitable example.
Ans: Using super: The super keyword in java is a reference variable which is used to refer Immediate
parent class object. Whenever you create the instance of subclass, an instance of Parent class is
created implicitly which is referred by super reference variable.
Class Animal{
String color=”white”;
Void printColor(){
Class Mainclass{
d.printColor();
Output: black
White
Can also be used to invoke the parent class constructor. Let’s see a simple example:
Class A {
Int I;
Private int j;
A(int a, int b) {
I=a;
J=b;
Void addij(){
Int k=i+j;
System.out.println(“(i+j=)”+k);
Class B extends A {
Int k;
Super(a,b);
K=c;
}void addik() {
System.out.println(“i: “ + i);
System.out.println(“k: “ + k);
Int c=i+k;
System.out.println(“i+k=”+c);
}
Class Mainclass{
B b=new B(1,2,3);
b.addij();
b.addik();
Output: (i+j=)3
I: 1
K: 3
I+k=4
3. Super is used to invoke super-class(parent class) method.. The super keyword can
Also be used to invoke the parent class method when parent class method and child class Method
names are same in other words method is overridden.
Class Animal{
Void eat(){
Void eat(){
System.out.println(“eating bread…”);
Void bark(){
System.out.println(“barking…”);
Void work(){
Super.eat();
Bark();
}
Class Mainclass{
d.work();
Answer:Abstract Classes: There are situations in which you will want to define a super-class that
declares
That is, sometimes you will want to create a super-class that only defines a generalized form that
Will be shared by all of its subclasses, leaving it to each subclass to fill in the details.To declare an
Abstract method, use this general form:
Any class that contains one or more abstract methods must also be declared abstract. To
Declare a class abstract, you simply use the abstract keyword in front of the class Keyword at the
beginning of the class declaration.
There can be no objects of an abstract class. That is, an abstract class cannot be directly Instantiated
with the new operator. Such objects would be useless, because an abstract Class is not fully defined.
Double dim1;
Double dim2;
Figure(double a, double b) {
Dim1 = a;
Dim2 = b;
}
Class Rectangle extends Figure {
Rectangle(double a, double b) {
Super(a, b);
Double area() {
Triangle(double a, double b) {
Super(a, b);
Double area() {
Class AbstractAreas {
Figref = r;
System.out.println(“Area is “ + figref.area());
Figref = t;
System.out.println(“Area is “ + figref.area());
}
4.What is dynamic method dispatch? Write a simple example that illustrates dynamic method
dispatch.
Ans:Dynamic Method Dispatch: Dynamic method dispatch is the mechanism by which a call to an
Overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is
Important because this is how Java implements run-time polymorphism.
Class A {
Void callme() {
Class B extends A {
// override callme()
Void callme() {
Class C extends A {
// override callme()
Void callme() {
Class Dispatch {
A r;
R = a; // r refers to an A object
r = b; // r refers to a B object
r.callme(); // calls B’s version of callme
r = c; // r refers to a C object
5.What is meant by interface? State its need and write syntax and features of interface.
An interface in Java is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Interfaces do not contain any
method implementation (prior to Java 8, except for default and static methods).
An interface is a blueprint of a class that specifies a set of methods that a class must implement.
1. Achieving Multiple Inheritance: Java does not support multiple inheritance with classes, but it
supports it through interfaces, allowing a class to implement multiple interfaces.
2. Abstraction: Interfaces provide complete abstraction by declaring what a class must do but not
how it does it.
4. Polymorphism: They enable polymorphic behavior as a class can implement multiple interfaces.
Syntax of an Interface
interface InterfaceName {
void method1();
void method2();
Features of Interfaces
1. Complete Abstraction: Interfaces allow only method declarations, not implementations (except
default and static methods in Java 8+).
2. Implicit Modifiers:
All fields are public, static, and final by default.All methods are public and abstract by default (except
default and static methods).
4. Inheritance in Interfaces: An interface can inherit from another interface using the extends
keyword.
6. Java 8 Enhancements: Default and static methods were introduced to provide a mechanism for
method implementation in interfaces.
Answer:Method Overriding in Java: If subclass (child class) has the same method as declared in the
Parent class, it is known as method overriding in java. In other words, If subclass provides
The specific implementation of the method that has been provided by one of its parent class, It is
known as method overriding.
Class Bank{
Int getRateOfInterest(){
Return 0;
Int getRateOfInterest(){
Return 8;
Int getRateOfInterest(){
Return 7;
Int getRateOfInterest(){
Return 9;
Class Test2{
Nesting of interfaces means defining an interface inside another interface or class. This is used to
logically group interfaces and associate them closely with the enclosing interface or class. Nested
interfaces are implicitly static.
Syntax:
Interface OuterInterface {
Void outerMethod();
// Nested interface
Interface InnerInterface {
Void innerMethod();
Example
Interface OuterInterface {
Void displayOuter();
Interface InnerInterface {
Void displayInner();
Outer.displayOuter();
Inner.displayInner();
Output:
Outer interface method.
Answer:Using final with Inheritance: The final keyword in java is used to restrict the user. The Java
final keyword can be used in many context. Final can be:
1. Variable
2. Method
3. Class
Final variable: There is a final variable speedlimit, we are going to change the value of this
Variable, but It can’t be changed because final variable once assigned a value can never be Changed.
Class Bike9{
Void run(){
Speedlimit=400;
Obj.run();
Java final method: If you make any method as final, you cannot override it.
Class Bike{
System.out.println(“running”);
Void run(){
Class MainClass{
Public static void main(String args[]){
Honda.run();
Java final class: If you make any class as final, you cannot inherit it.
Int add(){
Return 10;
Void run(){
Class MainClass{
Honda.run();
Module 4
9. Define package. Explain the steps involved in creating a user-defined package with an example.
Answer:
Definition of Package:
A package in Java is a namespace that organizes related classes and interfaces to avoid naming
conflicts and ensure modular programming. It provides access protection and easier code
management.
1. Create a Package:
Use the package keyword at the top of the file to specify the package name.
Save the file with the same name as the class and inside a directory with the package name.
Use the javac command to compile the file. Ensure you are outside the package directory.
This creates the mypackage folder with the compiled .class file.
Example:
Package mypackage;
Javac -d . MyClass.java
Import mypackage.MyClass;
Obj.display();
}
Javac TestPackage.java
Java TestPackage
Output:
10. Examine the various levels of access protections available for packages and their implications
with suitable examples.
Answer:Access Levels in Java and Their Implications Java provides four access levels for class
members (fields, methods, constructors) and their usage in packages:
1. Public
Accessible from anywhere (within the same class, package, or from another package).
Example:
Package pkg1;
System.out.println(“Public method”);
Package pkg2;
Import pkg1.PublicExample;
2. Protected
Example:
Package pkg1;
System.out.println(“Protected method”);
Package pkg2;
Import pkg1.ProtectedExample;
Example:
Package pkg1;
Class DefaultExample {
Void display() {
System.out.println(“Default method”);
Package pkg1;
4. Private
Example:
Package pkg1;
System.out.println(“Private method”);
Package pkg1;
Obj.show(); // Works
11.Explain the concept of importing packages in Java and provide an example demonstrating the
usage of the import statement.
In Java, the import statement is used to access classes and interfaces from other packages. It allows
reusability of code and helps avoid fully qualifying class names.
Types of import Statements:
1. Specific Import:
2. Wildcard Import:
Package mypackage;
Javac -d . MyClass.java
Obj.greet();
Javac TestImport.java
Java TestImport
Output:
Key Points:
1. No Import Needed for Same Package: Classes in the same package can directly access each
other.
2. Fully Qualified Names: If the import statement is not used, fully qualified names must be
used (e.g., mypackage.MyClass obj = new mypackage.MyClass();)
3. Static Import: Use import static to access static members directly. Example: import static
java.lang.Math.PI;
The Import statement simplifies the usage of external classes and improves code readability.
12. Define an exception and explain the exception handling mechanism with an example.
Exception-Handling Fundamentals:
Your code can catch this exception (using catch) and handle it in some
Rational manner.
A throws clause.
Any code that absolutely must be executed after a try block completes is
13. Write a program which contains one method which will throw an Illegal Access
Exception and use proper exception handle so that exceptions should be printed.
}
Public static void main(String[] args) {
Try {
throwIllegalAccess();
} catch (IllegalAccessException e) {
} finally {
1. Arithmetic Exception
Description: Thrown when an arithmetic operation attempts an invalid operation, such as division by
zero.
Example:
2. NullPointerException
Description: Thrown when an application attempts to access a null object or calls a method on a null
reference.
Example:
3. ArrayIndexOutOfBoundsException
Description: Thrown when an attempt is made to access an array with an invalid index (negative or
beyond its length).
Example:
Int[] arr = {1, 2, 3};
4. ClassCastException
Example:
5. IllegalArgumentException
Description: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
Example:
6. NumberFormatException
Description: Thrown when an attempt is made to convert a string to a numeric type, but the string is
not properly formatted.
Example:
7. IOException
Example:
8. FileNotFoundException
Description: A subclass of IOException, thrown when an attempt to open a file that does not exist is
made.
Example:
9. InterruptedException
Description: Thrown when a thread is interrupted while it is waiting, sleeping, or otherwise paused.
Example:
Thread.sleep(1000);
Example:
15.How do you create your own exception class? Explain with a program.
Answe: The Exception class does not define any methods of its own.
Thus, all exceptions, including those that you create, have the methods
They are shown in Table 10-3. You may also wish to override one or
In Java, you can create your own exception class by extending the Exception class (for checked
exceptions) or RuntimeException class (for unchecked exceptions). This allows you to define custom
behavior or add specific details to your exception.
Example Program:
// Default constructor
Public InvalidAgeException() {
// Parameterized constructor
Super(message);
}
// Main Class
Try {
checkAge(15);
} catch (InvalidAgeException e) {
} finally {
Explanation:
Includes a default constructor with a generic message and a parameterized constructor for custom
messages.
checkAge throws an InvalidAgeException if the age is not in the valid range (18 to 100).
The exception is caught in the catch block and the message is displayed.
2. Finally Block:
Ensures that cleanup or additional actions are performed regardless of whether an exception was
thrown.
That is, a try statement can be inside the block of another try.
This continues until one of the catch statements succeeds, or until all
Class NestTry {
Try {
Inta args.length;
/* If no command-line args are present, the following statement will generate a divide-by-zero
exception. */
Int b = 42/a;
System.out.println(“a” + a);
If one command-line arg is used, then a divide-by-zero exception will be generated by the following
code. */ if(a==1) a = a/(a-a); // division by zero
If (a==2) (
Int c[]={1};
catch (ArrayIndexOutOfBoundsException e)
} catch (ArithmeticException e)
System.out.println(“Divide by 0:”+e);
17.What is chained exception? Give an example that illustrates the mechanics of handling chained
exceptions.
Answer: Beginning with JDK 1.4, a feature was incorporated into the
However, the actual cause of the problem was that an I/O error occurred,
since that is the error that occurred, you might also want to let the
calling code know that the underlying cause was an I/O error.
Chained exceptions let you handle this, and any other situation in
try {
throw highLevelException;
} catch (IllegalArgumentException e) {
e.printStackTrace();
if (cause != null) {
Explanation:
1. Low-Level Exception:
2. High-Level Exception:
3. initCause Method:
Module 5
18.What do you mean by thread? Explain the different ways of creating threads.
Answer :
A thread is the smallest unit of execution in a program, often referred to as a lightweight sub-
process. Threads are part of a process and share the same memory and resources, but they execute
independently. They are widely used for multitasking within a single program, allowing multiple
tasks to run concurrently.
1. Efficient Resource Sharing: Threads share the memory and resources of the parent process,
reducing overhead.
2. Faster Context Switching: Switching between threads is faster than between processes.
3. Parallel Execution: Threads enable concurrent execution, improving application
responsiveness and performance.
In this method, a class is created by extending the Thread class and overriding its run() method. The
run() method contains the code to be executed by the thread. To start the thread, the start()
method is invoked.
Example:
@Override
System.out.println(“Thread is running…”);
}
}
Note: Extending the Thread class restricts the ability to extend other classes because Java does not
support multiple inheritance.
This method involves creating a class that implements the Runnable interface and overrides the
run() method. The Runnable object is passed to a Thread instance, which then starts the thread.
Example:
@Override
System.out.println(“Thread is running…”);
A class can implement Runnable and extend another class, promoting better design and flexibility.
It separates the task (defined in Runnable) from the thread creation, making it reusable.
From Java 8 onwards, threads can be created more concisely using lambda expressions.
Example:
Answer:
Multithreading is a technique in which multiple threads execute concurrently within a single process.
Each thread runs independently but shares the same memory and resources of the parent process.
This enables efficient multitasking, where different parts of a program can run simultaneously,
improving performance and responsiveness.
This.threadName = name;
@Override
System.out.println(threadName + “ is running…”);
T1.start();
T2.start();
T3.start();
1. isAlive() Method
The isAlive() method is used to check whether a thread is still active or has finished executing. It
returns true if the thread is currently running or in a runnable state, and false otherwise.
Syntax:
Example:
@Override
System.out.println(“Thread is running…”);
T1.start();
2. join() Method
The join() method allows one thread to wait until another thread completes its execution. This is
useful for ensuring that a specific thread finishes before proceeding with the rest of the program.
Syntax:
Example:
@Override
System.out.println(Thread.currentThread().getName() + “ is running…”);
}
}
T1.start();
Try {
} catch (InterruptedException e) {
System.out.println(e.getMessage());
21. What is the need of synchronization? Explain with an example how synchronization
is implemented in JAVA.
Synchronization is required in Java to control access to shared resources by multiple threads. When
multiple threads access and modify a shared resource concurrently, it can lead to data inconsistency
and unpredictable behavior. Synchronization ensures that only one thread can access the critical
section (shared resource) at a time, preventing race conditions and maintaining data integrity.
Class Counter {
Int count = 0;
Void increment() {
Count++;
});
});
T1.start();
T2.start();
Try {
T1.join();
T2.join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
The output may vary, but it is often less than 2000 due to race conditions, where both threads
modify the value of count simultaneously.
Solution: Synchronization
To avoid race conditions, we synchronize the critical section using the synchronized keyword.
Example:
Class Counter {
Int count = 0;
Count++;
});
});
T1.start();
T2.start();
Try {
T1.join();
T2.join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
1. Synchronized Method: Ensures only one thread executes the method at a time.
2. Synchronized Block: Limits synchronization to specific parts of a method for better
performance.
3. Locking Mechanism: A thread acquires a lock on the object before entering the synchronized
block or method and releases it after exiting.
Synchronized (object) {
// Critical section
Answer:Thread Priorities
Thread priorities are integers that specify the relative Priority of one thread to another.
a higher-priority thread doesn’t run any faster than a Lower-priority thread if it is the only thread
running.
Instead, a thread’s priority is used to decide when to Switch from one running thread to the next.
This is Called a context switch.
Yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are Examined, and
the highest-priority thread That is ready to run is given the CPU. A thread can be preempted by a
higher-Priority thread: In this case, a lower-Priority thread that does not yield the Processor is simply
preempted—no matter What it is doing— by a higher-priority Thread. Basically, as soon as a higher-
In cases where two threads with the same priority are Competing for CPU cycles, the situation is a
bit Complicated.
23. Explain how to achieve suspending, resuming and stopping threads with an example
program.
Answers,:In Java, threads can be suspended, resumed, and stopped using flags and control logic. A
thread is suspended by setting a flag and putting it in a wait() state, resumed by resetting the flag
and calling notify(), and stopped by using a termination flag in the run() method. Deprecated
methods like suspend(), resume(), and stop() should be avoided due to safety concerns. Example:
Try {
While (!isStopped) {
System.out.println(“Running…”); Thread.sleep(1000);
} catch (InterruptedException e) {}
24. Discuss values() and value Of() methods in Enumerations with suitable examples.
Java enumerations (enums) are special classes that represent a group of constants. Two commonly
used methods in enums are values() and valueOf().
1. Values() Method
The values() method returns an array containing all the constants of the enum in the order they are
declared. It is automatically added to every enum by the compiler.
Syntax:
Example:
Enum Days {
}
Public class EnumExample {
System.out.println(day);
2. valueOf() Method
The valueOf() method returns the enum constant of the specified name. The name must exactly
match an identifier used to declare the enum constant, and it is case-sensitive.
Syntax:
Example:
Enum Days {
Key Points
If the string passed to valueOf() does not match any enum constant, it throws an
IllegalArgumentException.