0% found this document useful (0 votes)
21 views21 pages

Oops Assignment 2

Sdf

Uploaded by

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

Oops Assignment 2

Sdf

Uploaded by

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

Oops Assignment-2

1. Explain the purpose of packages in Java and how they assist in


managing the namespace.
ANS
Package in Java is a mechanism to encapsulate a group of
classes, sub packages and interfaces. Packages are used for:
 Preventing naming conflicts. For example there can be two
classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces,
enumerations and annotations easier
 Providing controlled access: protected and default have package
level access control. A protected member is accessible by classes
in the same package and its subclasses. A default member
(without any access specifier) is accessible by classes in the
same package only.
 Packages can be considered as data encapsulation (or data-
hiding).

Packages help manage namespaces in several ways, including:


 Organizing large programs
Packages group related classes, interfaces, or other packages
into logical units. This makes it easier to manage large
programs.
 Creating private areas
In Java, packages allow programmers to create private areas to
declare classes. This prevents class names from colliding with
other classes in different packages.
 Organizing multiple packages
In Python, namespace packages can organize multiple packages
into the same namespace. This is useful when you have many
related packages or a large package that not all users need access
to.
 Splitting sub-packages
In Python, namespace packages can split sub-packages and
modules across multiple distribution packages.
Oops Assignment-2
2. Describe the steps to create a package in Java and explain how
to compile and run a program that uses it.
ANS
All we need to do is put related classes into packages. After that,
we can simply write an import class from existing packages and
use it in our program. A package is a container of a group of
related classes where some classes are accessible or exposed and
others are kept for internal purposes. We can reuse existing
classes from the packages as many times as we need them in our
program. Package names and directory structure are closely
related
Types of Packages in Java
There are two types of packages in java:
1. User-defined Package
2. Built-in packages
// Java Program to Import a package
import java.util.*;
class GFG {
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
String userName;
Display message
System.out.println("Enter Your Name:");
userName = myObj.nextLine();
System.out.println("Your Name is : " + userName);
}
}
COMPILE: JAVAC Program name.java
RUN:JAVA Filename
OUTPUT;
Enter Your Name:James
Oops Assignment-2
Your Name is:James

3. Discuss the concept of access protection in Java packages. How


does it control access to classes and their members?
ANS
This modifier can be applied to the data member, method, and
constructor, but this modifier can’t be applied to the top-level
classes and interface. A member is declared as protected as we
can access that member only within the current package but only
in the child class of the outside package.
Example:
import java.io.*;
import java.util.*;
class Parent {
protected void print() { System.out.println("GFG"); }
public static void main(String[] args)
{
Parent p = new Parent();
p.print();
Child c = new Child();
c.print();
Parent cp = new Child();
cp.print();
}
}
class Child extends Parent {
}
OUTPUT:
GFG
GFG
GFG
Oops Assignment-2
4. Explain how to import packages in Java and differentiate
between the different import techniques available.
ANS
To import java package into a class, we need to use
java import keyword which is used to access package and its
classes into the java program.
Use import to access built-in and user-defined packages into
your java source file so that your class can refer to a class that is
in another package by directly using its name.

Explicit Import (Explicitly Importing Specific Classes)


The explicit import technique involves importing specific
classes or interfaces from a package. This means you need to
specify the exact class or interface you want to use in your code.
Syntax:
import package_name.ClassName;

Implicit Import (Importing All Classes from a Package)


The implicit import technique, often referred to as a "wildcard
import," involves importing all classes from a package at once
using a wildcard (*).
Syntax:
import package_name.*;

5. Define exception handling in Java. Explain the importance of


try-catch blocks and how they are used to handle exceptions.
ANS
Exception handling in Java is a process that helps developers
address unexpected events that occur during a program's
execution.
When executing Java code, different errors can occur: coding
errors made by the programmer, errors due to wrong input, or
other unforeseeable things.
Oops Assignment-2
When an error occurs, Java will normally stop and generate an
error message. The technical term for this is: Java will throw
an exception (throw an error).
Java try and catch
The try statement allows you to define a block of code to be
tested for errors while it is being executed.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
The try and catch keywords come in pairs
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

6. Describe the different types of exceptions in Java. How do


checked and unchecked exceptions differ?
ANS

 ArithmeticException
