The Wayback Machine - https://web.archive.org/web/20241003171630/https://www.geeksforgeeks.org/final-arrays-in-java/
Open In App

Final Arrays in Java

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we all know final variable declared can only be initialized once whereas the reference variable once declared final can never be reassigned as it will start referring to another object which makes usage of the final impracticable. But note here that with final we are bound not to refer to another object but within the object data can be changed which means we can change the state of the object but not reference. So, as we all know that arrays are also an object so final arrays come into play. The same concept does apply to final arrays that are we can not make the final array refer to some other array but the data within an array that is made final can be changed/manipulated.   

Illustration:

Java
// Java Program to Illustrate Final Arrays
// Can Be Reassigned But Not Re-referred

import java.util.*;

class GFG {
    public static void main(String[] args)
    {

        final int[] arr = { 1, 2, 3, 4, 5 };

        arr[4] = 1;

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

Output
1
2
3
4
1

Implementation:  

Java
// Java Program to Illustrate Final Arrays

// Importing required classes
import java.util.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String args[])
    {

        // Declaring a final array
        final int arr[] = { 1, 2, 3, 4, 5 };

        // Iterating over integer array
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 10;
            System.out.println(arr[i]);
        }
    }
}

Output
10
20
30
40
50

Output Explanation: The array arr is declared as final, but the elements of an array are changed without any problem. Arrays are objects and object variables are always references in Java. So, when we declare an object variable as final, it means that the variable cannot be changed to refer to anything else. 

Example A:

Java
// Program 1

// Main class
class Test {
  
    int p = 20;
    public static void main(String args[])
    {
        final Test t = new Test();
        t.p = 30;
        System.out.println(t.p);
    }
}

Output
30

Example B:

Java
// Java Program to Illustrate Final Arrays
// Where Compiler Error Is Thrown

// Main class
class GFG {

    int p = 20;

    // Main driver method
    public static void main(String args[])
    {

        // Creating objects of above class
        final GFG t1 = new GFG();
        GFG t2 = new GFG();

        // Assigning values into other objects
        t1 = t2;

        System.out.println(t1.p);
    }
}

Output: Compiler Error: cannot assign a value to final variable t1

Conclusion: Above program compiles without any error and program 2 fails in compilation. Let us discuss why the error occurred.

So a final array means that the array variable which is actually a reference to an object, cannot be changed to refer to anything else, but the members of the array can be modified. Let us propose an example below justifying the same.

Example:

Java
// Java Program to Illustrate Members in Final Array
// Can be Modified

// Main class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Declaring a final array
        final int arr1[] = { 1, 2, 3, 4, 5 };

        // Declaring normal integer array
        int arr2[] = { 10, 20, 30, 40, 50 };

        // Assigning values to each other
        arr2 = arr1;
        arr1 = arr2;

        // Now iterating over normal integer array
        for (int i = 0; i < arr2.length; i++)

            // Printing the elements of above array
            System.out.println(arr2[i]);
    }
}

Output:

Example :

Java
import java.util.Arrays; // Import Arrays class for toString() method

public class FinalArrayExample {
  
    public static void main(String[] args)
    {
        final int[] numbers = { 1, 2, 3, 4, 5 };
        // Attempting to reassign the array reference will
        // result in a compilation error: numbers = new
        // int[] {6, 7, 8, 9, 10};

        // However, individual elements of the array can
        // still be modified:
        numbers[0] = 10;
        System.out.println(
            "Array after modifying first element: "
            + Arrays.toString(numbers));
    }
}

Output:




Previous Article
Next Article

