identifiers and variables in java

Identifiers and Variabes In Java Explained[2020]

We are going to discuss the Identifiers and variables in java in detail in this post. As the name suggests Identifiers are used for identification purposes.

In Java, Identifiers play a significant role.

As we know java is a simple language and in short Selecting Identifiers Rule is somehow the same as C++.

Rules to Define Identifier in Java

Some most important rules of the identifiers in java are listed below. Many of the same as in C++.

You must follow these rules to avoid the compile time error.

  1. ([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore) are used to create the identifier.
  2. You can not start the name of identifier with Numbers however you can use underscore and dollar symbol
  3. You can use any numbers of letters in your identifiers.
  4. C++ Java Identifiers are also case sensitive.
  5. you can not use keywords as Identifiers.

Examples

  1. geekstocode – Valid Keyword
  2. @geekstocode – Invalid Keyword because you can not use ‘@’ in identifier.
  3. 12geekstocode – You can not start the name of identifier with the numbers, Hence Invalid
  4. geeks_to_code – This is valid but not recommended as per naming convention[Discussed below]
  5. $geekstocode – This is also a valid Identifier.
  6. GeEeKsToCoDe – From above point number 1, this is also valid

We discussed some Famous Identifier Problems

Practice Questions:

Q1 : Identifiers in java can not starts with?

  • Characters
  • Digits
  • Underscore
  • None of the above

Q2 : Which of the following is the wrong identifier

  • _geekstocode
  • geeks_to_code
  • geeks$code
  • 1geekstocode

Q3 : Which is not the Identifier

  • _l_
  • __long__
  • long
  • _long_12

Q4 : Geekstocode and geekstocode have the same meaning when used as a identifier in java

  • True
  • False

Answers 1 : Identifiers never starts with Digits

Solution 2 : 1geekstocode is wrong because we can’t use Digits as first character

Retort 3: long is not a identifier because it is a keyword

Response 4 : False, because Java is case sensitive

Note: Answer, solution, Retort and Response are synonyms of each other. Just for Fun

Variables In Java

Variables are nothing but a name that is given to memory location in java. and most importantly is the basic unit of storage.

How to declare variables?

Declaring variable in java is same as in C++

Identifiers and Variables in java
  • Data Type: Type of data that can be stored in this variable.
  • Variable Name: Name given to the variable.
  • Value: It is the initial value stored in the variable.

you can choose any variable name keeping in mind the rules of identifiers as discussed above.

Types of Variables in Java

There are mainly three of types of variable according to the scope:

Local Variable

As name indicate, the variable within some specific block is known as Local variable

public class Geekstocode
{
    public void StudentAge() 
    {   //local variable age
        int age = 0;
        age = age + 5;
        System.out.println("Student age is : " + age);
    }

    public static void main(String args[])
    {
        Geekstocode obj = new Geekstocode();
        obj.StudentAge();
    }
}

In above code, age is local variable because it define within constructor and have no effect outside the constructor.

Check output of the code Here

Read First java program for more understanding

Output:

Student age is : 5

From above code we can conclude that

  1. These local variables are only created when the block or method in which these variables are defined is called.
  2. local variables destroyed after the method called completed.
  3. Scope of local variables are within a block
  4. You must initialize the local variable but not necessary at the time of declaration

Instance Variables:

Variables that are declared inside the class but not inside any method, constructor or block is known as Instance variable./


import java.io.*;
class Marks
{   
    //These variables are instance variables.
    //These variables are in a class and are not inside any function
    int engMarks;
    int mathsMarks;
    int phyMarks;
}

class MarksDemo
{
    public static void main(String args[])
    {   //first object
        Marks obj1 = new Marks();
        obj1.engMarks = 50;
        obj1.mathsMarks = 80;
        obj1.phyMarks = 90;

        //second object
        Marks obj2 = new Marks();
        obj2.engMarks = 80;
        obj2.mathsMarks = 60;
        obj2.phyMarks = 85;

        //displaying marks for first object
        System.out.println("Marks for first object:");
        System.out.println(obj1.engMarks);
        System.out.println(obj1.mathsMarks);
        System.out.println(obj1.phyMarks);
    
        //displaying marks for second object
        System.out.println("Marks for second object:");
        System.out.println(obj2.engMarks);
        System.out.println(obj2.mathsMarks);
        System.out.println(obj2.phyMarks);
    }
}

Output:

Marks for first object:
50
80
90
Marks for second object:
80
60
85

As you can see in the above program the variables, engmarks , mathsMarks , phyMarksare instance variables.

In case we have multiple objects as in the above program, each object will have its own copies of instance variables.

It is clear from the above output that each object will have its own copy of the instance variable.

By above illustration’s

  1. Instance variables can be accessed by creating objects only.
  2. No need to initialize Instance variables.
  3. we can use access specifiers for instance variables.
  4. If we do not specify any access specifier then the default access specifier will be used.
  5. Instance variables are created when objects are created.

Static Variables

static variables are also known as Class Variables

Instance Variable with a static keyword is known as static variable.

public static  int salary;

These variables are declared the same as Instance variables, but you must use a static keyword before these variables.

import java.io.*; 
class Geekstocode { 

	// static variable salary 
	public static double salary; 
	public static String name = "piyush"; 
} 

public class GeeksDemo { 
	public static void main(String args[]) 
	{ 

		// accessing static variable without object 
		Geekstocode.salary = 1000; 
		System.out.println(Geekstocode.name + "'s average salary:"
						+ Geekstocode.salary); 
	} 
} 

Output

piyush's average salary:1000.0

From above code we can conclude some basic points for Static variable

  1. Static variables are declared using static keywords.
  2. The Static variables created automatically at the start of the program
  3. static variables are only accessed by the Class name.
  4. If you do not initialize the static variable, it’s default value is going to be zero
  5. Static variables have only one copy

Practice Questions:

Q1: Predict the output:


public class Geekstocode
{
    int i = 30;
     public static void main (String[] args) {
        
        Geekstocode a = new Geekstocode();
        
        Geekstocode b = new Geekstocode();
        
        a.i = 34;
        System.out.println(a.i);
        
        System.out.println(b.i);
        
        
    }
}
  • 34 30
  • 30 34
  • 30 30
  • 34 34

Answer : 34 30

Explanation: The Instance variable is unique for their object, that means each copy of memory for variable i will be available for each object.

Q2: Again predict the output


public class Geekstocode
{
    static boolean geeks;
     public static void main (String[] args) {
        
        Geekstocode a = new Geekstocode();
        
        System.out.println(a.geeks);
        
        
    }
}
  • True
  • False
  • Compile Error
  • Runtime Error

Answer: False, By default, a boolean variable will contain false.

Instance variable Vs Static variable

This is the one of the most important interview questions:

  1. Static variables have only copy per class on the other hand Instance variables have a different copy for different objects
  2. Changes made in one instance variable of one object will not make any change in the instance variable of another object while changes made in one static variable will reflect in each object.
  3. We can access the instance variable by creating an object but we can access the static variable directly by class name.

Practice Q1: Predict the output


class GeeksToCode { 
    static int i = 1; 
public static void main(String[] args) 
    { 
        for (int i = 1; i < 10; i++) { 
            i = i + 2; 
            System.out.print(i + " "); 
        } 
    } 
} 

Option
A) 3 6 9
B) 3 6 9 …. 27
C) Error
D) none

Answer : A, Because you can access the static variable by using the class name only.

2 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *