#Complete noob (In intro to programming 1 atm); having an issue with a homework assignment...

1 messages · Page 1 of 1 (latest)

kindred ospreyBOT
#

<@&987246399047479336> please have a look, thanks.

quartz pike
#

yeah

#

so a variable declared in one method isn't shared with other methods

kindred ospreyBOT
#

In Java, there are four types of variable scopes:

  1. Class/Instance Variable Scope: These variables are declared within a class but outside any method, constructor, or block. They are also known as instance variables because each instance of the class has its own copy of these variables. They can be accessed by any method or constructor within the class.

Example:

public class MyClass {
    int x; // instance variable
    
    public void myMethod() {
        System.out.println(x); // Accessing instance variable
    }
}
  1. Local Variable Scope: These variables are declared within a method, constructor, or block and can only be accessed within that particular scope. They are created when the method/block is called and destroyed when it completes execution.

Example:

public void myMethod() {
    int x = 10; // local variable
    
    System.out.println(x); // Accessing local variable
}
  1. Method Parameter Scope: These variables are passed as arguments to a method and have scope within that method only.

Example:

public void myMethod(int x) { // Method parameter
    System.out.println(x); // Accessing method parameter
}
  1. Block Scope: These variables are declared within a block (enclosed in curly braces) and can only be accessed within that block. They include variables declared in loops, if statements, try-catch blocks, etc.

Example:

public void myMethod() {
    if (true) {
        int x = 10; // Block scope
        
        System.out.println(x); // Accessing block scope variable
    }
}
finite tundra
#

Thanks for the assistance