📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
Comments
Post a Comment
Leave Comment