Code Pumpkin

Java Variables Interview Questions

September 22, 2018
Posted by Abhi Andhariya and Indu Malik

Hello Developers, In this article, you will learn basics of java variables. If you are preparing for your first ever java interview, then you must go through all the questions mentioned in this article. It will definitely help you clear all your doubts related to java variables. After reading this article, you will be able to answer following interview questions related to java variables:

  1. What Is The Variable?
  2. How To Declare A Variable In Java?
  3. How To Assign A Value To Variable?
  4. What Is Variable Initialization? How Is It Different Than Assignment?
  5. Can We Declare And Initialize A Variable Together?
  6. Why Is Specifying DataType Mandatory In Java?
  7. How Many Types Of Datatypes Are There In Java?
  8. How Can You Create Constants In Java?
  9. What Are The Rules For Naming Java Variables?
  10. What Are Some Common Naming Conventions For Java Variables?
  11. Where Does Java Store Variable?

I have discussed each and everything in very depth. Without further ado, let's get started.

1. What is the variable?

Variable is a name which is given to a memory cell. Variable is also known as a container (or box) which is used to store data value during program execution in memory. It is a basic unit of data storage. Variable is a combination of two words:

Vary + Able = Variable | Java Variables Interview Questions

Variable value can be changed during program execution. Here 'vary' word represent variation, it means we can change the value of a variable during program execution. 

For Example, in below code snippet, we have declared a variable number, then in next step we initialized its value and then we modified its value. We will refer below code snippet multiple time to understand variable declaration, assignment and initialization in detail in subsequent topics.


public class VariableDemo {

    public static void main(String[] args) {

        // variable declaration
        int number;    
    
        // initialization / assign a value to variable
        number = 10;

        // modify variable value and assign it again
        number = number + 20;
    }

}

2. How to Declare a variable in java?

Declaring a variable is very easy. If you have noticed in above example, we have declared variable number on line 6. But along with that we have also specified its datatype i.e. int

Below code snippet shows some more example of variable declaration.


int number;
boolean flag;
String name;

Here number, flag and name are variable name and int, boolean and String are their respective data types.

