wellnwill Marathahalli Bangalore

Constants in Java

  • A variable whose value cannot be changed during the program execution. In java, constant is known as final variable. Example -
                  final byte b=10;
                  final int a=10;
  • A final variable that is not initialized at the time of declaration is called as blank final variable. Ex-
      final int a;
  • final variable will be replaced by actual value after compilation and operation will also be performed at compile time.
  •  class Test
     {
        public static void main(String args[])
           {
               int a=1;
               System.out.println("a:"+a);
               a=2;
               System.out.println("a:"+a);
           }
    }
    
    // O/P-   a:1,a:2
    
    class Test
    {
       public static void main(String args[])
         {
              final int a=1;
              System.out.println("a:"+a);
              a=2;
              System.out.println("a:"+a);
          }    
    }
    
    // O/P- Comiple Time Error
    

    Compiler knows final variable values and Boolean type also.

     final int a=10, b=20;                                
     int c=30;                                            
     System.out.println(a);                  System.out.println(10);
     System.out.println(b);                  System.out.println(20);
     System.out.println(false);   =======>   System.out.println(false);
     System.out.println(a+30);               System.out.println(40);
     System.out.println(a+b);                System.out.println(30);
     System.out.println(a+c);                System.out.println(10+c);
    
    class Test33
    {
       public static void main(String argss[])
       {
          final int a=20; 
          System.out.println(a);
          a=10;
          System.out.println(a);
       }
    }
    
    // O/P-  Compile Time Error - 
                 cannot assign a value to final variable a.
    
    class Test34
    {
       public static void main(String argss[])
       {
          final int a=20; 
          System.out.println(a);
          System.out.println(a+10);
       }
    }
    
    // O/P-   20,30
    
    
    
    class Test35
    {
        public static void main(String argss[])
        {
           const int a=20; 
           System.out.println(a);
        }
    }
    
    // O/P- Compile Time Error - illegal start of expression
       Note- We can not use const keyword to declare constant. We use final.
    
Footer with Map

Top