Variables in Java-Part I

Information can be stored in variables, which the programmer can then change and refer to later in the code. The data type of a Java variable can provide information about the size and organisation of the variable’s memory.

Syntax:

datatype variable = value

There are three types of variables in java:

  1. Local variable
  2. Instance variable
  3. Class/Static variable
  1. Local Variables:

A variable declared within the body of a method or constructor is referred to as a local variable. This is because the scope of a local variable is limited to the method or constructor in which it is defined, and it cannot be accessed by other methods in the class.To declare a local variable within the method body, the “static” keyword is used.

For example:

public class variableType {
    public void localVariable() {
        String name = "Ben";
        int marks = 95;
        System.out.println(name + " Scored " + marks + "%.");
    }

    public static void main(String[] args) {
        variableType vt = new variableType();
        vt.localVariable();
    }
}

Output:

Ben Scored 95%.

If an attempt is made to access a local variable outside the method or constructor in which it was created, it will result in an error.

For example:

public class variableType {
    public void localVariable() {
        String name = "Ben";
        int marks = 95;
    }
    public void notLocalVariable() {
        System.out.println(name + " Scored " + marks + "%.");
    }

    public static void main(String[] args) {
        variableType vt = new variableType();
        vt.notLocalVariable();
    }
}

Output:

name cannot be resolved to a variable
marks cannot be resolved to a variable
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in