Util class in java example

Java.util Package in Java

It contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).
Following are the Important Classes in Java.util package :

  1. AbstractCollection: This class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.
  2. AbstractList: This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “random access” data store (such as an array).
  3. AbstractMap: This class provides a skeletal implementation of the Map interface, to minimize the effort required to implement this interface.
  4. AbstractMap.SimpleEntry: An Entry maintaining a key and a value.
  5. AbstractMap.SimpleImmutableEntry: An Entry maintaining an immutable key and value.
  6. AbstractQueue: This class provides skeletal implementations of some Queue operations.
  7. AbstractSequentialList: This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “sequential access” data store (such as a linked list).
  8. AbstractSet: This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.
  9. ArrayDeque: Resizable-array implementation of the Deque interface.
  10. ArrayList: Resizable-array implementation of the List interface.
  11. Arrays: This class contains various methods for manipulating arrays (such as sorting and searching).
  12. BitSet: This class implements a vector of bits that grows as needed.
  13. Calendar: The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
  14. Collections: This class consists exclusively of static methods that operate on or return collections.
  15. Currency: Represents a currency.
  16. Date: The class Date represents a specific instant in time, with millisecond precision.
  17. Dictionary : The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values.
  18. EnumMap,V>: A specialized Map implementation for use with enum type keys.
  19. EnumSet: A specialized Set implementation for use with enum types.
  20. EventListenerProxy: An abstract wrapper class for an EventListener class which associates a set of additional parameters with the listener.
  21. EventObject: The root class from which all event state objects shall be derived.
  22. FormattableFlags: FomattableFlags are passed to the Formattable.formatTo() method and modify the output format for Formattables.
  23. Formatter: An interpreter for printf-style format strings.
  24. GregorianCalendar: GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.
  25. HashMap : Hash table based implementation of the Map interface.
  26. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance).
  27. Hashtable: This class implements a hash table, which maps keys to values.
  28. IdentityHashMap : This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).
  29. LinkedHashMap : Hash table and linked list implementation of the Map interface, with predictable iteration order.
  30. LinkedHashSet: Hash table and linked list implementation of the Set interface, with predictable iteration order.
  31. LinkedList: Doubly-linked list implementation of the List and Deque interfaces.
  32. ListResourceBundle: ListResourceBundle is an abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list.
  33. Locale – Set 1, Set 2: A Locale object represents a specific geographical, political, or cultural region.
  34. Locale.Builder: Builder is used to build instances of Locale from values configured by the setters.
  35. Objects: This class consists of static utility methods for operating on objects.
  36. Observable: This class represents an observable object, or “data” in the model-view paradigm.
  37. PriorityQueue: An unbounded priority queue based on a priority heap.
  38. Properties: The Properties class represents a persistent set of properties.
  39. PropertyPermission: This class is for property permissions.
  40. PropertyResourceBundle: PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file.
  41. Random: An instance of this class is used to generate a stream of pseudorandom numbers.
  42. ResourceBundle: Resource bundles contain locale-specific objects.
  43. ResourceBundle.Control: ResourceBundle.Control defines a set of callback methods that are invoked by the ResourceBundle.getBundle factory methods during the bundle loading process.
  44. Scanner: A simple text scanner which can parse primitive types and strings using regular expressions.
  45. ServiceLoader: A simple service-provider loading facility.
  46. SimpleTimeZone: SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar.
  47. Stack: The Stack class represents a last-in-first-out (LIFO) stack of objects.
  48. StringTokenizer: The string tokenizer class allows an application to break a string into tokens.
  49. Timer: A facility for threads to schedule tasks for future execution in a background thread.
  50. TimerTask: A task that can be scheduled for one-time or repeated execution by a Timer.
  51. TimeZone: TimeZone represents a time zone offset, and also figures out daylight savings.
  52. TreeMap: A Red-Black tree based NavigableMap implementation.
  53. TreeSet: A NavigableSet implementation based on a TreeMap.
  54. UUID: A class that represents an immutable universally unique identifier (UUID).
  55. Vector: The Vector class implements a growable array of objects.
  56. WeakHashMap: Hash table based implementation of the Map interface, with weak keys.
Читайте также:  Math class code java

Источник

Introduction to java.util Package

Hello all👋 I hope you are doing well. This is going to be a short introductory article about the most useful package in Java i.e., java.util package.

Let’s begin.

Let’s first understand package

What is a package?

In short a Java package is collection of similar type of classes.

A Package can be defined as a collection of similar types of classes, interfaces and sub-packages in the form of directory structure. You can read more about packages in one of my article here.

java.util

The basic utility classes required to a programmer are present in this package. It contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array). To use any class you have to import java.util package at top of the program:-

