In this section I cover a bunch of Java Utility Classes, covering BitSet, Optional, Date, Calendar, GregorianCalendar, TimeZone, Locale, Random, Observable, Timer/TimerTask, Currency, Formatter and Scanner. Some class may be deprecated but I list them here as some are still out in the wild and thus a bit of knowledge on them won't harm.
A BitSet class creates a special type of array that holds bit values in the form of boolean values
BitSet Example | BitSet bs1 = new BitSet(16); for(int i=0; i<16; i++) { if ((i % 2) == 0) bs1.set(i); // set the bits } System.out.println("Bits in BitSet: " + bs1); System.out.println("Bit at position 0: " + bs1.get(0)); // retrieve a bit System.out.println("Bit at position 0: " + bs1.get(1)); // retrieve a bit // lets set a bit and use and (or, xor also available) bs1.set(1, Boolean.TRUE); // set a bit bs1.and(bs1); // use and (or, xor available also) System.out.println("Bits in BitSet: " + bs1); Output -------------------------------------------------- Bits in BitSet: {0, 2, 4, 6, 8, 10, 12, 14} Bit at position 0: true Bit at position 0: false Bits in BitSet: {0, 1, 2, 4, 6, 8, 10, 12, 14} |
There a number of Optional classes, Optional, OptionalDouble, OptionalInt and OptionaLong, basically they all do the same thing and in that they handle situations in which a value may or may not be present. This helps with nullpointer exceptions.
Optional Example | Optional<String> noVal = Optional.empty(); Optional<String> hasVal = Optional.of("ABCDEF"); if( noVal.isPresent() ) System.out.println("This won't be displayed"); if(hasVal.isPresent()) System.out.println("The string in hasVal is: " + hasVal.get()); String defaultStr = noVal.orElse("Default String"); System.out.println(defaultStr); Output -------------------------------------- The string in hasVal is: ABCDEF Default String |
The Date classes encapsulates date/time, however many functions have now been moved to Calendar and DateFormat classes, to set dates you use a Long number which is the number of milliseconds since 1 Jan 1970
Date Example | Date date = new Date(); System.out.println("Date is: " + date); System.out.println("Milliseconds since 1 jan 1970: " + date.getTime()); // use the milliseconds sine 1 jJan 1970 to set time date.setTime(1488948517000L); System.out.println("Date is: " + date); Output ------------------------------------------- Date is: Fri May 08 15:45:24 BST 2020 Milliseconds since 1 jan 1970: 1588949124979 Date is: Wed Mar 08 04:48:37 GMT 2017 |
The Calendar Class provides a set of methods that allows you to convert a time in milliseconds to a number of components such as year, month, day, hours, minutes and seconds.
Calendar Example | String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; // Create a calendar initialized with the // current date and time in the default // locale and timezone. Calendar calendar = Calendar.getInstance(); // Display current time and date information. System.out.print("Date: "); System.out.print(months[calendar.get(Calendar.MONTH)]); System.out.print(" " + calendar.get(Calendar.DATE) + " "); System.out.println(calendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); // Set the time and date information and display it. calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 29); calendar.set(Calendar.SECOND, 22); System.out.print("Updated time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); Output ----------------------------- Date: May 8 2020 Time: 3:46:22 Updated time: 10:29:22 |
The GregorianCalendar Class is a concrete implementation of Calendar, the GregorianCalendar defines two fields AD and BC the two eras defined by the Gregorian calendar.
GregorianCalender Example | String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int year; // Create a Gregorian calendar initialized // with the current date and time in the // default locale and timezone. GregorianCalendar gcalendar = new GregorianCalendar(); System.out.println(gcalendar.getTime()); // Display current time and date information. System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND)); // Test if the current year is a leap year if(gcalendar.isLeapYear(year)) { System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year"); } Output ------------------------ Fri May 08 15:54:02 BST 2020 Date: May 8 2020 Time: 3:54:2 The current year is a leap year |
DataFormat and SimpleDataFormat Classes
The DataFormat class provides you the ability to format and parse dates and times, the SimpleDateFormat is a concreate of DateFormat and allows you to define your own patterns to display date and time information.
DataFormat Example | Date date = new Date(); DateFormat df; df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN); System.out.println("Japan: " + df.format(date)); df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.UK); System.out.println("United Kingdom: " + df.format(date)); df = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA); System.out.println("Canada: " + df.format(date)); |
SimpleDataFormat Example | Date date = new Date(); SimpleDateFormat sdf; sdf = new SimpleDateFormat("hh:mm:ss"); System.out.println(sdf.format(date)); sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz"); System.out.println(sdf.format(date)); sdf = new SimpleDateFormat("E MMM dd yyyy"); System.out.println(sdf.format(date)); sdf.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("GMT"))); |
The newer Time and Date API has been around since JDK8, this is a large package package however three commonly used classes are LocalDate, LocalTime and LocalDateTime, you can retrieve date, time plus you can format, compare, add/substract days, etc.
Time and Date API Example | LocalDate curDate1 = LocalDate.now(); System.out.println(curDate1); LocalTime curTime1 = LocalTime.now(); System.out.println(curTime1); LocalDate curDate2 = LocalDate.now(); System.out.println(curDate2.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL))); LocalTime curTime2 = LocalTime.now(); System.out.println(curTime2.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))); LocalDateTime curDateTime1 = LocalDateTime.now(); System.out.println(curDateTime1.format(DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a"))); // Obtain a LocalDateTime object by parsing a date and time string. LocalDateTime curDateTime2 = LocalDateTime.parse("May 12, 2020 8:50 am", DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a")); System.out.println(curDateTime2.format(DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a"))); |
Converting seconds to hours, minutes and seconds | public class exercise55 { public static void main(String[] args) { // There are many ways to do this, here are some examples Scanner in = new Scanner(System.in); System.out.println("Enter seconds: "); Integer ts = in.nextInt(); int seconds = ts % 60; int hours = ts / 60; int minutes = hours % 60; hours /= 60; System.out.println("Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds); hours = ts / 3600; minutes = (ts % 3600) / 60; seconds = ts % 60; System.out.println(String.format("Hours: %02d Minutes: %02d Seconds: %02d", hours, minutes, seconds)); System.out.println(LocalTime.MIN.plusSeconds(ts).toString()); } } |
The TimeZone Class allows you to work with timezones offset with Greenwich Mean Time (GMT), also referred to as Coordinated Universal Time (UTC), it compute daylight saving time as well.
TimeZone Example | TimeZone tz1 = TimeZone.getDefault(); System.out.println("ID: " + tz1.getID() + ", DisplayName: " + tz1.getDisplayName()); TimeZone tz2 = TimeZone.getTimeZone("Australia/Sydney"); System.out.println("ID: " + tz2.getID() + ", DisplayName: " + tz2.getDisplayName()); TimeZone tz3 = TimeZone.getTimeZone(ZoneId.systemDefault()); System.out.println("ID: " + tz3.getID() + ", DisplayName: " + tz3.getDisplayName()); TimeZone tz4 = TimeZone.getTimeZone(ZoneId.of("Asia/Jakarta")); System.out.println("ID: " + tz4.getID() + ", DisplayName: " + tz4.getDisplayName()); Output --------------------------- ID: Europe/London, DisplayName: Greenwich Mean Time ID: Australia/Sydney, DisplayName: Australian Eastern Standard Time ID: Europe/London, DisplayName: Greenwich Mean Time ID: Asia/Jakarta, DisplayName: Western Indonesia Time |
The Locale Class is used to describe a geographical or cultural region, it can be used if the application is used in different parts of the world, Internationalization is a very large topic which i won't be covering here.
Locale Example | // Creates a locale object using one parameter to constructor Locale locale = new Locale("fr"); System.out.println("locale: "+locale); // Create a locale object using two parameters constructor Locale locale2 = new Locale("fr", "CANADA"); System.out.println("locale2: "+locale2); // Create a locale object using three parameters constructor Locale locale3 = new Locale("no", "NORWAY", "NY"); System.out.println("locale3: "+locale3); // A local object from Locale.Builder Locale localeFromBuilder = new Locale.Builder().setLanguage("en").setRegion("GB").build(); System.out.println("localeFromBuilder: "+localeFromBuilder); //Locale from forLanguageTag method Locale forLangLocale = Locale.forLanguageTag("en-GB"); System.out.println("forLangLocale: "+forLangLocale); //Using Locale Contant Locale localeCosnt = Locale.FRANCE; System.out.println("localeCosnt: "+localeCosnt); Outout ------------------------------ locale: fr locale2: fr_CANADA locale3: no_NORWAY_NY localeFromBuilder: en_GB forLangLocale: en_GB localeCosnt: fr_FR |
The Random Class generates pseudorandom numbers, you specify the starting point for the number sequence.
Random Example | // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println("Random Integers: "+rand_int1); System.out.println("Random Integers: "+rand_int2); // Generate Random doubles double rand_dub1 = rand.nextDouble(); double rand_dub2 = rand.nextDouble(); // Print random doubles System.out.println("Random Doubles: "+rand_dub1); System.out.println("Random Doubles: "+rand_dub2); Output (will be similar to below): ------------------------------------------- Random Integers: 200 Random Integers: 959 Random Doubles: 0.4157682759881811 Random Doubles: 0.728011652311483 |
The Observable Class is used to create subclasses that other parts of your program can observe, when the subclass changes the observing classes are notified. This class has been deprecated but you may still see it in the wild. The Flow Class can be used as an alternative.
Observable Example | import java.util.*; // This is the observing class. class Watcher implements Observer { public void update(Observable obj, Object arg) { System.out.println("update() called, count is " + ((Integer)arg).intValue()); } } // This is the class being observed. class BeingWatched extends Observable { void counter(int period) { for( ; period >=0; period--) { setChanged(); notifyObservers(new Integer(period)); try { Thread.sleep(100); } catch(InterruptedException e) { System.out.println("Sleep interrupted"); } } } } class ObserverDemo { public static void main(String args[]) { BeingWatched observed = new BeingWatched(); Watcher observing = new Watcher(); /* Add the observing to the list of observers for observed object. */ observed.addObserver(observing); observed.counter(10); } } |
The Timer and TimerTask Classes allows you to schedule a task, you create a thread that runs in the background waiting for a specific time, when the time arrives the thread is run.
Timer/TimerTask Example | public class TimerTest { public static void main(String[] args) { MyTimerTask myTask = new MyTimerTask(); Timer myTimer = new Timer(); // Set an initial delay of 1 second,then repeat every half second. myTimer.schedule(myTask, 1000, 500); try { Thread.sleep(5000); } catch (InterruptedException exc) {} myTimer.cancel(); } } class MyTimerTask extends TimerTask { public void run() { System.out.println("Timer task executed."); } } |
The Currency Class encapsulates information about a currency
Currency Example | Currency c; c = Currency.getInstance(Locale.US); System.out.println("Symbol: " + c.getSymbol()); System.out.println("Default fractional digits: " + c.getDefaultFractionDigits()); System.out.println(); c = Currency.getInstance(Locale.UK); System.out.println("Symbol: " + c.getSymbol()); System.out.println("Default fractional digits: " + c.getDefaultFractionDigits()); Output ------------------------- Symbol: US$ Default fractional digits: 2 Symbol: £ Default fractional digits: 2 |
The Formatter Class allows you to format output, it provides format conversions that let you display numbers, strings, time/dates, etc. It operates the same a C/C++ printf() function. I have show a few basic examples but there is many functions for you to explore.
Formatter Example | Formatter fmtStr = new Formatter(); fmtStr.format("Formatting %s is easy %d %f", "with Java", 10, 98.6); System.out.println(fmtStr); fmtStr.close(); Formatter fmtNum = new Formatter(); for(double i=1.23; i < 1.0e+6; i *= 100) { fmtNum.format("%f %e", i, i); System.out.println(fmtNum); } fmtNum.close(); Output ----------------------------- Formatting with Java is easy 10 98.600000 1.230000 1.230000e+00 1.230000 1.230000e+00123.000000 1.230000e+02 1.230000 1.230000e+00123.000000 1.230000e+0212300.000000 1.230000e+04 |
The Scanner Class reads formetted input and converts it into its binary form, generally Console is used to read data from the console but can also be used to read a file, strings or any source that implements the Readable or ReadableByteChannel interfaces. You can read in strings, numbers, lines, etc
Scanner Example | Scanner consoleIn = new Scanner(System.in); System.out.println("Whats your name: "); String name = consoleIn.next(); System.out.println("Whats your age: "); Integer age = consoleIn.nextInt(); System.out.println("Hello " + name + " you are " + age + " years old"); |