Java is known as strictly typed language as it is mandatory to specify a data type of a variable before variable name. in java. It is used by compiler to help programmer avoid any mistakes such as storing String values to integer variables. Before reading or assigning a value, that variable must have been declared. Jump to the question Why is Specifying DataType before variable name Mandatory?


    3. How to assign a value to variable?

    We use assign operator (=) to assign a value to a variable. For Example, 

    
    number = 10;
    flag = true;
    name = "CodePumpkin";

    We can assign a value to variable any number of time in java, but when we assign a new value to a variable old value will be overwritten. 

    For example,  in first code snippet, we have first assigned a value 10 to number and then modified its value by performing number+20 operation and assign it back to variable number by .


    4. What is variable Initialization? How is it different than Assignment?

    When we assign a value to a variable first time, it is known as variable initialization. Before initialization objects have nullvalue and primitive types have default values such as 0 or false.  For example, variable number is initialized with value 10 on line 9 in first code snippet.


    5. Can we declare and initialize a variable together?

    Yes, we can declare and initialize a variable together. Her is the syntax for the same:

    Declaring and Initializing a java variable

    Declaring and Initializing a java variable

    For Example,

    
    int number=10;
    boolean flag=true;
    String name="CodePumpkin";

    6. Why is Specifying DataType Mandatory in Java?

    Data type of a variable is an attribute which tells what kind of data that variable can have. Every java variable takes up a certain amount of space in memory. How much memory a variable takes is depends on its datatype.

    For Example, As we see in our daily life, Different types of vehicle requires different amount of space in your parking area. For example, Our two wheeler may require two blocks where as Car may require 6 blocks of space. Same applies to variables in java. Storing a small number requires less space compared to large number. So, we need to declare a datatype of our variable accordingly.

    In other words, data types are used by JVM to assign space for that variable in the memory. If we do not specify datatype, JVM can not decide how much space is required by that variable during program execution. So, it is mandatory to use datatype before variable name and Java Compiler will cry, if you miss to do that.

    Java has two types of datatype primitive and non-primitive data type. We will understand more about data types in our next article 


    7. How many types of datatypes are there in java?

    Java has two types of datatypes. 

    1. Primitive Data Type 
              There are 8 primitive data types in java i.e. short, byte, int, long, float, double, boolean and char.
    2. Non-primitive Data Type
            – array, class, interface and enum are non-primitive data types. If you have noticed, String is not primary / primitive data type in java. String is a name of class. Similarly you can also define your own custom class types like Student, User, etc.
            – Don't worry if you don't have much idea about these datatypes. We will cover them all in upcoming article on datatype. 

    8. How can you create constants in java?

    So, what is constant? we can assign values to variable any number of time, but what if we want variable value to be fixed and we don't want developers to change its value, once variable is initialized. We can achieve this by declaring variable as final. It is wrong to call such fields as variable (vary + able), so we call them constants. 

    
    public class ConstantDemo {
    
        public static void main(String[] args) {
    
            // variable declaration
            final int NUMBER=10;    
      
            // Compiler will throw error on below line as we can not change value of constants
            NUMBER = NUMBER + 20;
        }
    
    }

    If you have noticed, instead of  defining variable name in lowercase, we have used all uppercase character i.e. NUMBER instead of number. There is no java rule that constant name should be in upper case, but its common practice followed by all java developers. 

    Once we declare variable as a final we can not change the value inside that field. Read more about it in our article on final Keyword.


    9. What are the rules for naming Java Variables?

    There are some rules related to Java variable names:

    1. Java Variable names are case sensitive. Variable declared as codepumpkin is different than CodePumpkin or CODEPUMPKIN
    2. Variable name must start with a letter, or $ or _ character. No other special character or digits are allowed as first character of variable name.
    3. After the first character, java variable name can have digits as well along with letter, $ and _
    4. Variable name can not be equal to reserved keyword in java. For example, you can not give your variable name as int, if or boolean as they are reserved keyword in java.

    Here are some of the valid java variable names:

    
    codepumpkin
    _CodePumpkin
    $CodePumpkin
    Code_Pumpkin_1
    

    Below are some of the invalid java variable names:

    
    @codepumpkin
    1_CodePumpkin
    Code_Pumpkin_#
    for
    if

    10. What are some common naming Conventions for Java Variables?

    Along with above rules, there are some naming conventions which are being followed by developers all around the worlds. Compiler will not enforce you to follow the naming conventions. But as its common practice by all java developers, when some other developer will read your code, it will be easier for them to understand. 

    1. variable name are written in lowercase i.e. number, name
    2. If there are multiple words in the variable name, then use camel case i.e. first character of each word should be capitalized except first word i.e. codePumpkin, cityName
    3. constant name should be inupper case. If there are multiple words in constant name, use underscore between two words i.e. NUMBER, STATUS_CODE

    If we don't follow above rules in declaring variable name, then compiler will throw errors, ut there are some naming conventions


    11. Where does java store variable?

    In the beginning of the article we have seen that variables are the name given to the memory cell. So where this memory cell resides?

    Well variables are stored in RAM memory. RAM stands for Random Access Memory. RAM is a volatile memory, means when the power of system is off all the data is erased into it. User application & application software occupies the space in RAM. Variables take area in memory which is known as reserved area. Program execution is performed on values, which are stored in memory cell and access these values by compiler using variable name.

    Where are java variabls being stored

    That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

    Happy Learning 🙂

    If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

    We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.



    About the Authors


    Surviving Java Developer, Passionate Blogger, Table Tennis Lover, Bookworm, Occasional illustrator and a big fan of Joey Tribbiani, The Walking Dead and Game of Thrones...!!

    I'm a Programming Enthusiast, Java Lover, Blogger, Former Google Intern. Big fan of Friends, loves to watch horror movies and etc etc.



    Tags: , ,


    Comments and Queries

    If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
    <pre><code class="java"> 
    String foo = "bar";
    </code></pre>
    
    For more information on supported HTML tags in disqus comment, click here.
    Total Posts : 124
    follow us in feedly

    Like Us On Facebook