Constants in Java

CONSTANT:

                   Constant means fix value we cannot change or we can say it’s a unchangeable value. Constant values are used in the program we cannot change the value during execution.After the initialize of the variable we can set constant value to the variable like this…….int a;     a=12;

 

Here,’a’ is the variable and 12 is the integer constant which is given to the variable ‘a’.

Types of Constants…….

Integer Constant-->

                              Integer values are those whose are complete not decimal value like 2,3,4,5 not 2.3,4.6.                    

                       Program example:

                            class constantinteger

                         {

                         public static void main(String ansg[])

                         {

                           int a;   //int is integer data type and a is variable

                           a=78;//78 is the constant integer value

                         System.out.print(“integer value=”,a);//print the value

                          }

                     }

                                    

Character Constant-->

                             When we one character like ‘s’,’v’, then it’s a character constant .We use this constant

                     With data type char.We use this like……..char a=’c’;

   Program Example:

                   Class chconst

             {

               public static void main(String chn[])

             {

               char c;

               c=’a’; // ‘a’ character constant value pass to variable c

             System.out.print(“character=”,c);//print the character

         }

}

                   ANOTHER EXAMPLE

 

class chars

{              public static void main (String ba[])

                {

                                char ch1, ch2;

                                ch1=88;//ASCII Code

                                ch2=‘Z’;//constant character

                                System.out.println (“ch1 and ch2: “ + ch1+” “+ch2);//print both ch1 &ch2

                }

}

Output: ch1 and ch2: X Z