Professional Documents
Culture Documents
class Rectangle {
double length;
double breadth;
}
// This class declares an object of type Rectangle.
class RectangleDemo {
public static void main(String args[]) {
Rectangle myrect = new Rectangle();
double area;
// assign values to myrect's instance variables
myrect.length = 10;
myrect.breadth = 20;
// Compute Area of Rectangle
area = myrect.length * myrect.breadth ;
System.out.println("Area is " + area);
}
}
Output :
C:Priteshjava>java RectangleDemo
Area is 200.0
[336280]
class declaration only creates a template. It does not create an actual object.
2. Creation of Object
Rectangle myrect = new Rectangle();
Actual Creation of Object.
This Statement will create instance of the class Ractangle and name of instance is
nothing but actual object myrect.
Fresh copy of Instance variables gets created for Fresh Instance. [myrect now have its
own instance variables -> length,breadth ]
Following fig shows one unknown term Constructor (Dont worry about this term ,
you will get more details in the incoming chapters)
As explained earlier , Each Instance/Object gets their own copy of instance variables i.e
length and breadth.
We can access myrects copy of instance variable using DOT operator (as shown
above).
Live Example : Class With Two Objects (Each have its own
copy of Instance Variable
class Rectangle {
double length;
double breadth;
}
// This class declares an object of type Rectangle.
class RectangleDemo {
public static void main(String args[]) {
Rectangle myrect1 = new Rectangle();
Rectangle myrect2 = new Rectangle();
double area1,area2;
// assign values to myrect1's instance variables
myrect1.length = 10;
myrect1.breadth = 20;
// Compute Area of Rectangle
area1 = myrect1.length * myrect1.breadth ;
System.out.println("Area of Rectange 1 : " + area1);
// assign values to myrect2's instance variables
myrect2.length = 10;
myrect2.breadth = 20;
// Compute Area of Rectangle
area1 = myrect2.length * myrect2.breadth ;
System.out.println("Area of Rectange 2 : " + area2);
}
Explanation :
2. As soon as above two statements gets executed , two objects are created
with specimen copy of their instance variables.
3. In short myrect1s version of lemgth and breadth gets created . Similarly
myrect2s version of length and breadth gets created.
4. Using dot Operator we can access instance variable of respective object.
myrect2.length = 5;
myrect2.breadth = 10;
this statement is used to create an object we are going to break down this statement in two
separate statements
Rectangle myrect1 ;
myrect1 = new Rectangle();
In short
1. First statement will just create variable myrect1 which will store address of actual object.
2. First Statement will not allocate any physical memory for an object thus any attempt
accessing variable at this stage will cause compile time error.
3. Second Statement will create actual object ranndomly at any memory address where it
found sufficient memory.
4. Actual memory address of Object is stored inside myrect1.
Output :
C:Priteshjava>javac RectangleDemo.java
RectangleDemo.java:10: variable myrect1 might not have
been initialized
System.out.println(myrect1.length);
^
1 error
[46860]
is similar to
Rectangle myrect1 = null;
Invalid Declaration :
Rectangle myrect1 ;
r2 is initialized with r1 means r1 and r2 both are referring same object , thus it does
not create duplicate object , nor does it allocate extra memory.
[46
860]
Output :
C:Priteshjava>java RectangleDemo
Value of R1's Length : 20.0
Value of R2's Length : 20.0
Typical Concept :
Suppose we have assigned null value to r2 i.e
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
.
.
.
r1 = null;
Note : Still r2 contain reference to an object. Thus We can create have multiple reference
variables to hold single object.
Method Name :
1. Method name must be valid identifier.
2. All Variable naming rules are applicable for writing Method Name.
Parameter List :
1. Method can accept any number of parameters.
2. Method can accept any data type as parameter.
3. Method can accept Object as Parameter
4. Method can accept no Parameter.
5. Parameters are separated by Comma.
6. Parameter must have Data Type
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.length = 10;
System.out.println("Before Function Length : " + r1.length);
r1.setLength(20);
System.out.println("After Function Length : " + r1.length);
}
Output :
C:Priteshjava>java RectangleDemo
Before Function Length : 10.0
After Function Length : 20.0
Explanation :
Calling a Method :
1. r1 is an Object of Type Rectangle.
2. We are calling method setLength() by writing
Object_Name [DOT] Method_Name ( Parameter List ) ;
Method Definition :
1. Method Definition contain the actual body of the method.
2. Method can take parameters and can return a value.
Output :
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
specified by the method. For example, if the return type of some method is boolean, you
could not return an integer.
boolean getLength()
{
int length = 10;
return(length);
}
2. The variable receiving the value returned by a method (such as len, in this case)
must also be compatible with the return type specified for the method.
int getLength()
{
return length;
}
boolean len = r1.getLength();
r1.setDiamentions(20,10);
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
}
Output :
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
In order to hide instance variable we can use this keyword. above syntax will clearly
make difference between instance variable and parameter.
Java Constructors
Output :
C:Priteshjava>javac RectangleDemo.java
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
Explanation :
1. new Operator will create an object.
2. As soon as Object gets created it will call ConstructorRectangle()
{
//This is Constructor
length = 20;
breadth = 10;
}
3. In the above Constructor Instance Variables of Object r1 gets their own values.
4. Thus Constructor Initializes an Object as soon as after creation.
5. It will print Values initialized by Constructor
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
Output :
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
Length of Rectangle : 40
Breadth of Rectangle : 20
Explanation :
1. After the Creation of Object , Instance Variables have their own values inside.
2. As soon as we call method , values are re-initialized.
Parameterized Constructors :
1. Constructor Can Take Value , Value is Called as Argument.
2. Argument can be of any type i.e Integer,Character,Array or any Object.
3. Constructor can take any number of Argument.
4. See following example How Parameterized Constructor Works ?
Output :
Length of Rectangle : 20
Breadth of Rectangle : 10
Explanation :
Carefully observe above program You will found something like this
Rectangle r1 = new Rectangle(20,10);
This is Parameterized Constructor taking argument.These arguments are used for any purpose
inside Constructor Body.
OR
Rectangle(int length,int breadth)
{
this.length = length;
this.breadth = breadth;
}
But if we use Parameter name same as Instance variable then compiler will recognize instance
variable and Parameter but user or programmer may confuse. Thus we have used this keyword
to specify that Variable is Instance Variable of Object r1.
Explanation :
1. Garbage Collection is Done Automatically by JVM.
2. As soon as compiler detects that Object is no longer needed inside program , Garbage
Collection Algorithm gets executed automatically to free up memory from the heap so
that free memory may be used by other objects .
3. Different Java Run times may have different approaches for Garbage Collection. [This
is required information to understand Garbage Collection Doing Further R&D you
may visit this]
Method Overloading :
1. In Java we can define number of methods in a class with the same name.
2. Defining two or more methods with the same name in a class is called method
overloading.
3. Compile determine which method to execute automatically.
4. The return type has no effect on the signature of a method.
Or
int display(double num1,int num2);
Or
void display(double num1,double num2);
Live Example :
package com.pritesh.programs;
class Rectangle {
double length;
double breadth;
void area(int length, int width) {
int areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
void area(double length, double width) {
double areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.area(10, 20);
r1.area(10.50, 20.50);
}
}
Explanation :
1. We have defined 2 methods with same name and different type of parameters.
2. When both integer parameters are supplied to the method then it will execute method
with all integer parameters and if we supply both floating point numbers as parameter
then method with floating numbers will be executed.
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
Explanation :
1. We can pass Object of any class as parameter to a method in java.
2. We can access the instance variables of the object passed inside the called method.
area = r1.length * r1.width
r2.area(r1.length, r1.width);
Actually this is not a way to pass the object to method. but this program will explain you how to
pass instance variables of particular object to calling method.
r2.area(r1.length, r1.width);
import java.io.File;
import java.io.IOException;
class Rectangle {
int length;
int breadth;
Rectangle(int l,int b) {
length = l;
breadth = b;
}
Rectangle getRectangleObject() {
Rectangle rect = new Rectangle(10,20);
return rect;
}
class RetOb {
public static void main(String args[]) {
Rectangle ob1 = new Rectangle(40,50);
Rectangle ob2;
ob2 = ob1.getRectangleObject();
System.out.println("ob1.length : " + ob1.length);
System.out.println("ob1.breadth: " + ob1.breadth);
System.out.println("ob2.length : " + ob2.length);
System.out.println("ob2.breadth: " + ob2.breadth);
}
}
40
50
10
20
Explanation :
1. In the above program we have called a method getRectangleObject() and the method
creates object of class from which it has been called.
2. All objects are dynamically allocated using new, you dont need to worry about an object
going out-of-scope because the method in which it was created terminates.
3. The object will continue to exist as long as there is a reference to it somewhere in your
program. When there are no references to it, the object will be reclaimed the next time
garbage collection takes place.
Term
Definition
Inheritance
Subclass
Superclass
Keywords Used
Hence
WagonR
IS-A Vehicle
instanceof
instanceof
instanceof
instanceof
Vehicle);
Vehicle);
Vehicle);
FourWheeler);
}
}
Output :
true
true
true
true
InstanceOf Operator :
In the above example we have used this following statement
System.out.println(v1 instanceof Vehicle);
the instanceof operator is used to check whether TwoWheeler is actually a Vehicle, and
FourWheelet is actually a Vehicle.
Extends Keyword :
We can extend a class by using the extends keyword in a class declaration after the class name
and before the parent class.
public class ParentClass {
}
Type
Super
Class
Name
Explanation
ParentClass The class from which another class is derived is called the superclass
The derived class (the class that is derived from another class) is called a
subclass
Consider we are storing the information of the student, then we may create a class like below
Class Student {
int roll;
String sname;
Address address;
}
In the above class we have entity reference Address which stores again its own information
like street,city,state,zip. like below
Class Address {
String street;
String state;
String zip;
String city;
}
so we can say that Student HAS-A Address Thus if the class has entity reference then entity will
represent the HAS-A relationship.
Consider the following example
Address.java
public class Address {
String
String
String
String
street;
city;
state;
zip;
Student.java
public class Student {
int roll;
Address address;
Student(int rollNo,Address addressDetail){
roll = rollNo;
address = addressDetail;
}
void printStudentDetails(Address address1) {
System.out.println("Roll
: " + roll);
System.out.println("Street : " + address1.street);
System.out.println("City
: " + address1.city);
System.out.println("State : " + address1.state);
System.out.println("Zip
: " + address1.zip);
}
Output :
Roll
Street
City
State
Zip
:
:
:
:
:
1
1-ST
PN
Mah
41
1. You can see the above code in which we already have the class Address which is used
to store the details of address. Thus using aggregation we have reused the existing class.
2. Inheritance can be achieved only using the IS-A relationship but using this HAS-A we
can use existing code more efficiently.
Output :
Compile Time Error
Explanation :
1. From subclass we cannot access the private members of the superclass.
2. subclass you can access its superclasss public and protected methods and fields
3. If the subclass and the superclass are in the same package, you can also access the
superclasss default methods and fields
We want to provide the different implementation to talk() method for Male and Human class.
Using override we can provide different implementations for talk() in Parent Class and in Child
Class.
TwoWheeler.java
package com.c4learn.inheritance;
public class TwoWheeler extends Vehicle {
public void vehicleMethod() {
System.out.println("Method" + " in TwoWheeler.");
}
public static void main(String[] args) {
TwoWheeler myBike = new TwoWheeler();
Vehicle myVehicle = new Vehicle();
myVehicle.vehicleMethod();
myBike.vehicleMethod();
}
}
In the above example, method is having the same set of parameter list
public int calculate(int num1,int num2)
then we cannot change the return type of the method in the overriden method.
Allowed ?
Public
Public
Allowed
Public
Private
Not Allowed
Public
Protected
Not Allowed
Protected
Public
Allowed
Protected
Protected
Allowed
Protected
Private
Following method will throw compile time error
package com.c4learn.inheritance;
public class InheritanceRules {
Not Allowed
because in the parent class, Method has Access level public while we have made access level as
private in the child class.
then child class cannot override static method from parent class but it can redeclare it just by
changing the method body like this
public static int calculate(int num1,int num2) {
return num1*num2;
}
however we have to keep the method static in the child class, we cannot make it non-static in the
child class, So following method declaration inside child class will throw error
Output :
result : 20
In this example we have same method declared inside parent and child class.
public void display() {
System.out.println("result : " + super.getValue());
}
In order to execute the parent method from the child class we need to use super keyword.
Understanding Constructors :
package com.c4learn.inheritance;
public class ParentClass {
public ParentClass()
{
System.out.println("Hello Parent");
}
System.out.println("Hello Child");
public ChildClass()
{
super(5);
System.out.println("Hello Child");
}
Now In the above program, we have written two constructors one with no argument and another
with single integer argument.
public ParentClass()
{
System.out.println("Hello Parent");
}
public ParentClass(int val)
{
System.out.println("Hello Parameter");
}
As we have explicitly called the single argument constructor using the super keyword, Parent
Classs Parameterized Constructor gets called.
If we write it after other statements then it will throw compile time error
Output :
Compile Time Error
We cannot modify the value of the final variable, we will get following error message
void setShape() {
// Error Here
SHAPE_SIDES = 4;
}
Output :
Compile Time Error
In this example we have declared method as final so we cannot override the final method,
otherwise we will get compile time error
Output :
Compile Time Error
In this example we have declared class as final so we cannot inherit the final class
Description
Final Value
Final Method
Final Class
Final Class cannot be inherited
2. Final Variable must be initialized at the time of declaration or inside constructor
3. Re-Assigning Value is not allowed for final member variable
4. Local Final Variable should be initialized during the time of declaration
5. Final and Finally both are different. Finally keyword is used on Exception handling in
Java
A. Up Casting :
You can cast an instance of a child class to its parent class. Casting an object of child class to a
parent class is called upcasting.
v2 = new
TwoWheeler();
B. Down Casting :
Casting an object of a parent class to its child class is called downcasting.
Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle. Following
is an example of the down casting
TwoWheeler v3 = (TwoWheeler) new
Vehicle();
In the above example we can say that String Hello World written inside System.out.println
will be called as String Literal.
Consider above program we can see, String Hello will be created inside String Constant
Pool and then reference to that String is being assigned to a String Object Str2.
Consider the below program
class FirstProgram {
public static void main(String[] args) {
String Str1 = "Hello";
String Str2 = "Hello";
}
}
In this program, Only Single Object will be created inside Constant Pool and reference to that
String will be returned to both Objects Str1 and Str2.
myName = "PRABHU";
System.out.println("Hello " + myName);
}
Explanation :
String myName = "PRASHAN";
Now when we assign another string literal to String Object then earlier string will be discarded.
myName = "PRABHU";
Actual String can be stored anywhere in the heap but String Object myName will locate the
position of the String PRABHU and stores the reference to that actual string.
Object/Variable
Memory Location
AKASH
Object
new String("AKASH")
Object
myName
Reference Variable
*Reference Variable is Pointing to a String Object new String(AKASH)
: Immutable String
What is Immutable Objects ?
When you have a reference to an instance of an object, the contents of that instance cannot be
altered
Consider the following example
class ImmutableString {
Output of Program :
I am living in India
I am living in India
though object is created for I am living in USA string but reference variable myString is
still not referring to new string. We need to specify the reference explicitly using following
assignment
myString = myString.replaceAll( "India" , "USA" );
class ImmutableString {
public static void main(String[] args) {
String myString = new String("I am living in India");
System.out.println( myString );
myString = myString.replaceAll( "India" , "USA" );
System.out.println( myString );
}
}
myString = 10 + 10 + Str3;
System.out.println("Complete Statement : " + myString);
}
Output :
Complete Statement : I love my country India
Complete Statement : India1010
Complete Statement : 20India
Operand 2
Result of Concatenation
Integer
String
String
String
String
String
Integer
Integer
Integer
First Concatenation :
myString =
=
=
=
Second Concatenation :
myString =
=
=
=
Str3 + 10 + 10;
"India" + 10 + 10
"India10" + 10
"India1010"
Third Concatenation :
myString = 10 + 10 + Str3;
= 10 + 10 + "India"
= 20 + "India"
= "20India"
Comparing Strings
Way 1
Way 2
Using == Operator
Way 3
If we need to compare the content only then we can use 1st method specified above and if we
need to compare the strings and cases both then we can use 2nd method. Below are the examples
for using both the methods
class ComparingString{
public static void main(String args[]){
String str1="c4learn.com";
String str2="c4learn.com";
String str3="C4LEARN.com";
System.out.println(str1.equals(str2));//true
System.out.println(str1.equals(str3));//false
System.out.println(str2.equalsIgnoreCase(str3));//true
}
Output :
true
false
true
str1 and str2 both are referring the same object. Which makes str1 and str2 equal. While in case
of 2nd line
System.out.println(str1 == str3);
Though content of str1 and str3 is same, instance of str3 is not same as that of str1. str3 refers to
the instance that is created in the non-pool / heap.
Output :
0
1
-1
Java substring
In the last topic we have learnt about comparison of two strings and different ways of comparing
strings. In this topic we are going to see finding out the substring in Java.
This method returns new String object containing the substring of the given string from specified
startIndex.
class SubString{
public static void main(String args[]){
String str1 = "c4learn.com";
String str2 = "c4learn.com";
System.out.println(str1.substring(0));
System.out.println(str1.substring(8));
System.out.println(str1.substring(2));
}
Output :
c4learn.com
com
learn.com
This method returns new String object containing the substring of the given string from specified
startIndex to endIndex.
class SubString{
public static void main(String args[]){
String str1 = "c4learn.com";
System.out.println(str1.substring(0,2));
System.out.println(str1.substring(3,6));
System.out.println(str1.substring(2,8));
}
}
Output :
c4
ear
learn.
Explanation :
Consider statement
str1.substring(0,2)
It will include all the characters from 0 to 2 excluding the endIndex. i.e (0,1 will be included
only and 2 will be excluded)
1. When any error occures in a method then new object (i.e Exception Object) is created by
a method
2. Exception Object contain information about error such as type of error and state of the
program.
3. Newly created exception object is passed to the Runtime System.
4. Runtime system will handle the exception to keep system stable
In this example, we know that any number divided by 0 will cause program to go into
unexpected situation. If program contain such unexpected statements then its better to handle
these unexpected results. Below is the unexpected error output
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZeroNoExceptionHandling.main(
DivideByZeroNoExceptionHandling.java:7)
Now we have done slight modification in the program by providing exception handling code in
the program
public class ExceptionExample {
public static void main(String[] args) {
int num1 = 50;
int num2 = 0;
int ans;
try {
ans = num1 / num2;
System.out.println("Result of Division : " + ans);
} catch(ArithmeticException e) {
System.out.println("Divide by Zero Error");
}
}
}
Own Exception
Java Errors
Errors occurred due to JVM
below are the different types of Exception in Java
A. Checked exceptions :
1. A checked exception is an exception which is error or a problem occurred because of
code written by programmer
2. Checked Exception cannot be neglected by the programmer.
3. Suppose we are opening the file and file is not present then exception occurred during the
compile time can be considered as checked exception.
4. These exceptions cannot be ignored at the time of compilation.
5. Class that extend throwable class except RuntimeException and Error is considered as
Checked exception.
B. Runtime exceptions:
1. Classes that extent RuntimeException class is called as Runtime Exception.
C. Errors :
1. These are not exceptions but the problems that are beyond the control of the user or the
programmer.
2. For example, Stack overflow, Virtual Machine Memory,AssertionError
//Statement 1;
//Statement 2;
//Statement 3;
}catch(Exception e) {
//Exception Handling Code
}
above is the syntax of try catch block in java. If an exception occurred during the execution of
Statement 1..3 then it will call exception handling code.
Legal Statement
Present
Present
Present
Present
Present
Consider the above example We know that division of any number with zero is not possible.If
we attempt to divide any number by zero in java then it may cause an error.
result = number1 / number2;
above statement may cause an exception so we need to put that code inside try block. Whenever
an exception occures the catch block gets executed.
} catch(ArithmeticException e) {
System.out.println("Divide by Zero Error");
}
Inside catch we have simply displayed an error message i.e Divide by Zero Error.
If we execute the above code instead then thrown exception is of type Arithmetic Exception
and Exception Type provided into Catch block is of type FileNotFoundException then
exception may not be catched. Thus above code can cause compile time error.
try {
result = number1 / number2;
System.out.println("Result of Division : " + ans);
}catch(Exception e) {
System.out.println("Divide by Zero Error");
}
In the above code we can catch all types of exception because Exception is superclass of all the
exceptions. [Refer the Exception Hierarchy]
num1 = 10;
num2 = 0;
result = 0;
arr[] = new int[5];
try {
arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
arr[5]
=
=
=
=
=
=
0;
1;
2;
3;
4;
5;
Output :
Err: Array Out of Bound
In the above example we have two lines that might throw an exception i.e
arr[5] = 5;
above statement can cause array index out of bound exception and
result = num1 / num2;
this can cause arithmetic exception. To Handle these two different types of exception we have
included two catch blocks for single try block.
}catch (ArithmeticException e) {
System.out.println("Err: Divided by Zero");
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Err: Array Out of Bound");
}
Now Inside the try block when exception is thrown then type of the exception thrown is
compared with the type of exception of each catch block.
If type of exception thrown is matched with the type of exception from catch then it will execute
corresponding catch block.
Notes :
1. At a time only single catch block can be executed. After the execution of catch block
control goes to the statement next to the try block.
2. At a time Only single exception can be handled.
3. All the exceptions or catch blocks must be arranged in order. [Refer the Exception
Hierarchy]
1. All the exceptions will be catched in the First Catch block because Exception is
superclass of all the exceptions.
2. In the above program ArrayIndexOutOfBoundsException is an subclass of Exception
Class.
Writing above code will throw following error message after compiling it
Unreachable catch block for ArrayIndexOutOfBoundsException.It is already handled by the
catch block for Exception
1. If in a try block we need to handle multiple exceptions then we need to write exception
handler for each type of exception.
2. We can combine the multiple exceptions in catch block using Pipe (|) Operator.
catch (IOException|SQLException ex) {
System.out.println("Exception thrown");
throw ex;
}
above single catch block can handle IO as well as SQL exceptions. So it is better to use Pipe
Operator to handle multiple exceptions instead of writing individual catch block for each
exception. Also Refer this oracle guide for more information.
both these lines will generate exception.If we put both these codes in same try block then it will
generate one exception and the next code wont be executed.
public class ExceptionExample {
public static void main(String argv[]) {
int
int
int
int
num1 = 10;
num2 = 0;
result = 0;
arr[] = new int[5];
try {
try {
arr[5] = 5;
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Err: Array Out of Bound");
}
try {
result = num1 / num2;
}catch (ArithmeticException e) {
System.out.println("Err: Divided by Zero");
}
System.out.println("Result of Division : " + result);
}catch (Exception e) {
System.out.println("Exception Occured !");
}
}
In the above nested try block code each and every exception is handled. In order to handle each
exception we need to use try block.
try {
------------} catch(Exception e) {
------------}
finally {
}
int i = 10/10;
} catch(Exception ex){
System.out.println("Inside 2nd catch Block");
} finally {
System.out.println("Inside 2nd finally block");
}
In the 1st try statement block we can see that we dont have finally block but in the 2nd try block
we have finally block. So finally block is always optional.
finally {
System.out.println("Inside 2nd finally block");
}
2nd try block does not throw any exception but still after the execution of try block code
executes finally statement block
Output :
Inside 1st catch Block
Inside 2nd finally block
1. If following statement is included in the try block (Terminating code using system exit)
System.exit(0);
2. If the thread executing the try or catch code is interrupted or killed, the finally statement
throw Keyword :
1. The throw keyword is used to explictily throw an exception.
2. We can throw either checked or uncheked exception. The throw keyword is mainly used
to throw custom exception.
Requirement :
We want to show an error message if the marks of student are below 75. We need to throw an
error message Please reappear for exam.
class StudentExcepeption{
static void validateMarks(int age){
if(marks < 75)
throw new ArithmeticException("Reappear for exam");
else
System.out.println("Student is having Distinction");
}
public static void main(String args[]){
validateMarks(71);
System.out.println("Remaining code...");
}
}