Image

Java - Core Java - Constant in Java

Constant in Java

Constant is an identifier whose value can not be changed during program execution.

In java if you want to make the identifier as constant so you have to use the final keyword. Final is a keyword which is very important foe three things. And they are variable, method , class.

If we want to make something non changeable during program execution so for that we have to make it as final.

Syntax.
Final data type v1=val1, v2=val2.. ;
Example
final int a=20;
          a=a+30; //invalid

How java differs from C and C++

Here is an example that tries to declared two separate variable with the same name in java this is illegal in c and c++ it would be legal
class ScopeError
{
 public static void main(String args[])
 {
   int bar=1;
   {
     int bar=2; //compile time eroor
   }
 }
}
O/P
g:\java>javac  ScopeError.java
ScopeError.java:7: Error: variable bar is already defined  in method main(String[])
int  bar=2
1 error