In Java, there is no global keyword, but we can use a public static variable to referring a global variable.
Examples
For example, you can create a global variable in Java like:
UserService.java
import java.util.HashMap;
import java.util.Map;
public class UserService {
public static Map < String, String > cache = new HashMap < > (); // GLOBAL VARIABLE
public static final String GLOBAL_USER_NAME = "RAMESH"; // GLOBAL VARIABLE
public static final int ID = 100; // GLOBAL VARIABLE
public static Map < String, String > getCache() {
return cache;
}
// Put data in global cache variable
public static void putCache(String key, String value) {
cache.put(key, value);
}
}
GlobalVariableDemo.java
Below Java program demonstrates how to use the above created global variables. Note that you can also write data to global variables (refer cache global variable)
package com.javaguides.websocketdemo.model;
import java.util.Map;
import java.util.Map.Entry;
public class GlobalVariableDemo {
public static void main(String[] args) {
// Put data in global variable
UserService.putCache("key1", "value1");
UserService.putCache("key2", "value2");
UserService.putCache("key3", "value3");
// Access global variable
Map < String, String > map = UserService.cache;
for (Entry < String, String > entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
// Access GLOBAL_USER_NAME variable
System.out.println(UserService.GLOBAL_USER_NAME);
// Access ID global variable
System.out.println(UserService.ID);
}
}
Output:
key1
value1
key2
value2
key3
value3
RAMESH
100
Comments
Post a Comment
Leave Comment