Occurs when an incorrect arithmetic operation is performed,
such as dividing a number by zero

 ClassNotFoundException
Oops Assignment-2
A checked exception that occurs when a required class is not
found

 ArrayIndexOutOfBoundsException
Occurs when an attempt is made to access an array element with
an index that is negative or greater than the array's size

 NullPointerException
Occurs when an attempt is made to use an object reference that
has been assigned the null value

 InterruptedException
A checked exception that occurs when a thread is interrupted
while waiting, sleeping, or otherwise occupied

 ArrayStoreException
A runtime exception that occurs when the wrong type of object
is placed into an array
Oops Assignment-2
7. Explain the purpose of the finally block in Java exception
handling. Provide an example to illustrate its usage.
ANS
The finally block in java is used to put important codes such as
clean up code e.g. closing the file or closing the connection. The
finally block executes whether exception rise or not and whether
exception handled or not. A finally contains all the crucial
statements regardless of the exception occurs or not.
EXAMPLE:
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
System.out.println(34 / 2);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");
}
finally {
System.out.println( "finally : i execut always.");
}
}
}
OUTPUT:
inside try block
17
finally : i execute always.

8. Discuss the concept of throwing exceptions in Java. How can a


custom exception be created and used?
ANS
Oops Assignment-2
When an exception is thrown using the throw keyword, the flow of
execution of the program is stopped and the control is transferred
to the nearest enclosing try-catch block that matches the type of
exception thrown. If no such match is found, the default exception
handler terminates the program.
In Java, you can create and use custom exceptions by extending the
Exception class (for checked exceptions) or the RuntimeException
class (for unchecked exceptions). Here's a step-by-step guide on
how to create and use custom exceptions
 Custom Checked Exception: Extend Exception.
 Custom Unchecked Exception: Extend RuntimeException.
 Use throw to throw the custom exception and try-catch to handle
it.
With custom exceptions, you make your error handling more
semantic, ensuring that your code is robust and easy to maintain.
EXAMPLE:
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}

public class Example {


public static void main(String[] args) throws
MyCustomException {
throw new MyCustomException("This is a custom
exception.");
}
Oops Assignment-2
}

9. Describe multiple catch blocks in Java. How does Java handle


exceptions with multiple catch statements?
ANS
In Java, multiple catch blocks are used to handle different types
of exceptions that may occur in a try block. This feature is
called multi-catch block
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}

In the following code, we have to handle two different


exceptions but take the same action for both. So we needed to
have two different catch blocks as of Java
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
Oops Assignment-2
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}
Oops Assignment-2
10.Define multithreading in Java and explain its advantages.How
does it differ from process-based multitasking?
ANS
Multithreading is a programming concept in Java that allows multiple
threads to run simultaneously
Advantages:
 Improved performance
 Better responsiveness
 Resource sharing
 Safer process execution

Difference between multithreading and process based multitasking


Oops Assignment-2
11.Explain the lifecycle of a thread in Java. Include a brief description of
each state.
Oops Assignment-2
12. Describe how threads can be created in Java. Compare the approaches of
implementing the Runnable interface and extending the Thread class.
ANS
 Extending the Thread class
Create a new class that extends the java.lang.Thread class, and then create an
instance of that class. The run() method in the new class should include the
functionality to be implemented by the thread.

 Implementing the Runnable interface


Create a class that implements the java.lang.Runnable interface and includes
a run() method. To use the class as a thread, create a Thread object by passing
the runnable class object, and then call the start() method.
The significant differences between extending Thread class and
implementing Runnable interface:
 When we extend Thread class, we can’t extend any other class even we
require and When we implement Runnable, we can save a space for our
class to extend any other class in future or now.
 When we extend Thread class, each of our thread creates unique object
and associate with it. When we implements Runnable, it shares the same
object to multiple threads.
Java program to illustrate defining Thread by extending Thread class
Oops Assignment-2

Java program to illustrate defining Thread by implements Runnable interface

13. Discuss the concept of thread synchronization in Java. How is it


