Showing posts with label global variable. Show all posts
Showing posts with label global variable. Show all posts

Thursday, 2 April 2020

How to define global variables in Java?

Using ‘public’ and ‘static’ keywords, you can define global variables.

public class GlobalVariable {
    public static int readCount = 0;
    public static int writeCount = 0;
    public static int appAccessCount = 0;
}

You can access the global variable using classname.

Example
'GlobalVariable.readCount'

If you want to define global constants, you can define an interface and define the variables inside the interface.

public interface GlobalConstants {
    float PI = 3.14F;
    float ERROR_RATE = 0.001f;
}

Note:
Variables in interface are ‘public’ ‘static’ ‘final’ by default.

You may like

Sunday, 9 December 2018

How to define a global variable that is property of global object?

If you assign a value to any undeclared variable, then it becomes a property of global object.

In case of web pages, window is the global object. If you assign a value to any undeclared variable, then it becomes the property of the global object window.

For example,
Hello.html
<!DOCTYPE html>

<html>
 <head>
  <title>Variables</title>
 </head>
 
 <body>
  <script type="text/javascript">
 message = "Hello World";
 
 document.write("message : " + window.message);
  </script>
 </body>
</html>

As you see, the variable ‘message’ is undeclared (not declared with var, let, const keywords), but assigned with value "Hello World". In this case, it becomes the property of global object ‘window’.

What is the advantage of Global variables that are attached to global object?
You can access the global variable that is declared in one frame (or) window from another frame (or) window.

Previous                                                 Next                                                 Home

Saturday, 8 December 2018

How to declare a global variable in a document?

When you declare any variable outside of a function, then it is global to the current document, and all the code in the document can access this global variable.

HelloWorld.js

var x = 10;

function increment_x(){
  x++;
}

function multiply_x_by_10(){
  x *= 10;
}

function print_x(){
  console.log("Value of x is : " + x);
}

increment_x();
print_x();

multiply_x_by_10();
print_x();

Output
Value of x is : 11
Value of x is : 110




Previous                                                 Next                                                 Home