Java

Java Variable Types

Java Variable Types

Instance Variables 
Instance variables are also known as fields or member variables. They are declared inside a class but outside of any methods. Instance variables are created when an object of the class is created and they belong to the object. Each object of the class has its own copy of the instance variables. They are also called non-static variables.
Example: 

class Car { 
int speed; 
String colour; 
} 


The class "Car" has two instance variables, "speed" and "color," of type int and String. 

Local Variables 
Local variables are declared inside a method or a block of code. They are only accessible within the method or block where they are declared. They are also called automatic variables or stack variables. They are created when a method or block is executed, and they are destroyed when the method or block completes execution. 
Example: 

class Car { 
int speed; 
String colour; 
void setSpeed(int newSpeed) { 
int oldSpeed = speed; 
speed = newSpeed; 
System. out.println("Speed changed from " + oldSpeed + " to " + newSpeed); } 
} 

Here oldSpeed and newSpeed are two local variables 
It's important to remember that each variable has a specific scope, which defines where it can be accessed. Instance variables have a wider scope than local variables, and they are accessible throughout the class, while local variables are only accessible within the method or block where they are declared. 
 

Top course recommendations for you

    Circular Queue
    1 hrs
    Beginner
    3.1K+ Learners
    4.5  (213)
    Python Stack
    2 hrs
    Beginner
    5.8K+ Learners
    4.45  (301)
    AI and Big Data in IOT
    1 hrs
    Intermediate
    10.2K+ Learners
    4.47  (1152)
    Selenium Basics
    1 hrs
    Beginner
    25.4K+ Learners
    4.43  (1917)
    Selenium with Python
    1 hrs
    Beginner
    13.2K+ Learners
    4.44  (819)
    Selenium Projects with Python
    2 hrs
    Intermediate
    8.8K+ Learners
    4.5  (242)
    Java Projects
    1 hrs
    Beginner
    25.2K+ Learners
    4.19  (243)
    JDBC in Java
    1 hrs
    Beginner
    9.3K+ Learners
    4.42  (797)
    Flask Python
    1 hrs
    Beginner
    8.2K+ Learners
    4.38  (456)
    Linked List in Python
    3 hrs
    Beginner
    2.9K+ Learners
    4.55  (62)