Class scope in java

Scope of Variables/Methods in Java | Explained

In the programming world, the term scope refers to the area of a program in which certain data is accessible. In programming languages, the variables and methods should have a self-explanatory name and it must be unique as well, however at the same time, you have to maintain a unique, self-explanatory, and concise name which can be a little bit difficult if the program is very much lengthy.

Therefore programming languages offer the concept of scope which says not all variables/methods exist everywhere in the program instead these variables and methods will be accessible in the area where they are created.

This write-up presents a profound understanding of the following concepts:

Scope of Variable in Java

It determines whether the variable will be accessible within the entire program, within a method, or it’s accessible across the other classes as well. So in simple words, the scope of the variables determines that the variables are accessible only within the area where they are created.

Example

The below snippet will provide a better understanding of variable scope

public class MethodScope {
public static void main ( String [ ] args ) {
// the variable «name» can’t be used here

// hereafter «name» can be used anywhere in the method
System . out . println ( name ) ;
}
}

Let’s consider an example to test what will be the output, if we try to access a variable before it’s declaration:

The above snippet authenticates that the variable before its declaration can’t be accessed.

Class-level Scope in Java

The variables declared inside a class can be accessed by all the functions in that class depending on its access modifier/specifier i.e. public, private, etc. In some cases (i.e. in public access modifiers and using objects of that specific class), we can access and call the variables and methods outside the class as well.

For the profound understanding of the concepts consider the below code snippet:

package javascope ;
class ClassExample1 {
public String var1 ;
private int var2 ;

public void function1 ( String var1, int var2 ) {
// var1, var2 can be accessed here
System . out . println ( «function1» ) ;
}

private void function2 ( int var3 ) {
// var1, var2 can be accessed here
System . out . println ( «function2» ) ;
}
}

Читайте также:  Javascript console error messages

public class MainClass {
public static void main ( String [ ] args ) {
ClassExample1 obj = new ClassExample1 ( ) ;
// public variables can be accessed in this class
// public methods/functions can be called from here
function1 ( «Scope» , 5 ) ;
String name = obj. var1 ;
// private variables can be accessed in this class
int id = obj. var2 ; //Throws an error, can’t access private variables of other class here
// private methods/functions can’t be called from here
obj. function2 ( 4 ) ;
}
}

The complete code snippet will look like this:

From the above snippet we have seen that the public variables and methods can be accessed and called in other classes as well using the class’ object. However, we can’t access the private variables of one class to other class even with the help of a class object.

Method-level Scope in Java

The variable declare/created within the method will be accessible anywhere in that method after its declaration, however, it wouldn’t be accessible before its declaration. Moreover, accessing the variable of one method within the other method is not possible and if we talk about methods specifically, we can call one method within other methods as well.

The below snippet will provide a better understanding of method scope in Java:

Let’s consider the below screenshot for a profound understanding of method-level scope:

From the above snippet it is clear that we can’t access the variable of one method within other methods however, we can call a method from other methods.

Block-level Scope in Java

Everything that comes within the curly brackets <> is referred as block scope and the variables created within the block of code will be accessible by the code that comes between the curly braces. The variables declared within the block scope wouldn’t be accessible outside of the block scope.

In this example we create two variables having the method-level scope and initialize them some values:

public static void main ( String [ ] args ) {
String name = «John» ;
{
int id = 0 ;
for ( int i = 0 ; i id ++;
if ( id == 4 ) {
System . out . println ( «id: » + id ) ;
System . out . println ( «name: » + name ) ;
}

We utilize the for loop which will iterate five times and prints the name when “id = 4”. The below-snippet will provide a complete understanding of the scope and displays the output as well:

The snippet verifies that it successfully accesses both the variables i.e. name, id.

The variables created at block level wouldn’t be accessible before the start or after the end of block-level scope as shown in the below-given screenshot:

The above snippet verifies that an error occurs when we try to access the variable of block-level outside the block scope.

Читайте также:  Image binarization opencv python

Conclusion

A variable declared within the method scope will be accessible only inside the method and a variable declared within the block scope will be accessible within the block scope. We can’t access a variable before its declaration and accessing the variables outside of the scope will result in an error. This write-up presents a comprehensive guide for the scope of variables and methods in Java.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

Java Scope

In Java, variables are only accessible inside the region they are created. This is called scope.

Method Scope

Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:

Example

Block Scope

A block of code refers to all of the code between curly braces <> .

Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared:

Example

public class Main < public static void main(String[] args) < // Code here CANNOT use x < // This is a block // Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x); >// The block ends here // Code here CANNOT use x > >

A block of code may exist on its own or it can belong to an if , while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block’s scope.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Scope Rules in Java | What are scope rules for class members and local variables in Java?

In java, every class has members in terms of variables, constants, methods, and objects. To access these members from within the class, OR outside the class, java provides explicit accessibility modifiers to control the accessibility of members in a class. Below are the accessibility modifiers provided by Java —

Читайте также:  Получить enum по имени java

public
protected
default
private

The access to public, protected, default, and private members are governed by specific scope rules. Two such scope rules are —

-Class scope for members, and
-Block scope for local variables

What is the Class scope for members in Java?

The class scope for members defines the rules as to how member declarations are accessed within the class. It defines how to access the members including the inherited ones from code within a class.

Static members belong to a class and not to any object of the class therefore static code cannot be executed in the context of an object, therefore ‘this’ and ‘super’ references are not available for static members. Also, a static block cannot access the non-static (instance) members by their simple names but on the contrary static members can be accessed within a non-static block because the object has the knowledge of its class.

1. Static variable can be accessed by instance method of a class

2. Instance variables cannot be accessed by their simple names within a static method of a class

3. Static method can be called/accessed within an instance method of a class

4. Instance method cannot be called or accessed by their simple names within a static method of a class

5. ‘this’ reference keyword cannot be used in a static context/block/static method.

6. ‘super’ reference keyword cannot be used in a static context/block/static method.

What is the block scope for local variables in Java?

Block scope for local variables defines the scope as to how local variable declarations are accessed within a block. In java, the grouping of ‘declarations’ and ‘statements’ inside braces <> forms a block. Blocks can be nested and certain scope rules are applicable to local variables declared in such blocks.

1. A local variable can be declared anywhere inside a block.

2. A local variable declared inside a block is in scope or accessible within the block in which it is declared but it is not accessible outside of this block.

3. In a method, the parameters declared in the method parenthesis () along with the variables declared inside method block <> comprised of local variables. These local variables cannot be redeclared again in the same block.

4. The method parameters cannot be redeclared in the method body.

5. In the case of nested blocks, the variables declared in the outer block are visible in the inner block but the variables declared in the inner block cannot be accessible in the enclosing or outer block.

Источник

Оцените статью