Java variables

// By:Team // No Comment

Email this to someonePrint this pageShare on Google+2Share on Facebook2Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on StumbleUpon2

Variable Definition

  • A variable in Java, objects store their states in java variables. Variables are used as containers to hold values (int, long, string…) during the life cycle of an application.
  • A variable provides us with named storage that our programs can manipulate. To define a variable, we need to assign a data type for that variable. Data type defines the kind of value this variable can hold(int,long or String etc.).

Example of variable definition

Variable Initialization
Now that we are done defining a variable, we can initialize the above variable by assigning a value to it. In this case, we assign the variable an integer value.

Different Primitive Data Types
Java supports the below mentioned primitive data types.

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

Variable Types in Java
Variables in Java can be defined anywhere in the code (inside a class, inside a method or as a method argument) and can have different modifiers. Depending on these conditions variables in Java can be divided into four categories.

  • Instance Variable
  • Static Variable
  • Local Variable
  • Method Parameter

Instance Variable(Non Static Fields)
Instance variables are used by objects to store their states. Variables which are defined without the STATIC keyword and are outside any method declaration are object specific and are known as Instance Variables. Such variables are called as instance variables because their values are instance specific and values of these  variables are not shared among instances.

Class Variable(Static Fields)
Variables which are declared with a “static” keyword inside a class (outside any method) are known as Class variable or Static variable. They are known as Class level variable because values of these variables are not specific to any instance but are common to all instances of a class. Such variables will be shared by all instances of an object.

Local Variables(Method Local)
When a variable is declared inside a method it is known as method local variable. Scope of local variables is only inside the method, which means local variables cannot be accessed outside that method. There are some restrictions on access modifier that can be applied on Local variables.

Parameters
Parameters are variables that are passed in methods. For example, String args[] variable in main method is a parameter.

Note*: Corresponding Wrapper Classes is also available.

Email this to someonePrint this pageShare on Google+2Share on Facebook2Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on StumbleUpon2

About Team

Browse Archived Articles by Team

Related

Sorry. There are no related articles at this time.