Wednesday, September 18, 2013

Java variables

  • Variables are locations where the data is stored when program execute.
  • It refers to memory location.
  • You should follow the variable naming rules before type a name, Go to Java naming standards post.
  • There are two major types of variables in java.

      1. Numeric (integer and floating point)
      2. Single character
      3. Boolean (true/false)
                         Complex objects
      1. Strings
      2. Dates
      3. Everything else

Another types of declaration of variables

1. Instance variables (Non-static variable)
2. Class variables (Static variables)
3. Local variables

public class Apple{
     int x = 10;         // Instance variable
     static int y = 20;  // static variables

     public static void main(String args[]){
          byte z=5;      // local variables

Instance variable

  • This variables are declared in a class, but outside of any block.
  • These are visible for all method, constructor and any block in the class.
  • If you are using instance variable in non-static field, you have to call it through object.
  • We will learn how to create objects in next posts. Here is a example.
  • Value is depend on the object which is created.

class Apple{
 int x = 10;                     // Instance variable

    public static void main(String args[]){
     Apple obj = new Apple();    // create obj object

        /*System.out.println(x); this will give a compile time error */

Class variables (Static variables)

  • This variable declared with a ‘static’ keyword.
  • This variables are start with program start and destroy when program stops.
  • Can be accessed with class name.
  • Values depend on the class.

class Apple{
     static float x = 10.5f;
     static String s = "ryjskyline";

     public static void main(String args[]){

          System.out.println(s); // Apple.s is also correct

Local variable

  • Local variable are declared in method, constructors of any other block.
  • This type of variable destroy once it exits the method, constructor or block.
  • Access modifiers can’t be used for local variables.
  • This variable does not initialize to default values.
  • Local variables should be explicitly assigning value. 

public class Apple{

     public static void main(String args[]){
          int x =10;