Variables and Names

In programming a variable is nothing more than a name for something so you can use the name rather than the something as you code. Programmers use these variable names to make their code read more like English, and because programmers have a lousy ability to remember things. If they didn't use good names for things in their software they'd get lost when they came back and tried to read their code again.

If you get stuck with this exercise, remember the tricks you've been taught so far for finding differences and focusing on details:

  1. Write a comment above each line explaining to yourself what it does in English.
  2. Read your .java file backwards.
  3. Read your .java file out loud, saying even the punctuation and symbols.

Let's Create our some of the variables and use those variables , Create a file with nam "VariablesAndNames.java"

public class VariablesAndNames {

    public static void main(String[] args) {


        // In Java , for sentences or alphabetic word or non-numeric word, we use "String"
        // for Numbers we use int,double, etc.,
        // We will start with basic

        String myName, myClan, fatherName, motherName;    // We are creating variable here
        int myAge, myHeight, myWeight;                      // We are creating int type variable here

        myName = "Raj Rastogi";
        myAge = 23;
        myHeight = 74;  // In inches
        myWeight = 180;  // In lbs
        myClan = "w3clan.com";
        fatherName = "Krishna Rastogi";
        motherName = "Priya Rastogi";

        System.out.println("My name is " + myName);
        System.out.println("My Clan is " + myClan);
        System.out.println("My Father Name is " + fatherName);
        System.out.println("My Mother Name is " + motherName);
        System.out.println("I am " + myAge);
        System.out.println("My height is " + myHeight);
        System.out.println("My weight is " + myWeight);

        // All in One line . Make sure you don't do typing mistake or mis any thing.

        System.out.println("My name is " + myName + ". I am " + myAge + ". My clan name is "+myClan + ". My father Name is : "+ fatherName + ". My Mother name is : " + motherName + ". I am " + myHeight + " inches tall and i have " + myWeight + "lbs weight");
        
    }
    
}

Important note :-

  1. In Java , for sentences or alphabetic word or non-numeric word, we use "String"
  2. for Numbers we use int,double, etc.,

There are three kinds of variables in Java:

  • Local variables

  • Instance variables

  • Class/static variables

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 : Create a file with name "FindAge.java"

public class FindAge{ 

   public void puppyAge() {
      int age = 0;     // It is important to initialise before we do math below
      age = age + 7;   
      System.out.println("Puppy age is : " + age);
   }
   
   public static void main(String args[]){
      FindAge findage = new FindAge();
      findage.puppyAge();
   }

}




// Wrong Code

public class FindAge{ 

   public void puppyAge(){
      int age;     // We have not initialised variable and we are doing math below
      age = age + 7;    // This will throw an error as age has no initialised value
      System.out.println("Puppy age is : " + age);
   }
   
   public static void main(String args[]){
      FindAge findage = new FindAge();
      findage.puppyAge();
   }

}

Instance variables:

  • Instance variables are declared in a class, but outside a method, constructor or any block.

  • When a space is allocated for an object in the heap, a slot for each instance variable value is created.

  • Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.

  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

  • Instance variables can be declared in class level before or after use.

  • Access modifiers can be given for instance variables.

  • The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However visibility for subclasses can be given for these variables with the use of access modifiers.

  • Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.

  • Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) should be called using the fully qualified name .ObjectReference.VariableName.

Example: Create a file with name "Student"

public class Student {

   // this instance variable is visible for self or any child class.
   public String name;

   // marks variable is visible in Student class only.
   private double marks;

   // The name variable is assigned in the constructor.
   // Constructor are functions that are initialised when class object is created or class is called

   public Student (String studentName){
      name = studentName;
   }

   // The marks variable is assigned a value.

   public void setMarks(double studentMarks){
      marks = studentMarks;
   }

   // This method prints the student details.

   public void studentInfo(){
      System.out.println("name  : " + name );
      System.out.println("Marks : " + marks);
   }

   public static void main(String args[]){
      Student studentOne = new Student("Raj Rastogi");
      studentOne.setMarks(89);
      studentOne.studentInfo();

  }
}

Class/static variables:

  • Class variables also known as static variables are declared with the statickeyword in a class, but outside a method, constructor or a block.

  • There would only be one copy of each class variable per class, regardless of how many objects are created from it.

  • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.

  • Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.

  • Static variables are created when the program starts and destroyed when the program stops.

  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.

  • Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks.

  • Static variables can be accessed by calling with the class nameClassName.VariableName.

  • When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.

Example : Create a file with name "Classroom.java"

public class Classroom {

   // marks variable is a private static variable
   private static double marks;

   // CLASSROOM is a constant
   public static final String CLASSROOM = "Standard 10 ";

   public static void main(String args[]){
      marks = 100;
      System.out.println(CLASSROOM + "average marks:" + marks);
   }

}

Loading ...

Related Results :

  1. Variables and Names
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author