Examples
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
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);
}
}
key1
value1
key2
value2
key3
value3
RAMESH
100
References
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment