What Is The Local Variable And Global Variable In Java? - News4u95 - A Part of Your Everyday Life

Breaking

Sunday, June 5, 2022

What Is The Local Variable And Global Variable In Java?

What Is The Local Variable And Global Variable In Java?

Local Variable And Global Variable In Java 

What Is The Local Variable And Global Variable In Java?
What Is The Local Variable And Global Variable In Java?

Local Variable In Java

What Is Local Variable?

1. Variable is a container which holds the value

2. Variable is name of memory location

3. Variable always declare with data type.

4. Variable which is present inside the method is called local variable.

 

Why We Use Local Variable?

1. To store the value, we use variable.

2. To maintain the scope of value within the method, we use local variable.

3. To maintain the heap memory, we use local variable.

 

When We Use Local Variable?

1. When we want to store the value at method level, we use local variable.

2. When we don’t want to give scope of value outside the method, we use local variable.

 

How We Use Local Variable?

1. Local variable always declare inside the method

2. Syntax of variable: data_type variable_name = value;

 

Example of Local Variable:

public class Trials {

                void method() {

                                int n = 90; // local variable

                                System.out.println(n);

                }

                public static void main(String args[]) {

                                Trials obj = new Trials();

                                obj.method();

                }

}// end of class"

 

Global Variable In Java

What Is Global Variable?

1. Variable is a container which holds the value

2. Variable is name of memory location

3. Variable always declare with data type.

4. Variable which is present outside the method is called global variable.

5. Global variable also known as instance variable.

 

Why We Use Global Variable?

1. To store the value, we use variable.

2. To maintain the scope of value at class level, we use global variable.

 

When We Use Global Variable?

1. When we want to store the value at class level, we use local variable.

2. When we want to give scope of value outside the method, we use global variable.

 

How We Use Global Variable?

1. Global variable always declare outside the method but inside the class.

2. Syntax of variable : data_type variable_name = value;

 

Example of Global Variable:

public class Trials {

                int n = 90;  // global variable

                void method() {

                                System.out.println(n);

                }

                public static void main(String args[]) {

                                Trials obj = new Trials();

                                obj.method();

                }

}// end of class

 

Read More Articles: What Is Main Method, Print Method and Output In Java?

No comments:

Post a Comment