Java Variables -Part II

2. Instance Variables:

An instance variable is a variable that is declared within a class, but not within a method or constructor. Unlike static variables, these variables are declared without the use of the “static” keyword. They can be accessed by any method or constructor within the class.

Example:

public class variableType {

    public String name = "Ben";
    public int marks = 95;

    public void instanceVariable() {
        System.out.println(name + " Scored " + marks + "%.");
    }

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

Output:

Ben Scored 95%.

3. Class/Static Variables:

A static variable is a variable declared within a class, but outside of any method or constructor. It is differentiated from an instance variable by its declaration using the “static” keyword. These variables can be accessed by all methods or constructors within the class.

Example:

public class variableType {

    public static String name;
    public static int marks;

    public static void main(String[] args) {
        name = "Ben";
        marks = 95;
        System.out.println(name + " Scored " + marks + "%.");
    }
}

Output:

Ben Scored 95%.

Variables that are not declared static result in errors.

Example:

public class variableType {
    public String name;
    public int marks;

    public static void main(String[] args) {
        name = "Ben";
        marks = 95;
        System.out.println(name + " Scored " + marks + "%.");
    }
}

Output:

Cannot make a static refrence to a non-static field
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