Skip to content

Latest commit

 

History

History
74 lines (54 loc) · 1.97 KB

File metadata and controls

74 lines (54 loc) · 1.97 KB

09. variables and Literals

Variables

  • It is a named memory location that holds the data value of a particular data type.

    Declaration: 
    	dataType variableName; 
    
    Initialization: 
        dataType variableName = value; 
                **OR**
        dataType variableName; 
        variableName = value; 
    

Variable Naming rules:

  • cannot contain white spaces
  • can begin with a special character dollar ($) and underscore ( _ )
  • first letter of a variable cannot be a digit
  • camelCase convention should be used
  • Built in keywords ( int, for, while, class, break, continue, etc ) cannot be used

Types of variables:

  • Local:
    • declared within a body of method, constructor or code block.
    • scope is limited within that block.
    • created within the method or block and destroyed after the method invocation.
    • No initialization ( no default values ), if not initialized compile time error
    • stored in stack
  • Instance
    • declared inside the class but outside any method, constructor or block body
    • not shared between objects.
    • scope is tied to the instance or object of the class.
    • created with the new keyword and destroyed when the object is destroyed.
    • default values are given if not initialized
    • stored in heap
  • Static ( Class Variable )
    • declared inside a class but not inside the method, constructor or a block, with the static keyword
    • shared with all instances of class.
    • scope is tied to the class itself.
    • created at the start of the program and destroyed at the end of the program.
    • default values are given if not initialized
    • stored in Method Area or Class Area

Literals

  • The data items that have fixed or constant values.
int number = 20;
//int -> data type
//number -> variable 
//20 -> literal

Types:

  1. Integer literals

  2. Floating literals

  3. Boolean literals

  4. Character literals

  5. String literals

  6. Null literal