import java.util.Class_name; 

To make it easy let’s take an example, let’s suppose you want to print date and time in your program you will need to import java.util package.

import java.util.Date; //or //import java.util.*; public class Demo  public static void main(String[] args)  Date date = new Date(); System.out.println("The date is : " + date); > > 

java.util.png

You can run your code online here

What is use of java.util package?

  • For Java collections.
  • For random number generation.
  • For Calendar.
  • For string parsing.
  • For internationalization support by using the internationalization supported classes from java.util package (Locale).

Some important and generally used classes

Some important and generally used classes and interfaces which are present inside the java.util package are:-

  • Arrays :- This class contains various methods for manipulating arrays.
  • ArrayList :- This class is resizable-array implementation of the List interface.
  • Collections :- This class consists exclusively of static methods that operate on or return collections.
  • Date :- This class represents a specific instant in time, with millisecond precision.
  • EventObject :- This class is the root class from which all event state objects shall be derived.
  • Formatter :- An interpreter for printf-style format strings.
  • HashMap :- The HashMap class Hash table based implementation of the Map interface.
  • HashSet :- The HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance).
  • HashTable :- The HashTable class implements a hash table, which maps keys to values.
  • LinkedList :- The LinkedList class Doubly-linked list implementation of the List and Deque interfaces.
  • Locale :- A Locale object represents a specific geographical, political, or cultural region.
  • Objects :- This class consists of static utility methods for operating on objects.
  • Random :- An instance of this class is used to generate a stream of pseudorandom numbers.
  • Scanner :- A simple text scanner which can parse primitive types and strings using regular expressions. (Read more)
  • StringTokenizer :- The string tokenizer class allows an application to break a string into tokens.
  • Timer :- A facility for threads to schedule tasks for future execution in a background thread.
  • TimerTask :- A task that can be scheduled for one-time or repeated execution by a Timer.
  • TreeMap :- The TreeMap class A Red-Black tree based NavigableMap implementation.
  • TreeSet :- The TreeSet class A NavigableSet implementation based on a TreeMap.

Источник

Create a Utility Class in Java

Create a Utility Class in Java

Utility classes in Java are also known as Helper Class. It is an efficient way to create methods that can be re-used. The code we need to use over and over again can be put inside a utility class.

Usage of Utility Class in Java

The Java utility class is a stateless class that cannot be instantiated and declared using final and public keywords. In the example given below, we have a UtilityClassExample , which has a private constructor that prevents instantiation. For example, there are many examples of Util classes in Java like Apache StringUtils , CollectionUtils , or java.lang.Math .

The methods in the utility class should be declared static and not abstract as object methods need instantiation. The final keyword prevents subclassing. Here, we create our own Utility class with a private constructor, which, when invoked, throws an exception. Since we declared a private constructor, default can not be created; hence class can not be instantiated.

In the code given below, we have all members of the UtilityClassExample static. If we need to add or subtract two int or float type variables, we created methods in the utility class to re-use the code. We also have a method that returns a number multiplied by ten.

In the method addFloatValues() , we have also used Math.round() to round off the result to the nearest int. The Float class has the sum() method that returns the sum of two float arguments. We call each member method of this utility class passing arguments and print the output in the main() method of the class TestUtitity . Thus this utility class has methods that are used very often.

public final class UtilityClassExample   private static final int constantValue = 10;  private UtilityClassExample()   throw new java.lang.UnsupportedOperationException("Utility class and cannot be instantiated");  >  public static int addIntValues(int i,int j)  int sum = i + j;  return sum;  >  public static int subIntValues(int i,int j)  int diff = 0;  if(i>j)  diff = i - j;  >else  diff = j - i;  >  return diff;  >  public static float addFloatValues(float i, float j)  float sum = Float.sum(i,j);  return Math.round(sum);  >  public static float subFloatValues(float i, float j)  float diff = 0.00f;  if(i>j)  diff = i - j;  >else  diff = j - i;  >  return diff;  >   public static int returnValAfterMultiplying(int i)  return i * constantValue;  > >  class TestUtility   public static void main(String [] args)  int a = 4;  int b = 9;  int c = 7;  float d = 3.12f;  float e = 6.85f;   System.out.println(+a+" multiplied by ten is : "+UtilityClassExample.returnValAfterMultiplying(a));  System.out.println(b+"+"+c+" is : "+UtilityClassExample.addIntValues(b,c));  System.out.println(d+"+"+e+" is : "+UtilityClassExample.addFloatValues(d,e));  System.out.println(b+"-"+a+" is : "+UtilityClassExample.subIntValues(b,a));  System.out.println(e+"-"+d+" is : "+UtilityClassExample.subFloatValues(e,d));  > > 

Источник

Оцените статью