DEV Community

Cover image for Literals and Variables in Java.
Kumar Sanskar
Kumar Sanskar

Posted on

Literals and Variables in Java.

Well I took a break of two days from my learning Java journey so that I could do my another favorite thing that is doing some art work after being surrounded from tech my all days, some time these breaks are necessary so as to give you a mental peace.
Enough of talks now let's get back to our business that is learning Java.

It's day six and today I will talk about Literals and variables.

Literals :-

  • literal can be anything that has a fixed value and can be represented in a human readable form and are also called as consonants.
  • in java literals can be of any of the eight primitive types.
  • in addition too the eight primitive types Java also supports Hexadecimal, octal, and binary literals.
  • Hexadecimal literals have to begin with 0x or 0X and octal literals have to begin with 0 and similarly binary literals have to begin with 0b or 0B.
  • Java furthermore also supports another type of literal String, it can be understood as set of characters enclosed by double quotes and can even contain character escape sequences like /n, /t etc.

Variables -

  • as evident from the name itself it refers to something that can vary and are used to declare as well as initialize values in a Java program.
  • Initializing Variables in Java

      type variableName = value;
      for example :- 
      int ageOfStudent = 20;
    
  • while declaring and initializing variables of same data type we can separate them using commas and even assign values simulatenously. for example -

    int ageOfStudent = 10, numberOfSiblings = 2;
Enter fullscreen mode Exit fullscreen mode
  • java also supports dynamic initialization of variables that is at run time.
  • Scope and Lifetime of a Variable -

    • in Java all the variables are defined within a block of code which like every other program is defined by opening and closing of curly braces.
    • these blocks define a scope.
    • in Java scopes are defined by two ways:-

      i. defined by methods
      ii. defined by class

  • a variable defined within a block is called local variable.

  • objects declared in outer scope will be visible to inner scope but the vice-versa will not hold true.

Closing here for the day, feel free to add, correct or suggest any mistake that may have crept in.

Top comments (0)