La palabra clave final se usa en diferentes contextos. En primer lugar, final es un modificador de no acceso aplicable solo a una variable, un método o una clase. Los siguientes son diferentes contextos donde se usa final.
Java
// Java Program to demonstrate Different // Ways of Initializing a final Variable // Main class class GFG { // a final variable // direct initialize final int THRESHOLD = 5; // a blank final variable final int CAPACITY; // another blank final variable final int MINIMUM; // a final static variable PI // direct initialize static final double PI = 3.141592653589793; // a blank final static variable static final double EULERCONSTANT; // instance initializer block for // initializing CAPACITY { CAPACITY = 25; } // static initializer block for // initializing EULERCONSTANT static{ EULERCONSTANT = 2.3; } // constructor for initializing MINIMUM // Note that if there are more than one // constructor, you must initialize MINIMUM // in them also public GFG() { MINIMUM = -1; } }
Java
// Java Program to demonstrate // Reference of Final Variable // Main class class GFG { // Main driver method public static void main(String[] args) { // Creating sn object of StringBuilder class // Final reference variable final StringBuilder sb = new StringBuilder("Geeks"); // Printing the element in StringBuilder object System.out.println(sb); // changing internal state of object reference by // final reference variable sb sb.append("ForGeeks"); // Again printing the element in StringBuilder // object after appending above element in it System.out.println(sb); } }
Java
// Java Program to Demonstrate Re-assigning // Final Variable will throw Compile-time Error // Main class class GFG { // Declaring and customly initializing // static final variable static final int CAPACITY = 4; // Main driver method public static void main(String args[]) { // Re-assigning final variable // will throw compile-time error CAPACITY = 5; } }
Java
// Java program to demonstrate // local final variable // Main class class GFG { // Main driver method public static void main(String args[]) { // Declaring local final variable final int i; // Now initializing it with integer value i = 20; // Printing the value on console System.out.println(i); } }
Java
// Java Program to demonstrate Final // with for-each Statement // Main class class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing // custom integer array int arr[] = { 1, 2, 3 }; // final with for-each statement // legal statement for (final int i : arr) System.out.print(i + " "); } }
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA