Page 394 - CITS - Computer Software Application -TT
P. 394
COMPUTER SOFTWARE APPLICATION - CITS
Java final Example
Let’s consider the following example where we declare final variable age. Once declared it cannot be
modified.
FinalExampleTest.java
public class FinalExampleTest {
//declaring final variable
final int age = 18;
void display() {
// reassigning value to age variable
// gives compile time error
age = 55;
}
public static void main(String[] args) {
FinalExampleTest obj = new FinalExampleTest();
// gives compile time error
obj.display();
}
}
Output
In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final
using the final keyword.
Java finally Example
Let’s see the below example where the Java code throws an exception and the catch block handles that exception.
Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.
FinallyExample.java
public class FinallyExample {
public static void main(String args[]){
381
CITS : IT&ITES - Computer Software Application - Lesson 101 - 108 CITS : IT&ITES - Computer Software Application - Lesson 101 - 108