implemented to prevent thread interference?
ANS
Java Synchronization is used to make sure by some synchronization method that
only one thread can access the resource at a given point in time.
Oops Assignment-2
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization
Process Synchronization is a technique used to coordinate the execution of
multiple processes. Thread Synchronization is used to coordinate and ordering
of the execution of the threads in a multi-threaded program.
In Java, synchronization is implemented to prevent thread interference by using
the synchronized keyword to mark a method or block of code that can only be
executed by one thread at a time. This ensures that only one thread can access a
shared resource or critical section at a time, which prevents data corruption and
inconsistencies.
Here's how synchronization works in Java:
1. A new thread acquires a lock on the shared object or class.
2. The thread performs the required operation.
3. The thread releases the acquired lock.
4. The same steps start from step 1 for other threads.

14. Explain the role of join() and isAlive() methods in thread management.
Provide examples of their usage.
ANS
join(): It will put the current thread on wait until the thread on which it is called
is dead.
EXAMPLE:
Oops Assignment-2

isAlive():The isAlive() method returns true if the thread upon which it is called
is still running otherwise it returns false
Oops Assignment-2
15. Define enumerations in Java. Explain how they enhance type
safety and provide an example of their usage.
ANS
An enumeration (enum for short) in Java is a special data type which
contains a set of predefined constants.
Here are some ways that enums enhance type safety:
Validates values
Enums ensure that only valid values can be used, making code less
prone to errors.
Detects errors
The compiler will notify you if you mistype a case label or a value in
an assignment.
Improves readability
Enums make code more readable and understandable by representing
the logical grouping and the intended object explicitly.
Centralizes changes
Changes to enums are centralized, making the code easier to update
and maintain.
EXAMPLE:
Oops Assignment-2
16. Describe wrapper classes in Java. Explain the importance of
wrapper classes and give examples of their usage with primitive data
types.
ANS
In Java, wrapper classes are parent classes that allow users to use
primitive data types as objects. They are used to make primitive data
types more efficient and manageable.
Here are some reasons why wrapper classes are important:
Object-oriented compatibility
Wrapper classes allow primitive data types to participate in object-
oriented programming paradigms like inheritance, polymorphism, and
encapsulation.
Nullable values
Primitive data types cannot represent null values, but wrapper classes
can. This is important in certain scenarios, such as when dealing with
databases or APIs.
Working with collections
Wrapper classes allow programmers to bind the values of different
primitive data types into objects, which helps when working with
collections like HashMap and ArrayList.
Utility functions
Wrapper classes provide different utility functions that can be used
with primitive data types
Example of Usage with Primitive Data Types
Oops Assignment-2
17. Explain autoboxing and unboxing in Java. How does autoboxing
simplify code? Provide an example to illustrate.
ANS
Autoboxing is the process by which primitive data types are
automatically converted into their corresponding wrapper objects,
while unboxing involves the automatic extraction of the primitive
value from the wrapper object.
Autoboxing feature greatly simplifies code because it eliminates the
need for manual conversion between primitives and wrapper objects.
As a result, you can focus more on the logic of your program rather
than dealing with tedious type conversions.Autoboxing is particularly
useful when working with collections (like ArrayList) that require
objects but the programmer often wants to work with primitive types
(like int, double, etc.).
EXAMPLE:

18. Discuss the use of enumerations in switch statements. Provide an


example to demonstrate their application.
ANS
An Enum is a unique type of data type in java which is generally
a collection (set) of constants. More specifically, a Java Enum type is
a unique kind of Java class. An Enum can hold constants, methods,
etc. An Enum keyword can be used with if statement, switch
statement, iteration, etc.
 enum constants are public, static, and final by default.
Oops Assignment-2
 enum constants are accessed using dot syntax.
 An enum class can have attributes and methods, in addition to
constants.
 You cannot create objects of an enum class, and it cannot extend
other classes.
 An enum class can only implement interfaces.
EXAMPLE:

19. Describe the valueOf() and values() methods in Java


enumerations. Explain their purpose with examples.
ANS
VALUEOF():
It is a static method present in the String class. It is used to convert
any data type, such as int, double, char, or char array, to its string
representation by creating a new String object. We can also use
valueOf() to convert a char array or a subarray of a char array to a
String.
Oops Assignment-2
EXAMPLE

Value():
In Java, value() is not a built-in method, but it could refer to retrieving
the value of a variable or an object.
EXAMPLE

 We create a class SimpleValue with a private instance variable


value.
 The constructor initializes this value when an object is created.
 The method value() simply returns the stored value.
 In the main method, we create an instance of SimpleValue with
a specific value (42) and print it using the value() method.

You might also like