Variables

Variable Declaration in Java

Used to declare a variable.


Syntax
modifier dataType variableName; //modifier is optional

//variables can be assigned values either separately or on declaration
variableName = value; //separate line assignment

modifier dataType variableName = value; //same line assignment

Notes

The modifier (public, private) restricts or permits direct access to the variable with respect to its scope (class, method, etc.).

Standard (non-static) variables declared within a class are called instance variables. Their value is attached to each class instance.

Variables without a modifier are known as local variables, typically used within a method. They are temporary and only exist within the scope of the where its declared method.

dataType is the data type of the variable. It can either be a primitive data type, or a String. Note that because a String is not a primitive data type, it must use same line assignment (with a value or with null) and cannot be modified after being assigned a value.


Example
public class Car { 
    private int speed; //public variable declaration
    public int wheels; //private variable declaration
    
    /*...constructor, etc...*/

    public void speedUp() {
        //local variable declaration, in line assignment, only seen within speedUp method
        int speedIncrease = 10;
        speed += speedIncrease;
    }
}

< Type Casting   |   Constants >

© 2019 SyntaxDB. All Rights Reserved.