Java Scope of Variables
Java Tutorial » Java Scope Method
Scope of a variable is the part of the program where the variable is accessible. These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class.
Example:
public class Test
{
// All variables defined directly inside a class
// are member variables
int x;
private String y;
void method_1() {....}
int method_2() {....}
char z;
}
{
// All variables defined directly inside a class
// are member variables
int x;
private String y;
void method_1() {....}
int method_2() {....}
char z;
}
We can declare class variables anywhere in class, but outside methods.
Method Scope example
Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:
Example
2240
public class Main {
public static void main(String[] args) {
// Code here cannot use a
int a = 2240;
// Code here can use a
System.out.println(a);
}
}
Output:public static void main(String[] args) {
// Code here cannot use a
int a = 2240;
// Code here can use a
System.out.println(a);
}
}
2240
Java Block Scope - Loop Variables, example
A variable declared inside pair of brackets “{” and “}” in a method has scope withing the brackets only.
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
225
public class Test
{
public static void main(String args[])
{
{
// The variable a has scope within
// brackets
int a = 225;
System.out.println(a);
}
// Uncommenting below line would produce
// error since variable a is out of scope.
// System.out.println(a);
}
}
Output:{
public static void main(String args[])
{
{
// The variable a has scope within
// brackets
int a = 225;
System.out.println(a);
}
// Uncommenting below line would produce
// error since variable a is out of scope.
// System.out.println(a);
}
}
225
java scope operator, variables, resolution operator, modifiers, definition, prototype, protected, try catch, class
Java Scope - java
Online Editor
This tool makes it easy to create, adjust, and experiment with custom colors for the web.
HTML Templates

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.
CSS HTML Layout

Find here examples of creative and unique website layouts.
Free CSS HTML Menu

Find here examples of creative and unique website CSS HTML menu.