Assign value to final variable java

Java Variables

In Java, there are different types of variables, for example:

  • String — stores text, such as «Hello». String values are surrounded by double quotes
  • int — stores integers (whole numbers), without decimals, such as 123 or -123
  • float — stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char — stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
  • boolean — stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

Where type is one of Java’s types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type String and assign it the value «John«:

String name = "John"; System.out.println(name); 

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15; System.out.println(myNum); 

You can also declare a variable without assigning the value, and assign the value later:

Читайте также:  JavaScript function to get the function name.

Example

int myNum; myNum = 15; System.out.println(myNum); 

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example

Change the value of myNum from 15 to 20 :

int myNum = 15; myNum = 20; // myNum is now 20 System.out.println(myNum); 

Final Variables

If you don’t want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as «final» or «constant», which means unchangeable and read-only):

Example

final int myNum = 15; myNum = 20; // will generate an error: cannot assign a value to a final variable 

Other Types

A demonstration of how to declare variables of other types:

Example

int myNum = 5; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello"; 

You will learn more about data types in the next section.

Источник

final Keyword in Java

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. The following are different contexts where final is used.

Final Keyword In Java

Characteristics of final keyword in java:

In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended. Here are some of its characteristics:

  • Final variables: When a variable is declared as final, its value cannot be changed once it has been initialized. This is useful for declaring constants or other values that should not be modified.
  • Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is useful for methods that are part of a class’s public API and should not be modified by subclasses.
  • Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for classes that are intended to be used as is and should not be modified or extended.
  • Initialization: Final variables must be initialized either at the time of declaration or in the constructor of the class. This ensures that the value of the variable is set and cannot be changed.
  • Performance: The use of final can sometimes improve performance, as the compiler can optimize the code more effectively when it knows that a variable or method cannot be changed.
  • Security: final can help improve security by preventing malicious code from modifying sensitive data or behavior.

Overall, the final keyword is a useful tool for improving code quality and ensuring that certain aspects of a program cannot be modified or extended. By declaring variables, methods, and classes as final, developers can write more secure, robust, and maintainable code.

Final Variables

When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but the internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from the final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words.

Illustration:

final int THRESHOLD = 5; // Final variable
final int THRESHOLD; // Blank final variable
static final double PI = 3.141592653589793; // Final static variable PI
static final double PI; // Blank final static variable

Initializing a final Variable

We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable can only be initialized once, either via an initializer or an assignment statement. There are three ways to initialize a final variable:

  1. You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.
  2. A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.
  3. A blank final static variable can be initialized inside a static block.

Let us see these two different ways of initializing a final variable:

Java

Geeks there was no main method in the above code as it was simply for illustration purposes to get a better understanding in order to draw conclusions:

Observation 1: When to use a final variable?

The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program.

Observation 2: Reference final variable?

When a final variable is a reference to an object, then this final variable is called the reference final variable. For example, a final StringBuffer variable looks defined below as follows:

As we all know that a final variable cannot be re-assign. But in the case of a reference final variable, the internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity. To understand what is meant by the internal state of the object as shown in the below example as follows:

Java

The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays with the final keyword are also called final arrays.

Note: As discussed above, a final variable cannot be reassign, doing it will throw compile-time error.

Java

Final Variable Throwing Compile-time Error

Remember: When a final variable is created inside a method/constructor/block, it is called local final variable, and it must initialize once where it is created. See below program for local final variable.

Java

Remember the below key points as perceived before moving forward as listed below as follows:

  1. Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in the above examples. A final variable can be assigned value later, but only once.
  2. final with foreach loop: final with for-each statement is a legal statement.

Java

Output explanation: Since the “i” variable goes out of scope with each iteration of the loop, it is actually re-declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables.

Example:

Java

The value is: 10 Hello, world! Hello! Hello, final!

Final classes

When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited).

There are two uses of a final class:

Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer, Float, etc. are final classes. We can not extend them.

final class A < // methods and fields >// The following class is illegal class B extends A < // COMPILE-ERROR! Can't subclass A >

Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can not make a class immutable without making it final.

Final Methods

When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final. We must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes.

Illustration: Final keyword with a method

class A < final void m1() < System.out.println("This is a final method."); >> class B extends A < void m1() < // Compile-error! We can not override System.out.println("Illegal!"); > >

Advantages:

The final keyword in Java provides several advantages, including:

  • Ensuring immutability: When a variable or reference is marked as final, its value cannot be changed once it is assigned. This helps ensure that data is immutable and cannot be accidentally or maliciously modified.
  • Improving performance: The use of final can sometimes help improve performance, as the Java Virtual Machine (JVM) can optimize code more effectively when it knows that certain values or references cannot be changed.
  • Making code easier to understand: By declaring variables, methods, or classes as final, developers can make their code easier to understand and reason about. When a value or reference is marked as final, it is clear that it will not change, which can simplify code analysis and debugging.
  • Promoting code reuse: By declaring methods as final, developers can prevent subclasses from overriding them. This can help promote code reuse and reduce duplication, as subclasses must use the parent class’s implementation of the method.
  • Enhancing security: The use of final can help enhance security by preventing malicious code from modifying sensitive data or behavior.

Overall, the final keyword is a useful tool for improving code quality and ensuring that certain aspects of a program cannot be modified. By declaring variables, methods, and classes as final, developers can write more secure, robust, and maintainable code.

For more examples and behavior of final methods and final classes, please see Using final with inheritance. Please see the abstract in java article for differences between the final and abstract.
Related Interview Question(Important): Difference between final, finally, and finalize in Java

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Источник

Assigning values to static final variables in java

In java, a non-static final variable can be assigned a value at two places.

Example

public class Tester < final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() < //Scenario 2: assignment in constructor A = 1; >public void display() < System.out.println(A + ", " + B); >public static void main(String[] args) < Tester tester = new Tester(); tester.display(); >>

Output

But in case of being static final, a variable cannot be assigned at the constructor. The compiler will throw a compilation error. A static final variable is required to be assigned in a static block or at time of declaration. So a static final variable can be assigned a value at the following two places.

Example

public class Tester < final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() < //Scenario 2: assignment in constructor A = 1; >public void display() < System.out.println(A + ", " + B); >public static void main(String[] args) < Tester tester = new Tester(); tester.display(); >>

Output

The reason behind this behavior of the static final variable is simple. A static final is common across the objects and if it is allowed to be assigned in the constructor, then during the creation of an object, this variable is getting changed per object and thus is not assigned once.

Samual Sam

Learning faster. Every day.

Источник

Оцените статью