Saturday, 20 April 2019

Java Final Keyword – A Complete Guide with Examples

Introduction

In Java, the final keyword is a non-access modifier that can be applied to variables, methods, and classes. It is used to impose restrictions and ensure certain values, behaviors, or structures remain unchanged during program execution.

In simple words:

  • Final variable → Constant value (cannot be changed once assigned).
  • Final method → Cannot be overridden.
  • Final class → Cannot be inherited.

This makes final a very powerful tool in ensuring immutability, security, and proper design in Java applications.

1. Final Variables in Java

When a variable is declared as final, its value cannot be changed once assigned.

Syntax:

final double INTEREST_RATE = 0.05;

Example: Final Variable

In banking, the interest rate is usually fixed and should not change once set.

class BankAccount {
    private String accountHolder;
    private double balance;
    final double INTEREST_RATE = 0.05;  // 5% fixed interest rate

    BankAccount(String holder, double amount) {
        this.accountHolder = holder;
        this.balance = amount;
    }

    void calculateInterest() {
        double interest = balance * INTEREST_RATE;
        System.out.println("Interest for " + accountHolder + " is: " + interest);
    }
}

public class FinalVariableRealExample {
    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount("Alice", 10000);
        acc1.calculateInterest();
    }
}

Key Points:

  • A final variable must be initialized at the time of declaration or inside a constructor.
  • Once assigned, its value cannot be modified.
  • Commonly used for constants (e.g., PI, MAX_VALUE).

2. Final Methods in Java

When a method is declared as final, it cannot be overridden by subclasses.

Example: Final Method

class Vehicle {
    final void startEngine() {
        System.out.println("Engine started");
    }
}

class Car extends Vehicle {
    // ❌ This will cause an error
    // void startEngine() {  
    //     System.out.println("Car engine started");
    // }
}

public class FinalMethodExample {
    public static void main(String[] args) {
        Car car = new Car();
        car.startEngine();
    }
}

Why use Final Methods?

  • To prevent subclasses from changing critical methods.
  • Ensures consistent behavior across inheritance hierarchy.

3. Final Classes in Java

When a class is declared as final, it cannot be extended (inherited).

Example: Final Class

final class Bank {
    void displayBankName() {
        System.out.println("Welcome to XYZ Bank");
    }
}

// ❌ Compile-time error: Cannot inherit from final class
// class MyBank extends Bank { }

public class FinalClassExample {
    public static void main(String[] args) {
        Bank bank = new Bank();
        bank.displayBankName();
    }
}

Why use Final Classes?

  • To prevent inheritance for security or design reasons.
  • Commonly used in classes like java.lang.String, java.lang.Math, and java.lang.System.

4. Final Parameters in Java

You can also declare method parameters as final. This ensures that the parameter’s value cannot be modified inside the method.

Example: Final Parameter

public class FinalParameterExample {
    void calculateSquare(final int number) {
        // number = number * number;  // ❌ Error: cannot assign a value to final variable
        System.out.println("Square: " + (number * number));
    }

    public static void main(String[] args) {
        FinalParameterExample obj = new FinalParameterExample();
        obj.calculateSquare(5);
    }
}

5. Blank Final Variable (Uninitialized Final Variable)

A final variable that is not initialized at declaration time is called a blank final variable.
It must be initialized in the constructor.

Example:

class Student {
    final int rollNumber;  // blank final variable

    Student(int roll) {
        rollNumber = roll;  // initialized in constructor
    }

    void display() {
        System.out.println("Roll Number: " + rollNumber);
    }
}

public class BlankFinalExample {
    public static void main(String[] args) {
        Student s1 = new Student(101);
        Student s2 = new Student(102);

        s1.display();
        s2.display();
    }
}

6. Static Final Variables (Constants)

A static final variable is used to define constants (commonly written in uppercase).

Example:

class Constants {
    static final double PI = 3.14159;
    static final int MAX_USERS = 100;
}

public class StaticFinalExample {
    public static void main(String[] args) {
        System.out.println("PI: " + Constants.PI);
        System.out.println("Max Users: " + Constants.MAX_USERS);
    }
}

Friday, 30 March 2018

Find odd or even Numbers in an Array

package com.tutorial4u;

import java.util.Scanner;

/*Java Program to Find odd or even Numbers in an Array*/
public class EvenOrOddInArray {
     public static void main(String[] args) {
           Scanner sc = new Scanner(System.in);

           System.out.print("Enter the size of Array : ");
           int num = sc.nextInt();
           int arr[] = new int[num];
           System.out.println("Enter all the element : ");
           for(int i=0;i<num;i++){
                arr[i]=sc.nextInt();
           }
           for (int i = 0; i <num; i++) {
                if (arr[i] % 2 == 0)
                      System.out.println("even");
                else
                      System.out.println("odd");
           }
     }
}


Output:

Enter the size of Array : 5
Enter all the element :
22
21
33
42
24
even
odd
odd
even
even

Sunday, 25 March 2018

Count Duplicate Character

package com.tutorial4u;

import java.util.HashSet;
import java.util.Scanner;

public class DuplicateCharCount {
     public static void main(String[] args) {
           int count = 0;
           System.out.print("Enter any String : ");
           Scanner sc = new Scanner(System.in);
           String str = sc.nextLine();
           char[] ch = str.toCharArray();
           System.out.print("Duplicate character are : ");
           for(int i = 0;i<ch.length;i++){
                for(int j = i+1;j<ch.length;j++){
                      if((ch[i] == ch[j]) && (i!=j)){
                           System.out.print(ch[i]);
                           count++;
                           break;
                      }
                }
           }
     }
}



Output : 

Enter any String : tutorial4u
Duplicate character are : tu

Friday, 2 March 2018

Remove Duplicate String From Two String

package com.tutorial4u;

public class DeleteRepetedCharacterFromTwoString {

     public static void main(String[] args) {
           String s1 = "Tutorial";
        String s2 = "TotalJava";
        System.out.println("String s1 is = " + s1 + " , String s2 is = " + s2);

        char c1[] = s1.toCharArray();
        char c2[] = s2.toCharArray();
       
        for (int i = 0; i < c1.length; i++) {
          
               boolean charMatch = false;
              
               for (int j = 0; j < c2.length; j++) {
                     if ((String.valueOf(c1[i])).toLowerCase().equals(
                                   ((String.valueOf(c2[j])).toLowerCase()))) {
                       charMatch = true;
                            break;
                     }
               }
               if (charMatch) {
                     s1 = s1.replaceAll(String.valueOf(c1[i]).toUpperCase(), "");
                     s1 = s1.replaceAll(String.valueOf(c1[i]).toLowerCase(), "");
                     s2 = s2.replaceAll(String.valueOf(c1[i]).toLowerCase(), "");
                     s2 = s2.replaceAll(String.valueOf(c1[i]).toUpperCase(), "");
               }
        }
        System.out.println("After deleted s1 = " + s1 + ",  after deleted s2 = " + s2);
     }
}



Output :


String s1 is = Tutorial , String s2 is = TotalJava
After deleted s1 = uri,  after deleted s2 = Jv

Java Development Kit (JDK) and Java Runtime Environment (JRE)

                  Java Development Kit (JDK) and Java Runtime Environment (JRE)  To download and install the Java Development Kit (  JDK ) ...