JAVA #05 – Variables in Java

Share on WhatsApp
Share via email Share

What are variables?

A temporary holding area of memory in which data can be store (also called operand). Variables in Java behave the same way like most of other object oriented programming languages.

Local variables

  • Local variables are declared in methods, constructors, or blocks.
  • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
  • Access modifiers cannot be used for local variables.
  • Local variables are visible only within the declared method, constructor or block.
  • Local variables are implemented at stack level internally.
  • There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

Example:

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to this method only.

 

Some basic datatypes in Java and its values declaration.

  1. float 10.6756567f
  2. int   16,123
  3. String   “Ali Khan”
  4. byte   10101010111
  5. long 12379873547912
  6. short 0-255
  7. boolean true,false
  8. char ‘A’
  9. double 45.5675675687345

 

Instance variables:

  • Instance variables are those variables which holds instance of any object.
  • When a space is allocated for an object in the heap, a slot for each instance variable value is created.
  • Instance variables are usually initialized by using ‘new’ keyword.
  • If an instance variable is declared in class, it can have access modifier. Otherwise it doesn’t need access modifier in Java programming language.

Example:

Watch this video about Variables in Java in Urdu/Hindi to learn more:

 

Share on WhatsApp
Share via email Share
2 Comments
  1. Asad Khan
  2. Asad Khan

Leave a Reply

Your email address will not be published.