Java IAT3
Java IAT3
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} finally {
// Code that always gets executed, regardless of whether an exception is
thrown or caught
}
Q.Define Exception. Write a program which contains one method which will
throw IllegalAccessException and use proper exception handlers so that
exception should be printed in the calling function.
A.An exception in Java is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. Exceptions are objects that represent
exceptional conditions or errors that arise during the execution of a program.
In Java, there are two types of exceptions: checked exceptions and unchecked
exceptions. Checked exceptions must be handled explicitly in the code, either by
using a try-catch block or by declaring the exception using the throws keyword in
the method signature. Unchecked exceptions, on the other hand, are not required to
be handled explicitly in the code.
Here's a program that contains a method that throws IllegalAccessException, and
proper exception handling is used in the calling function to catch and print the
exception:
This program demonstrates proper exception handling in Java, where the exception
thrown by the doSomething() method is caught and handled gracefully in the calling
function.
Q.Explain packages and its types. Explain import command in Java with an
examples.
A.In Java, a package is a way of organizing and grouping related classes and
interfaces. Packages provide a mechanism for creating namespaces, which helps
avoid naming conflicts and organizes classes and interfaces into logical units.
Packages also facilitate access control by allowing classes to be grouped together
and controlled as a unit.
There are two main types of packages in Java:
1. Built-in Packages: These are the packages that are included with the Java
Development Kit (JDK) and are part of the Java API. Examples of built-in
packages include java.lang, java.util, java.io, etc.
2. User-defined Packages: These are the packages that are created by the user
to organize their own classes and interfaces. User-defined packages help in
managing large projects by grouping related classes and interfaces together.
And here's the syntax for importing all classes and interfaces from a package:
import package_name.*;
Now, let's see some examples of using the import command in Java:
In this example, we are importing the ArrayList class from the java.util package.
This allows us to use the ArrayList class in our MyClass without fully qualifying its
name.
In this example, we are importing all classes from the java.util package using the
* wildcard. This allows us to use any class or interface from the java.util package
in our MyClass without fully qualifying their names.
Q.What is meant by thread priority? How is it assigned and how to get the thread
priority?
A.Thread priority in Java is a mechanism provided by the Java Virtual Machine
(JVM) to control the scheduling of threads. Each thread in Java is assigned a priority
that determines its importance to the scheduler relative to other threads. Threads
with higher priority are given preference by the scheduler and are more likely to be
scheduled for execution before threads with lower priority. However, thread priority is
only a hint to the scheduler and not an absolute guarantee of execution order.
In Java, thread priority is represented by an integer value ranging from 1 to 10, where
1 is the lowest priority and 10 is the highest priority. The default priority of a thread is
5.
Thread priorities are assigned using the setPriority(int priority) method of the
Thread class. This method sets the priority of the thread to the specified integer
value.
Here's how you can assign a priority to a thread in Java:
Thread thread = new Thread();
thread.setPriority(Thread.MAX_PRIORITY); // Set priority to the highest value
(10)
To get the priority of a thread, you can use the getPriority() method of the Thread
class. This method returns the priority of the thread as an integer value.
Here's how you can get the priority of a thread in Java:
Thread thread = Thread.currentThread();
int priority = thread.getPriority(); // Get the priority of the current thread
System.out.println("Thread priority: " + priority);
It's important to note that the exact behavior of thread priorities may vary between
different operating systems and JVM implementations. Additionally, reliance on
thread priorities for controlling thread execution order is generally discouraged
because it can lead to platform-dependent behavior and may not always produce the
desired results. Therefore, thread priorities should be used judiciously and in
conjunction with other concurrency control mechanisms, such as synchronization
and locks.
// Set priorities
thread1.setPriority(Thread.MIN_PRIORITY); // Set minimum priority (1)
thread2.setPriority(Thread.NORM_PRIORITY); // Set normal priority (5)
thread3.setPriority(Thread.MAX_PRIORITY); // Set maximum priority (10)
// Start threads
thread1.start();
thread2.start();
thread3.start();
}
}
class Counter {
private int count = 0;
thread1.start();
thread2.start();
class Counter {
private int count = 0;
incrementThread.start();
decrementThread.start();
Q.Describe the various levels of access protections available for packages and
their implications with suitable program examples.
A.In Java, there are four levels of access protection provided by packages, which
control the visibility of classes, interfaces, constructors, and methods within the
same package or across different packages. These levels of access protection are:
1. Private: The private access modifier restricts access to the member to only
within the same class. It is the most restrictive access level.
2. Default (Package-private): If no access modifier is specified, the member has
default (package-private) access within the same package. It restricts access
to only within the same package.
3. Protected: The protected access modifier restricts access to the member to
within the same package or by subclasses (even if the subclass is in a
different package).
4. Public: The public access modifier provides unrestricted access to the
member from any other class or package.
Let's illustrate these access levels with suitable program examples:
Example 1: Private Access Modifier
package example;
class MyClass {
private int privateField;
class MyClass {
int defaultField; // Default (package-private) access
package example2;
import example1.MyClass;
In this example:
● MAX_VALUE and DEFAULT_NAME are variables (constants) defined within the
MyInterface interface.
● They are implicitly public, static, and final, meaning they can be accessed
as MyInterface.MAX_VALUE and MyInterface.DEFAULT_NAME from any class
that implements the interface.
Here's an example demonstrating how variables in interfaces are used:
Output:
yaml
Copy code
Maximum value: 100
Default name: John Doe
In this example, the Main class implements the MyInterface interface. It can access
the variables MAX_VALUE and DEFAULT_NAME defined in the interface directly using the
interface name (MyInterface). This allows for a centralized definition of constants
that can be easily accessed and shared across multiple classes.
// Nested interface
interface NestedInterface {
void nestedMethod();
}
}
In this example:
● MyInterface is an interface containing constant variables (MAX_VALUE and
DEFAULT_NAME), an abstract method myMethod(), a default method
defaultMethod(), and a static method staticMethod().
● The interface also contains a nested interface NestedInterface with an
abstract method nestedMethod().
● Any class that implements the MyInterface interface must provide
implementations for the myMethod() method, and it may optionally override
the default methods if needed.
Q.With syntax explain the use of following methods in threads
i) isAlive( ) ii) Join( ) iii) wait() iv) notify() v) notifyAll()
A. Here's a brief explanation of each method with its syntax:
i) isAlive() method:
● This method checks whether a thread is still alive or has terminated.
● Syntax: boolean isAlive()
ii) join() method:
● This method waits for a thread to terminate. It causes the current thread to
pause its execution until the thread on which it's called completes its
execution.
● Syntax: void join()
iii) wait() method:
● This method causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
● Syntax: void wait()
iv) notify() method:
● This method wakes up a single thread that is waiting on this object's monitor.
If multiple threads are waiting, only one of them is chosen to be awakened.
● Syntax: void notify()
v) notifyAll() method:
● This method wakes up all threads that are waiting on this object's monitor.
This causes all threads to become eligible for execution.
● Syntax: void notifyAll()
Note: The wait(), notify(), and notifyAll() methods must be called from within a
synchronized context, i.e., they should be called on an object while holding its lock.
Otherwise, an IllegalMonitorStateException will be thrown.
Q.What are enumerations? Explain the following methods with an example program.
i) values() and valueOf() ii) ordinal() iii) equals() iv) CompareTo()
A. Enumerations in Java are a special type of class that represents a group of
constants (enumerated values). Enumerations provide a way to define a fixed set of
named constants, which makes the code more readable, maintainable, and
error-prone.
Now, let's explain the methods associated with enumerations with examples:
i) values() and valueOf() methods:
● values(): This method returns an array containing all of the values of the
enumeration in the order they are declared.
● valueOf(): This method returns the enumeration constant with the specified
name.
● Example:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
// Printing results
System.out.println("Result 1: " + result1); // Output: 30
System.out.println("Result 2: " + result2); // Output: 5.64
}
}
In this example:
● Autoboxing occurs when assigning primitive values 10 and 3.14 to Integer
and Double objects, respectively.
● Autounboxing occurs when assigning num1 and value1 to primitive int and
double variables, respectively.
● Autoboxing and autounboxing also take place in expressions, such as addition
(num1 + 20 and value1 + 2.5), where int and double values are automatically
converted to Integer and Double objects for the operation and then
automatically unboxed back to primitive values for the result.
Q. What are type wrappers? Explain with a program example the character and
numeric type wrappers.
A. Type wrappers, also known as wrapper classes, are classes in Java that provide
an object representation of primitive data types. Each primitive data type in Java has
a corresponding wrapper class, which allows primitive data types to be used as
objects in Java programs. Wrapper classes are used to wrap primitive values and
provide methods to manipulate those values as objects.
There are two types of wrapper classes in Java:
Character wrapper classes: These classes are used to represent characters
(char).
● Character: Wrapper class for char.
Numeric wrapper classes: These classes are used to represent numeric data
types.
● Byte: Wrapper class for byte.
● Short: Wrapper class for short.
● Integer: Wrapper class for int.
● Long: Wrapper class for long.
● Float: Wrapper class for float.
● Double: Wrapper class for double.
Here's a program example demonstrating the character and numeric wrapper
classes:
Output:
Character: A
Integer value: 10
Double value: 3.14
Unboxed Integer value: 10
Unboxed Double value: 3.14
In this example:
● The Character wrapper class is used to wrap a char value 'A'.
● Numeric wrapper classes (Integer and Double) are used to wrap int and
double values, respectively.
● Autoboxing is used to automatically convert primitive values to wrapper
objects (intValue = 10 and doubleValue = 3.14).
● Unboxing is used to automatically convert wrapper objects to primitive values
(intValueUnboxed = intValue and doubleValueUnboxed = doubleValue).