Similar Reads

Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
final vs Immutability in Java
final: In Java, final is a modifier that is used for class, method, and variable also. When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means
3 min read
Difference between Final and Abstract in Java
In this article, the difference between the abstract class and the final class is discussed. Before getting into the differences, lets first understand what each of this means. Final Class: A class which is declared with the "Final" keyword is known as the final class. The final keyword is used to finalize the implementations of the classes, the me
4 min read
Why a Constructor can not be final, static or abstract in Java?
Prerequisite: Inheritance in Java Constructor in java is a special type of method which is different from normal java methods/ordinary methods. Constructors are used to initialize an object. Automatically a constructor is called when an object of a class is created. It is syntactically similar to a method but it has the same name as its class and a
6 min read
Can We Override Final Method in Java?
A method in a subclass is said to Override a method in its superclass if that method has a signature identical to a method in its superclass. When this method is called by an object of the subclass, then always the Overridden version will be called. In other words, the method which was Overridden in the superclass will become hidden. The JVM has 2
3 min read
Private vs Final Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modi
3 min read
Private vs Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
5 min read
Can We Extend final Method in Java?
Final method in java can be extended but alongside the main concept to be taken into consideration is that extend means that you can extend that particular class or not which is having final method, but you can not override that final method. One more case where you can not extend that final method is the class that contains the final method is als
3 min read
Effectively Final Variable in Java with Examples
A final variable is a variable that is declared with a keyword known as 'final'. Example: final int number; number = 77; The Effectively Final variable is a local variable that follows the following properties are listed below as follows: Not defined as finalAssigned to ONLY once. Any local variable or parameter that's assigned a worth just one occ
4 min read
Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
5 min read
Java - Final vs Static Access Modifier
Final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a variable, a method, or a class. Following are different contexts where final is used. While the static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given
5 min read
Assigning values to static final variables in Java
Assigning values to static final variables in Java: In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.For example, following program works fine. Java Code class Test { //
1 min read
Private and final methods in Java
When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons. Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn't add any value. It may in-fact cause unnecessary confusion. class B
1 min read
final, finally and finalize in Java
This is an important question concerning the interview point of view. final keyword final (lowercase) is a reserved keyword in java. We can't use it as an identifier, as it is reserved. We can use this keyword with variables, methods, and also with classes. The final keyword in java has a different meaning depending upon whether it is applied to a
13 min read
Blank Final in Java
A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later. final int i = 10; i = 30; // Error because i is final. A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final. // A simple blank final example final int i;
2 min read
Using final with Inheritance in Java
Prerequisite - Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. Using final with inheritance During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throug
4 min read
Output of Java programs | Set 24 (Final Modifier)
Difficulty level : Easy Prerequisite : final keyword in java Predict the output of following Java Programs: What will be output of following program? class Test { final int MAXIMUM; final double PI; public Test(int max) { MAXIMUM = max; } public Test(double pi) { PI = pi; } public static void main(String[] args) { Test t1 = new Test(1500); Test t2
3 min read
Instance variable as final in Java
Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc. If we don’t initialize an instance variable, then JVM automatically provide default value acco
3 min read
Final static variable in Java
Prerequisite : static variables, final keyword Static variable: When the value of a variable is not varied, then it is a not good choice to go for instance variable. At that time we can add static modifier to that variable. Whenever we declare variable as static, then at the class level a single variable is created which is shared with the objects.
3 min read
Final local variables in Java
Prerequisite : final keyword, Variables, Scope of Variables A local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists. If we are declaring a local variable then we should initialize it within the blo
2 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
final variables in Java
In Java, we can use final keyword with variables, methods, and classes. When the final keyword is used with a variable of primitive data types such as int, float, etc), the value of the variable cannot be changed.  Example 1: Usage of final with primitive datatype Java Code // Java Program to illustrate Use of Final Keyword // With Primitive Dataty
2 min read
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java. The following are different contexts where the final is used: VariableMethodClass Characteristics of final keyword in Java:In Java, the final keyword is used to indicate that a variable, method, or cl
11 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Final vs Static vs Abstract Non-Access Modifier
Modifiers are specific keywords present in Java using that we can make changes to the characteristics of a variable, method, or class and limit its scope. Java programming language has a rich set of Modifiers. Modifiers in Java are divided into two types Access ModifiersNon-Access modifiers Non-access modifiers provide information about the charact
7 min read
private vs private-final injection of dependency
Dependency Injection (DI) is essential for improving code modularity, maintainability, and testability in the context of sophisticated Java programming. Choosing between private and private-final injection for dependencies is a typical DI concern. We will examine the distinctions between these two strategies in this post, as well as their applicati
5 min read
How to Sort an Arrays of Object using Arrays.sort()
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array storing any type of object can be Integer, String or
3 min read
Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Java.util.Arrays.deepEquals() in Java
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension. Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of eleme
4 min read
Java.util.Arrays.copyOfRange() in Java
This method creates a copy of elements, within a specified range of the original array.Syntax : public static int[] copyOfRange(int[] original_array, int from_index, int to_index) original_array : Array to be copied fromfrom_index : Starting index of range to be copiedto_end : the final index of the range to be copied, exclusive. (This index may li
4 min read
Practice Tags :