Java Question Bank Answers
Java Question Bank Answers
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors – wagging the tail, barking, eating
Variable:
A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.
EX:
Parameters:
Parameters refers to the list of variables in a method declaration.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
3 What are the commands used for compilation and execution of java programs?
EX:
public class HelloWorld {
System.out.println("Hello, World")
}}
Compilation commands:
javac HelloWorld.java
java HelloWorld
Out Put :
Hello, World
1. Arithmetic Operators + - * / %
2. Unary Operators ++, --
3. Relational Operator ==, != , > ,< , >= , <=
4. Conditional Operator && (And ) , II (OR)
5. Assignment Operator = , += , -= , *= , /=
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
6.What is an abstraction?
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Example:
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
int x = 20;
int y = 50;
System.out.println(Math.min(x, y));
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically. The automatic conversion is
done by the compiler and manual conversion performed by the programmer. In this section,
we will discuss type casting and its types with proper examples.
Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically. It is safe because
there is no chance to lose data. It takes place when:
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
Let's see an example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Converting a higher data type into a lower one is called narrowing type casting. It is also known as
explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
double d = 166.66;
long l = (long)d;
int i = (int)l;
Output
The primary purpose of the "this" keyword is to refer to the current object.
Example:
class ThisExample
{
ThisExample ()
{
System.out.println("hello a");
}
ThisExample (int x){
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
ThisExample a=new ThisExample (10);
}
Example:
if(count<=5){
System.out.println("hello "+count);
p();
}
}
hello 4
hello 5
1. compile-time polymorphism
2. runtime polymorphism.
1. compile-time polymorphism :
Example:
return a + b;
return a + b;
2. Runtime polymorphism :
Example:
class Bike{
void run(){
System.out.println("running");
void run() {
b.run();
} }
Output:
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Eample Program:
class GFG {
// if memory is a constraint
byte b = 4;
// byte b1 = 7888888955;
short s = 56;
// short s1 = 87878787878;
// is double in java
double d = 4.355453532;
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
The Reference Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings,
objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a
string in Java is, that the string is designed to hold a sequence of characters in a single
variable whereas, a character array is a collection of separate char-type entities. Unlike
C/C++, Java strings are not terminated with a null character.
Example Program:
class Main {
public static void main(String[] args)
{
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
2 Arrays:
An array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Object oriented
Java is true object oriented language.
Almost “Everything is an Object” paradigm. All program code and data reside within objects
andclasses.
The object model in Java is simple and easy to extend.
Java comes with an extensive set of classes, arranged in packages that can be used in our
programsthrough inheritance.
Distributed
Java is designed for distributed environment of the Internet. Its used for creating
applications on
networks.
Java applications can access remote objects on Internet as easily as they can do in local
system.
Java enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
Interpreted
Robust
It provides many features that make the program execute reliably in variety of
environments.
Java is a strictly typed language. It checks code both at compile time and runtime.
Java language and Java Virtual Machine helped in achieving the goal of “write once;
run anywhere,any time, forever.” Changes and upgrades in operatingsystems,processors
and system resources will not force any changes in Java Programs.
Portable
Java Provides away to download programs dynamically to all the various types of
platforms connected to the Internet. It helps in generating Portable executable code.
High performance:
Java performance is high because of the use of bytecode.The bytecode was used, so
that it was easily translated into native machine code.
Multithreaded:
Multithreaded Programs handled multiple tasks simultaneously, which was helpful in
creating interactive, networked programs.Java run-time system comes with tools that
support multiprocess synchronization used to construct smoothly interactive systems.
Dynamic:
Java is capable of linking in new class libraries, methods, and objects.
It can also link native methods (the functions written in other languages such as C and C++).
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
1.Array Declaration
dataType arr[];
int a[10]
2. Array crteation
array RefVar =new datatype[size];
int a[]=new int[5]
3. Array initialization
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
4.What is a constructor? Explain the purpose of constructor with Example program?
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Example :
class Bike {
//creating a default constructor
Bike() {
System.out.println("Bike is created");
}
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
2. Parameterized constructor:
Example Program:
class Student4{
int id;
String name;
id = i;
name = n;
}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
void display()
{System.out.println(id+" "+name);
s1.display();
s2.display();
}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
package nameofPackage;
{
Body of the class
}
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a class does not extend any other class then it is a direct child class of Object and if
extends another class then it is indirectly derived. Therefore the Object class methods are available to
all Java classes. Hence Object class acts as a root of the inheritance hierarchy in any Java Program.
4. Explain subclass ?
A subclass is a class derived from the superclass. It inherits the properties of the superclass and also
contains attributes of its own.
A subclass inherits the methods and instance data of its superclasses, and is related to its superclasses
by an is-a relationship
The super keyword in Java is a reference variable that is used to refer to parent class when we’re
working with objects.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
The final keyword in Java is a non-access modifier, which restricts the user and defines entities that
cannot be changed or modified. It plays a prominent role when you want a variable to always store the
same value. The final keyword in Java is used to enforce constancy or immutability and specifies that
the value of the variable or element should not be modified or extended further.
Abstract class
Interface
1) Interface can have only abstract methods. Since Java 8, it can have default and static methods
Also
The java.io package is used to handle input and output operations. Java IO has various classes that
handle input and output sources. A stream is a sequence of data.
Java input stream classes can be used to read data from input sources such as keyboard or a file.
Similarly output stream classes can be used to write data on a display or a file again.
We use the extends keyword to inherit properties and methods from a class. The class that acts as a
parent is called a base class, and the class that inherits from this base class is called a derived or a child
class. Mainly, the extends keyword is used to extend the functionality of a parent class to the derived
classes
On the other hand, we use the implements keyword to implement an interface. An interface consists
only of abstract methods. A class will implement the interface and define these abstract methods as
per the required functionality. Unlike extends, any class can implement multiple interfaces.
Benefits of Inheritance :
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance leads
to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by the
derived class.
Costs of Inheritance :
Inheritance decreases the execution speed due to the increased time and effort it takes, the program
to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one
cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
Hierarchical Inheritance :
interface MyInf {
//Method Declaration
void Method1();
//Method definition
System.out.println("Method1() called");
//Method definition
System.out.println("Method2() called");
//Method definition
System.out.println("Method3() called");
S2.Method1();
S2.Method2();
S3.Method1();
S3.Method3();
Multiple Inheritance :
interface Printable{
void print();
interface Showable{
void show();
obj.print();
obj.show();
To access attributes (fields) of the superclass if both superclass and subclass have attributes with the
same name.
To explicitly call superclass no-arg (default) or parameterized constructor from the subclass
constructor.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
class Animal {
class Main {
dog1.printType();
Benefits of packages :
Avoid naming conflicts. For example, there can be two classes with the name Student in two packages,
university.csdept.Student and college.itdept.Student
Provide controlled access: The access specifiers protected and default have access control on package
level. A member declared as protected is accessible by classes within the same package and its
subclasses. A member without any access specifier that is default specifier is accessible only by classes
in the same package.
Benefits of Interfaces :
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Achieving Abstraction: Interfaces allow you to achieve total abstraction, where you define a contract
without specifying the implementation details. This enables you to separate the interface from the
implementation, making your code more modular and maintainable.
Java Interfaces Can Have Multiple Inheritance: Java classes can only inherit from a single superclass,
but interfaces can implement multiple interfaces. This allows you to receive behavior from multiple
sources, enhancing code reusability and flexibility.
Achieving Loose Coupling: Interfaces facilitate loose coupling between components of your code. By
depending on them rather than concrete classes, you can easily swap implementations without
affecting the clients that use those interfaces.
Class Interface
A class can be
An Interface cannot be instantiated i.e. objects
instantiated i.e., objects of
cannot be created.
a class can be created.
It can contain
It cannot contain constructors.
constructors.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
A classpath environment variable is the location from which classes are loaded at runtime by JVM in
java.
What is Path? A path is a unique location of a file/ folder in a OS. PATH variable is also called system
variable or environment variable.
JAVA_HOME &
PATH >
variable value: C:\Program Files\Java\jdk1.7.0_51 (Directory in which java has been installed)
Then enter -
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).
Types of Inheritance
Single Inheritance
Multi-level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
class Employee
float salary=34534*12;
float bonus=3000*6;
Multi-level Inheritance
In multi-level inheritance, a class is derived from a class which is also derived from another class is
called multi-level inheritance. In simple words, we can say that a class that has more than one parent
class is called multi-level inheritance. Note that the classes must be at different levels. Hence, there
exists a single base class and single derived class but multiple intermediate base classes.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
class Student
int reg_no;
reg_no=no;
void putNo()
float marks;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
void getMarks(float m)
marks=m;
void putMarks()
System.out.println("marks= "+marks);
//derived class
float score;
score=scr;
void putScore()
System.out.println("score= "+score);
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
ob.getScore(68.7);
ob.putScore();
Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical inheritance.
class Student
{
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
2.Write the procedure to create a package with multiple public classes and also explain how to
access a package ?
Java package is a mechanism of grouping similar type of classes, interfaces, and sub-classes collectively
based on functionality. When software is written in the Java programming language, it can be
composed of hundreds or even thousands of individual classes. It makes sense to keep things organized
by placing related classes and interfaces into packages.
Creating packages
First declare the name of the package using the package keyword followed by a package name
Package firstpackage;
----------------------
---------------------
Here the package name is firstpackage, the class firstclass is now considered a part of this package
package mypack;
int length,breadth,height;
length=l;
breadth=b;
height=h;
return length*breadth*height;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
int r;
r=rr;
return (3.14f*r*r);
3 . Explain the concept of importing packages and write a program that implements the importing
concept
Here pkg1 is the name of top level package , and pkg2 is the name of subordinate package inside
outer package separated by a dot. * indicate that the java compiler should import the entire package
Import java.io.*
Package Mypack;
String name;
Double bal;
name = n;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
bal = b;
If ( bal < 0 )
The Balance class is now public and its show ( ) method are public . this means that they can be
accessed by any type of code outside the mypack package
Example here TestBalance imports MyPack and is then able to make use of the Balance class
Import MyPack. *;
Class TestBalance
Test . show ( );
4. How do you design and implement an interface in java ? how can you extend one interface by the
other interface ?
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the methods declared in
the interface.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
interface <interface_name>{
// by default.
interface printable{
void print();
obj.print();
An interface contains variables and methods like a class but the methods in an interface are abstract
by default unlike a class. An interface extends another interface like a class implements an interface in
interface inheritance.
interface A {
void funcA();
interface B extends A {
void funcB();
class C implements B {
System.out.println("This is funcA");
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
System.out.println("This is funcB");
C obj = new C( );
obj.funcA( );
obj.funcB( );
}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
1. What is an Error?
An error is a serious problem that typically occurs during compilation (before the program
runs). Errors often indicate syntax violations or resource limitations that prevent the program from
being created or executed correctly.
An exception is an event that disrupts the normal flow of a program's execution at runtime. It
usually signals an unexpected condition or error.
Checked Exceptions: These exceptions must be declared in the method's signature using
throws keyword. They represent recoverable errors, like IOException for file operations.
Unchecked Exceptions: These exceptions don't need explicit declaration. They represent
programming errors or runtime conditions, like NullPointerException when accessing a null reference.
Java
try {
} finally {
.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Java provides a rich set of built-in exception classes for common error scenarios. Some
examples include:
Runtime errors: Exceptions are a specific type of runtime error that occurs during program
execution. Other runtime errors could be memory access violations or infinite loops.
Logical errors: These are mistakes in the program's logic that cause incorrect behavior even
if it executes without errors. Examples include typos in variable names or flawed algorithms.
Java provides a rich set of built-in exception classes to handle common error scenarios during
program execution. Here are some frequently encountered exceptions:
3. ClassCastException: Thrown when you attempt to cast an object to a type that it's not
compatible with. For example, trying to cast a String object to an Integer object.
4. FileNotFoundException: Thrown when a file you're trying to open or access cannot be found
in the specified location.
5. IOException: A broader exception class for various input/output (I/O) related errors, like
network connection issues or file access problems.
6. NullPointerException: Thrown when you attempt to use a reference variable that has not
been initialized (i.e., it's null) and try to access its members or methods.
7. NumberFormatException: Occurs when you try to convert a string that doesn't represent a
valid number format (e.g., "hello") into a numerical type (e.g., int or double).
This is not an exhaustive list, but it covers some of the most common built-in exceptions you'll
encounter in Java programming. By understanding these exceptions and how to handle them
appropriately, you can write more robust and user-friendly code.
Improved program robustness: Exception handling allows programs to gracefully recover from
unexpected errors instead of crashing abruptly.
Enhanced code readability: Exception handling separates error handling code from the main
program logic, making the code more maintainable and easier to understand.
Increased reusability: Exception handling mechanisms can be reused across different parts of
a program, promoting code reuse and consistency.
Better error diagnostics: Exceptions provide detailed information about the error, aiding
debugging and troubleshooting.
3. Write a Java program that illustrates the application of multiple catch statements?
try {
} catch (NumberFormatException e) {
} catch (Exception e) {
}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
Explanation:
The try block attempts to parse the string "hello" into an integer, which will trigger a
NumberFormatException.
The second catch block serves as a catch-all for any other exceptions that might occur.
try {
System.out.println(numbers[4]); // ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e) {
catch (ArithmeticException e)
} finally {
Explanation:
• The finally block executes always, regardless of exceptions within the try block. It's ideal for
releasing resources or performing cleanup tasks.
• The program continues execution after exception handling (if no exceptions were thrown).
2.Write a program with nested try statements for handling exceptions and how to create a user
defined exception?
try {
} catch (ageException e) {
System.out.println(e.getMessage());
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
try {
} catch (Exception e) {
if (age < 0) {
return age;
super(message);
Explanation:
• The validateAge method throws a custom AgeException if the age is invalid. This exception is
handled in the main method's outer catch block.
• The inner try-catch handles any exceptions that might occur within the System.out.println
statement.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
3.Explain the use of try,catch,throw,throws and finally in detail with example program?
try:
catch:
throw:
throws:
• Declares exceptions that a method might throw but doesn't handle itself.
• It informs the caller that the method might throw these exceptions.
finally:
• Executes always, regardless of whether exceptions occur within the try block.
• It's commonly used for resource management (closing files, database connections) or
performing cleanup tasks.
try {
} catch (ArithmeticException e) {
} finally {
System.out.println("Cleaning up resources...");
}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY
int result = 10 / 0;
Explanation:
1. main method:
o The try block calls the divideByZero method, which might throw an exception.
2. divideByZero method:
o The throws ArithmeticException clause in the method signature declares that this exception
might be thrown.
Key Points:
• try and catch: Work together for exception handling. try encloses risky code, and catch
captures thrown exceptions.
• throws: Declares potential exceptions that a method might throw, informing the caller.
• finally: Always executes, regardless of exceptions, making it ideal for resource management
and cleanup.
Remember:
• Use exception handling strategically to make your code more robust and easier to maintain.
• Provide meaningful error messages for better debugging and user experience.