The Runtime.getRuntime().availableProcessors() method returns the maximum number of processors available to the Java virtual machine, the value will never be smaller than one. Knowing the number of available processor you can use it for example to limit the number of thread in your application when you are writing a multi-thread code.
package org.kodejava.lang;
public class NumberProcessorExample {
public static void main(String[] args) {
final int processors = Runtime.getRuntime().availableProcessors();
System.out.println("Number of processors = " + processors);
}
}
The code snippet below shows you a simple way to calculate days between two dates excluding weekends and holidays. As an example, you can use this function for calculating work days. The snippet utilize the java.time API and the Stream API to calculate the value.
What we do in the code below can be described as the following:
Create a list of holidays. The dates might be read from a database or a file.
Define filter Predicate for holidays.
Define filter Predicate for weekends.
These predicates will be use for filtering the days between two dates.
Define the startDate and the endDate to be calculated.
Using Stream.iterate() we iterate the dates, filter it based on the defined predicates.
Finally, we get the result as list.
The actual days between is the size of the list, workDays.size().
package org.kodejava.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class DaysBetweenDates {
public static void main(String[] args) {
List<LocalDate> holidays = new ArrayList<>();
holidays.add(LocalDate.of(2022, Month.DECEMBER, 26));
holidays.add(LocalDate.of(2023, Month.JANUARY, 2));
Predicate<LocalDate> isHoliday = holidays::contains;
Predicate<LocalDate> isWeekend = date -> date.getDayOfWeek() == DayOfWeek.SATURDAY
|| date.getDayOfWeek() == DayOfWeek.SUNDAY;
LocalDate startDate = LocalDate.of(2022, Month.DECEMBER, 23);
LocalDate endDate = LocalDate.of(2023, Month.JANUARY, 3);
System.out.println("Start date = " + startDate);
System.out.println("End date = " + endDate);
// Days between startDate inclusive and endDate exclusive
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Days between = " + daysBetween);
List<LocalDate> workDays = Stream.iterate(startDate, date -> date.plusDays(1))
.limit(daysBetween)
.filter(isHoliday.or(isWeekend).negate())
.toList();
long actualDaysBetween = workDays.size();
System.out.println("Actual days between = " + actualDaysBetween);
}
}
Running the code snippet above give us the following result:
Start date = 2022-12-23
End date = 2023-01-03
Days between = 11
Actual days between = 5
The following code example demonstrate how to export MySQL database schema into markdown table format. We get the table structure information by executing MySQL’s DESCRIBE statement.
The steps we do in the code snippet below:
Connect to the database.
We obtain the list of table name from the database / schema.
Executes DESCRIBE statement for each table name.
Read table structure information such as field, type, null, key, default and extra.
Write the information into markdown table format and save it into table.md.
And here are the complete code snippet.
package org.kodejava.jdbc;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DescribeMySQLToMarkDown {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
String tableQuery = """
select table_name
from information_schema.tables
where table_schema = 'kodejava'
and table_type = 'BASE TABLE'
order by table_name;
""";
try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(tableQuery);
List<String> tables = new ArrayList<>();
while (resultSet.next()) {
tables.add(resultSet.getString("table_name"));
}
System.out.println(tables.size() + " tables found.");
try (BufferedWriter writer = new BufferedWriter(new FileWriter("table.md"))) {
for (String table : tables) {
System.out.println("Processing table: " + table);
Statement statement = connection.createStatement();
ResultSet descResult = statement.executeQuery("DESCRIBE " + table);
writer.write(String.format("Table Name: **%s**%n%n", table));
writer.write("| Field Name | Data Type | Null | Key | Default | Extra |\n");
writer.write("|:---|:---|:---|:---|:---|:---|\n");
while (descResult.next()) {
String field = descResult.getString("field");
String type = descResult.getString("type");
String nullInfo = descResult.getString("null");
String key = descResult.getString("key");
String defaultInfo = descResult.getString("default");
String extra = descResult.getString("extra");
String line = String.format("| %s | %s | %s | %s | %s | %s |%n",
field, type, nullInfo, key, defaultInfo, extra);
writer.write(line);
}
writer.write("\n<br/>\n<br/>\n");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This code snippet will produce something like below. I have tidy up the markdown for a better presentation.
Table Name: **books**
| Field Name | Data Type | Null | Key | Default | Extra |
|:-----------|:----------------|:-----|:----|:--------|:---------------|
| id | bigint unsigned | NO | PRI | null | auto_increment |
| isbn | varchar(30) | NO | | null | |
<br/>
<br/>
The simplest way to get the Java version is by running the java -version command in your terminal application or Windows command prompt. If Java is installed and available on your path you can get information like below.
java -version
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)
Using System Properties
But if you want to get Java version from your Java class or application you can obtain the Java version by calling the System.getProperty() method and provide the property key as argument. Here are some property keys that related to Java version that you can read from the system properties.
Since JDK 9 we can use Runtime.version() to get Java runtime version. The feature(), interim(), update and patch() methods of the Runtime.Version class are added in JDK 10. These methods is a replacement for the major(), minor() and security() methods of JDK 9.
Below is the code snippet that demonstrate the Runtime.version().
Filter items in a long list are often accomplished using the JTextField component. As the user inputs into the JTextField component, the set of items shown in the list is narrowed to just those things that correspond to the input received from the user.
It is necessary to utilize two elements to implement this function of the JList component, one of which is a model that filters a set of elements based on some text. The other executes the filter method when the user enters text.
Implementing the input field is a simpler job, so let’s start with it in our review of the implementation process. The JTextField component model is a document used with a Swing set of components. It is necessary to implement the DocumentListener interface in the model in order to monitor input to a Document. Text input, updating, and deletion are tracked using three methods defined below:
public void insertUpdate (DocumentEvent event)
public void changedUpdate (DocumentEvent event)
public void removeUpdate (DocumentEvent event)
When the model attributes are updated, the changedUpdate() method is used to update the model. It is possible that it will not be realized. In order to avoid duplicating filtering actions across all three methods, the generic method generated in the custom model is simply called by the other two. A detailed explanation of the JTextField component, which is used for filtering in the JList component, may be found in the following section:
In order to avoid being restricted to just using the JTextField component that was generated using the JList, the installJTextField() method is used, which attaches the event listener to the component that was built using the JList in the first place. In addition, a mechanism is provided to eliminate this match. Through the usage of these methods, the user of a filtering JList may choose to use their own JTextField in place of the default one.
public void installJTextField(JTextField input) {
input.getDocument().addDocumentListener(listener);
}
public void unnstallJTextField(JTextField input) {
input.getDocument().removeDocumentListener(listener);
}
After that, the filtering model is taken into consideration. This case implements the filter() function, which is invoked by methods that implement the DocumentListener interface, as seen below. To put this strategy into action, you’ll need to have two lists of objects on hand: a source list and a filtered list of items. Because you are inheriting from the AbstractListModel class, you must implement some of the methods listed below in your code:
Constructor
Method for adding items to the model is being implemented in this project.
getElementAt() is used to get an element.
getSize() is used to retrieve sizes.
The constructor produces two instances of the List objects. The type of objects that are stored as List elements does not matter. Therefore List objects are generated to carry items of the following types:
List<Object> list;
List<Object> filteredList;
public FilteringModel() {
list = new ArrayList<>();
filteredList = new ArrayList<>();
}
Model elements are added by adding them to the original model and then filtering the resulting model with the previously added elements. Optimization of this approach may be achieved by using a method to filter a single element when it is added; however, in this implementation, the filter() function is invoked when an element is added, which is also used to filter the whole list. (It should be noted that the event implementation in the DocumentListener also invokes the filter() method.) As a result, even when only one item is added to the list, the whole list is filtered, with each item that matches the search parameters being added to the filtered list.
public void addElement(Object element) {
list.add(element);
filter();
}
The size of the returned model is the same as the size of the filtered list, but not the same as the original:
public int getSize() {
return filteredList.size();
}
Similar to the technique for obtaining the size of a model, the method for obtaining an item from a list returns elements from the filtered list rather than the original list. In order to avoid having to go through the complete list, it has been implemented as follows:
Finally, the filter() method is responsible for most of the work. Because you have no way of knowing whether the new search string will broaden or limit the set of items, the quickest and most straightforward solution is to remove the whole filtered list and replace it with items that fit your search criteria from the original list. A match may be discovered at the beginning of a line as well as at any point throughout it. An example of searching for the letter “A” is shown below. This function enables you to locate items in a string that begin with the capital letter “A” or contain the letter “A” at any point in the string.
void filter(String search) {
filteredList.clear();
for (Object element: list) {
if (element.toString().contains(search)) {
filteredList.add(element);
}
}
fireContentsChanged(this, 0, getSize());
}
It is important to note that the search in this approach is case-sensitive. You may alter the method to implement a case-insensitive search and start the search at the beginning of the string.
After you have added entries to the filtered list, you may also sort the results. This operation requires your familiarity with the model’s contents. The function toString() is currently used by search, which does not indicate that it may include elements of a suitable type that can also be sorted when it is performed.
Here is a full implementation of the JList filter element with an inner class ListModel, as seen in the accompanying code sample. This class implements the DocumentListener interface, which the text component uses to listen for new documents. Although the addition of this class may seem needless at first look, given that filtering is only done for this model, the specification of behavior in this implementation is the most accurate.
package org.kodejava.swing;
import javax.swing.AbstractListModel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.util.ArrayList;
import java.util.List;
public class FilteringJList extends JList<Object> {
private JTextField input;
public FilteringJList() {
setModel(new FilteringModel());
}
public void installJTextField(JTextField input) {
if (input != null) {
this.input = input;
FilteringModel model = (FilteringModel) getModel();
input.getDocument().addDocumentListener(model);
}
}
public void uninstallJTextField(JTextField input) {
if (input != null) {
FilteringModel model = (FilteringModel) getModel();
input.getDocument().removeDocumentListener(model);
this.input = null;
}
}
public void setModel(ListModel<Object> model) {
if (!(model instanceof FilteringModel)) {
throw new IllegalArgumentException();
} else {
super.setModel(model);
}
}
public void addElement(Object element) {
((FilteringModel) getModel()).addElement(element);
}
private static class FilteringModel extends AbstractListModel<Object> implements DocumentListener {
List<Object> list;
List<Object> filteredList;
String lastFilter = "";
public FilteringModel() {
list = new ArrayList<>();
filteredList = new ArrayList<>();
}
public void addElement(Object element) {
list.add(element);
filter(lastFilter);
}
public int getSize() {
return filteredList.size();
}
public Object getElementAt(int index) {
Object returnValue;
if (index < filteredList.size()) {
returnValue = filteredList.get(index);
} else {
returnValue = null;
}
return returnValue;
}
void filter(String search) {
filteredList.clear();
for (Object element : list) {
if (element.toString().contains(search)) {
filteredList.add(element);
}
}
fireContentsChanged(this, 0, getSize());
}
public void insertUpdate(DocumentEvent event) {
Document doc = event.getDocument();
try {
lastFilter = doc.getText(0, doc.getLength());
filter(lastFilter);
} catch (BadLocationException ble) {
System.err.println("Bad location: " + ble);
}
}
public void removeUpdate(DocumentEvent event) {
Document doc = event.getDocument();
try {
lastFilter = doc.getText(0, doc.getLength());
filter(lastFilter);
} catch (BadLocationException ble) {
System.err.println("Bad location: " + ble);
}
}
public void changedUpdate(DocumentEvent event) {
}
}
}
It is now necessary to develop a test program. The following six lines will be crucial in the event. They build a JList component, attach it to the JScrollPane component, and then attach a text box to it as seen in the code:
FilteringJList list = new FilteringJList();
JScrollPane pane=new JScrollPane(list);
frame.add(pane,BorderLayout.CENTER);
JTextField text=new JTextField();list.installJTextField(text);
frame.add(text,BorderLayout.NORTH);
To the model, new components are introduced in the program’s primary body. The model shown below includes a list of Christmas gifts, the names of Santa’s reindeer, the names of London Underground lines, and the letters of the Greek alphabet.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.EventQueue;
public class JListFiltersDemo {
public static void main(String[] args) {
Runnable runner = () -> {
JFrame frame = new JFrame("Filtering List");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FilteringJList list = new FilteringJList();
JScrollPane pane = new JScrollPane(list);
frame.add(pane, BorderLayout.CENTER);
JTextField text = new JTextField();
list.installJTextField(text);
frame.add(text, BorderLayout.NORTH);
String[] elements = {
"Partridge in a pear tree", "Turtle Doves", "French Hens",
"Calling Birds", "Golden Rings", "Geese-a-laying",
"Swans-a-swimming", "Maids-a-milking", "Ladies dancing",
"Lords-a-leaping", "Pipers piping", "Drummers drumming",
"Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid",
"Donner", "Blitzen", "Rudolf", "Bakerloo", "Center",
"Circle", "District", "East London", "Hammersmith and City",
"Jubilee", "Metropolitan", "Northern", "Piccadilly Royal",
"Victoria", "Waterloo and City", "Alpha", "Beta", "Gamma",
"Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa",
"Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "Sigma",
"Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega"};
for (String element : elements) {
list.addElement(element);
}
frame.setSize(500, 500);
frame.setVisible(true);
};
EventQueue.invokeLater(runner);
}
}
Filtering JList Component Models Demo
Because this filtering strategy is based on the JList component and its accompanying JTextField component, it will operate successfully if your list’s entries are appropriately displayed when you use the function toString(). Creating a Filter interface that is provided to the model when filtering operations are performed might be useful for doing more complicated filtering tasks.
In this example, the only item that is not addressed is the process of selection. By default, when the contents of the model list change, the JList does not update the selection of the model list. Filtering may be used to either retain the chosen item or emphasize the first item in the list, depending on the desired behavior.
Even though the original JList component does not explicitly offer the functionality, there are techniques to implement filtering. Overriding the getNextMatch() function allows you to alter the default behavior if you so want.
This article covers basic operators of Java syntax, and how they function. By thorough discussion and coding examples, you’ll be able to use basic operators in your programs like a pro.
What are basic operators?
Java provides different sets of operators to perform simple computations like addition/ subtraction and other advanced operators for decision-making or individual bitwise calculations.
Here are some major categories of operators
Arithmetic Operators (+, -, *, /)
Relational Operators (==, !=)
Logical Operators (&&, ||)
Assignment Operators (=, +=, -=)
Unary Operators (pre/post-fix)
Shift Operators (>>, << )
Bitwise Operators (&, |, ^)
Ternary/Conditional Operator (?:)
Misc Operators
The scope of this article encompass arithmetic, relational and logical operators only.
Arithmetic Operators
You can use basic arithmetic operators to perform a mathematical calculation and impact the value of any variable. Let’s see how it works in Java.
package com.basicoperators.core;
public class ArithmeticOperators {
public static void main(String[] args) {
// Addition
int apples = 5;
int oranges = 7;
int totalFruits = apples + oranges;
System.out.println("\n-------------Addition---------------- " );
System.out.println("Apples: " + apples);
System.out.println("Oranges: " + oranges);
System.out.println("Total Fruits: " + totalFruits);
// Subtraction
int totalBananas = 24;
int bananasSold = 12;
int bananasLeft = totalBananas - bananasSold;
System.out.println("\n----------------Subtraction--------------- " );
System.out.println("Total Bananas: " + totalBananas);
System.out.println("Bananas Sold: " + bananasSold);
System.out.println("Bananas Left: " + bananasLeft);
// Multiplication
int weeks = 3;
int daysInAWeek = 7;
int totalNumberOfDays = weeks * daysInAWeek;
System.out.println("\n--------------Multiplication-------------- " );
System.out.println("Days In A Week: " + daysInAWeek);
System.out.println("Days In A Week: " + daysInAWeek);
System.out.println("Total Number Of Days: " + totalNumberOfDays);
// Division
int totalMinutesConsumed = 420;
int minutesInOneHour = 60;
int numOfHours = totalMinutesConsumed / minutesInOneHour;
System.out.println("\n----------------Division---------------- " );
System.out.println("Total Minutes: " + totalMinutesConsumed);
System.out.println("Minutes In One Hour: " + minutesInOneHour);
System.out.println("Num Of Hours: " + numOfHours);
}
}
Output
----------------------Addition----------------------
Apples: 5
Oranges: 7
Total Fruits: 12
---------------------Subtraction---------------------
Total Bananas: 24
Bananas Sold: 12
Bananas Left: 12
--------------------Multiplication-------------------
Days In A Week: 7
Days In A Week: 7
Total Number Of Days: 21
----------------------Division----------------------
Total Minutes Consumed: 420
Minutes In One Hour: 60
Num Of Hours: 7
Relational Operators
As the name implies, relational operators define the relationship of one instance with another. This means you can compare two numbers and see what relationship do they share. If they are equal to each other, one is greater than or smaller than the other number. Like 2 is less than 3. According to Java syntax, both instances should be of the same data type. For example, you can not compare if an integer is less than a string. Here is a small snippet explaining how you can use basic relational operators in Java.
package com.basicoperators.core;
public class RelationalOperators {
public static void main(String[] args) {
int even = 2;
int odd = 3;
System.out.println("Even = " + even);
System.out.println("Odd = " + odd);
// prints if even is equal to odd
boolean check = even == odd;
System.out.println("Is Even equal to Odd? " + check);
// prints if even is not equal to odd
check = even != odd;
System.out.println("Is Even not equal to Odd? " + check);
// prints if even is greater than odd
check = even > odd;
System.out.println("Is Even greater than Odd? " + check);
// prints if even is less than odd
check = even < odd;
System.out.println("Is Even less than Odd? " + check);
// prints if even is greater than equal to odd
check = even >= odd;
System.out.println("Is Even greater than equal to Odd? " + check);
// prints if even is less than equal to odd
check = even <= odd;
System.out.println("Is Even less than equal to Odd? " + check);
}
}
Output
Even = 2
Odd = 3
Is Even equal to Odd? false
Is Even not equal to Odd? true
Is Even greater than Odd? false
Is Even less than Odd? true
Is Even greater than equal to Odd? false
Is Even less than equal to Odd? true
Logical Operators
Logical Operators in Java are used for decision-making. They allow the programmer to test if the combination of given expressions are true or false. Based on the result of your expression, you can make a decision.
AND – returns “true” only if both expressions are true
OR – returns “true” if any of the given expressions is true
NOT – returns the “inverse” of any given boolean expression
For your better understanding, let’s look at the following snippet.
package com.basicoperators.core;
public class LogicalOperators {
public static void main(String[] args) {
String myPet1 = "doggo";
String myPet2 = "kitty";
System.out.println("Pet1: " + myPet1);
System.out.println("Pet2: " + myPet2);
// implements AND
boolean check = myPet1.equals("doggo") && myPet2.equals("kitty");
// returns true only when both conditions are true
System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);
check = myPet1.equals("dog") && myPet2.equals("kitty");
// returns "false" even if single condition is false
// remember these conditions are case sensitive
System.out.println("Does my first pet name \"dog\", and second one \"kitty\"? " + check);
// implements OR
check = myPet1.equals("doggo") || myPet2.equals("lion");
// returns "true" even when single condition is true
System.out.println("Does any of my pet name \"doggo\"? " + check);
check = myPet1.equals("cat") || myPet2.equals("tiger");
// returns "false" because both conditions are false
System.out.println("Does any of my pet name \"tiger\"? " + check);
// implements NOT
check = !(myPet1.equals("bingo") && myPet2.equals("kate"));
// returns "true" when both conditions are true (inverse of statement)
System.out.println("Does my first pet name \"bingo\", and second one \"kate\"? " + check);
check = !(myPet1.equals("doggo") && myPet2.equals("kitty"));
// returns "false" because both conditions are true
System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);
}
}
Output
Pet1: doggo
Pet2: kitty
Does my first pet name "doggo", and second one "kitty"? true
Does my first pet name "dog", and second one "kitty"? false
Does any of my pet name "doggo"? true
Does any of my pet name "tiger"? false
Does my first pet name "bingo", and second one "kate"? true
Does my first pet name "doggo", and second one "kitty"? false
Conclusion
The basic operators in Java are pretty simple to learn and easy to use. You might get overwhelmed by studying the different operators all at once. However, we recommend you practicing one set at a time. This way, you’ll master all of them soon. As always, you’re welcome to plug-in in case of any confusion. Happy learning!
In this example you will learn how to create a generic class in Java. In some previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.
As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.
package org.kodejava.generics;
public class GenericMachine<T> {
private final T engine;
public GenericMachine(T engine) {
this.engine = engine;
}
public static void main(String[] args) {
// Creates a generic machine with diesel engine.
GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());
machine.start();
// Creates another generic machine with jet engine.
GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());
anotherMachine.start();
}
private void start() {
System.out.println("This machine running on: " + engine);
}
}
Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compiled successfully. And here are the engine classes:
package org.kodejava.generics;
public class DieselEngine {
}
package org.kodejava.generics;
public class JetEngine {
}
The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.
The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.
To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.
To retrieve a list of all available time zones ids we can call the java.time.ZoneId static method getAvailableZoneIds(). This method return a Set of string of all zone ids. The format of the zone id are “{area}/{city}”. You can use these ids of string to create the ZoneId object using the ZoneId.of() static method.
package org.kodejava.datetime;
import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;
public class GetAllTimeZoneIds {
public static void main(String[] args) {
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
for (String id : zoneIds) {
ZoneId zoneId = ZoneId.of(id);
System.out.println("id = " + id);
System.out.println("displayName = " +
zoneId.getDisplayName(TextStyle.FULL, Locale.US));
}
}
}
Here are some zone IDs printed out to the console:
id = Asia/Aden
displayName = Arabian Time
id = America/Cuiaba
displayName = Amazon Time
id = Etc/GMT+9
displayName = GMT-9:00
id = Etc/GMT+8
displayName = GMT-8:00
id = Africa/Nairobi
displayName = Eastern Africa Time
...
...
...
id = Europe/Nicosia
displayName = Eastern European Time
id = Pacific/Guadalcanal
displayName = Solomon Is. Time
id = Europe/Athens
displayName = Eastern European Time
id = US/Pacific
displayName = Pacific Time
id = Europe/Monaco
displayName = Central European Time