Java PriorityQueue Class ”; Previous Next Introduction The Java PriorityQueue class is an unbounded priority queue based on a priority heap. Following are the important points about PriorityQueue − The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects. Class declaration Following is the declaration for java.util.PriorityQueue class − public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable Parameters Following is the parameter for java.util.PriorityQueue class − E − This is the type of elements held in this collection. Class constructors Sr.No. Constructor & Description 1 PriorityQueue() This creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering. 2 PriorityQueue(Collection<? extends E> c) This creates a PriorityQueue containing the elements in the specified collection. 3 PriorityQueue(int initialCapacity) This creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering. 4 PriorityQueue(int initialCapacity, Comparator<? super E> comparator) This creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator. 5 PriorityQueue(PriorityQueue<? extends E> c) This creates a PriorityQueue containing the elements in the specified priority queue. 6 PriorityQueue(SortedSet<? extends E> c) This creates a PriorityQueue containing the elements in the specified sorted set. Class methods Sr.No. Method & Description 1 boolean add(E e) This method inserts the specified element into this priority queue. 2 void clear() This method removes all of the elements from this priority queue. 3 Comparator<? super E> comparator() This method returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements. 4 boolean contains(Object o) This method returns true if this queue contains the specified element. 5 void forEach(Consumer<? super E> action) This method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. 6 Iterator<E> iterator() This method returns an iterator over the elements in this queue. 7 boolean offer(E e) This method inserts the specified element into this priority queue. 8 boolean remove(Object o) This method removes a single instance of the specified element from this queue, if it is present. 9 boolean removeAll(Collection<?> c) This method removes all of this collection”s elements that are also contained in the specified collection (optional operation). 10 boolean removeIf(Predicate<? super E> filter) This method removes all of the elements of this collection that satisfy the given predicate. 11 boolean retainAll(Collection<?> c) This method retains only the elements in this collection that are contained in the specified collection (optional operation). 12 Spliterator<E> spliterator() This method creates a late-binding and fail-fast Spliterator over the elements in this queue. 13 <T> T[] toArray(T[] a) This method returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. Methods inherited This class inherits methods from the following classes − java.util.AbstractQueue java.util.AbstractCollection java.util.Object java.util.Collection Adding an Item to a Priority Queue Example The following example shows the usage of Java PriorityQueue add(E) method to add Integers. We”re adding couple of Integers to the PriorityQueue object using add() method calls per element and then print each element to show the elements added. package com.tutorialspoint; import java.util.PriorityQueue; public class PriorityQueueDemo { public static void main(String[] args) { // create an empty priority queue with an initial capacity PriorityQueue<Integer> queue = new PriorityQueue<>(5); // use add() method to add elements in the queue queue.add(20); queue.add(30); queue.add(20); queue.add(30); queue.add(15); queue.add(22); queue.add(11); // let us print all the elements available in queue for (Integer number : queue) { System.out.println(“Number = ” + number); } } } Let us compile and run the above program, this will produce the following result − Number = 11 Number = 20 Number = 15 Number = 30 Number = 30 Number = 22 Number = 20 Print Page Previous Next Advertisements ”;
Category: Java
Java – WeakHashMap
Java WeakHashMap Class ”; Previous Next Introduction The Java WeakHashMap class is a hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed by the garbage collector, when its key is no longer in use. Following are the important points about WeakHashMap − Both null values and the null key are supported. Like most collection classes, this class is also not synchronized. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. This class is a member of the Java Collections Framework. Class declaration Following is the declaration for java.util.WeakHashMap class − public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V> Here <K> is the type of keys maintained by this map and <V> is the type of mapped values. Class constructors Sr.No. Constructor & Description 1 WeakHashMap() This constructor is used to create an empty WeakHashMap with the default initial capacity (16) and load factor (0.75). 2 WeakHashMap(int initialCapacity) This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75). 3 WeakHashMap(int initialCapacity, float loadFactor) This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor. 4 WeakHashMap(Map<? extends K,? extends V> m) This constructor is used to create a new WeakHashMap with the same mappings as the specified map. Class methods Sr.No. Method & Description 1 void clear() This method removes all of the mappings from this map. 2 boolean containsKey(Object key) This method returns true if this map contains a mapping for the specified key. 3 boolean containsValue(Object value) This method returns true if this map maps one or more keys to the specified value. 4 Set<Map.Entry>K,V>> entrySet() This method returns a Set view of the mappings contained in this map. 5 v get(Object key) This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 6 boolean isEmpty() This method returns true if this map contains no key-value mappings. 7 Set<K> keySet() This method returns a Set view of the keys contained in this map. 8 v put(K key, V value) This method associates the specified value with the specified key in this map. 9 void putAll(Map<? extends K,? extends V> m) This method copies all of the mappings from the specified map to this map. 10 v remove(Object key) This method removes the mapping for a key from this weak hash map if it is present. 11 int size() This method returns the number of key-value mappings in this map. 12 Collection<V> values() This method returns a Collection view of the values contained in this map. Methods inherited This class inherits methods from the following classes − java.util.AbstractMap java.lang.Object java.util.Map Adding a Key-Value Pair to a WeakHashMap of Integer, Integer Pairs Example The following example shows the usage of Java WeakHashMap put() method to put few values in a Map. We”ve created a Map object of Integer,Integer pairs. Then few entries are added using put() method and then map is printed. package com.tutorialspoint; import java.util.WeakHashMap; public class WeakHashMapDemo { public static void main(String args[]) { // create hash map WeakHashMap<Integer,Integer> newmap = new WeakHashMap<>(); // populate hash map newmap.put(1, 1); newmap.put(2, 2); newmap.put(3, 3); System.out.println(“Map elements: ” + newmap); } } Output Let us compile and run the above program, this will produce the following result. Map elements: {3=3, 2=2, 1=1} Print Page Previous Next Advertisements ”;
Java – Hashtable
Java Hashtable Class ”; Previous Next Introduction The Java Hashtable class implements a hashtable, which maps keys to values.Following are the important points about Hashtable − In this any non-null object can be used as a key or as a value. If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. Class declaration Following is the declaration for java.util.Hashtable class − public class Hashtable<K,V> extends Dictionary<K,V> implements Hashtable<K,V>, Cloneable, Serializable Class constructors Sr.No. Constructor & Description 1 Hashtable() This constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75). 2 Hashtable(int initialCapacity) This constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75). 3 Hashtable(int initialCapacity, float loadFactor) This constructs a new, empty hashtable with the specified initial capacity and the specified load factor. 4 Hashtable(Hashtable<? extends K,? extends V> t) This constructs a new hashtable with the same mappings as the given Hashtable. Class methods Sr.No. Method & Description 1 void clear() This method clears this hashtable so that it contains no keys. 2 Object clone() This method creates a shallow copy of this hashtable. 3 V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). 4 V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this hashtable unless null. 5 V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value. 6 boolean contains(Object value) This method tests if some key maps into the specified value in this hashtable. 7 boolean containsKey(Object key) This method tests if the specified object is a key in this hashtable. 8 boolean containsValue(Object value) This method returns true if this hashtable maps one or more keys to this value. 9 Enumeration<V> elements() This method returns an enumeration of the values in this hashtable. 10 Set<Hashtable.Entry<K,V>> entrySet() This method returns a Set view of the mappings contained in this hashtable. 11 boolean equals(Object o) This method compares the specified Object with this Hashtable for equality, as per the definition in the Hashtable interface. 12 V get(Object key) This method returns the value to which the specified key is mapped, or null if this hashtable contains no mapping for the key. 13 int hashCode() This method returns the hash code value for this Hashtable as per the definition in the Hashtable interface. 14 boolean isEmpty() This method tests if this hashtable maps no keys to values. 15 Enumeration<K> keys() This method returns an enumeration of the keys in this hashtable. 16 Set<K> keySet() This method returns a Set view of the keys contained in this hashtable. 17 V put(K key, V value) This method maps the specified key to the specified value in this hashtable. 18 void putAll(Hashtable<? extends K,? extends V> t) This method copies all of the mappings from the specified hashtable to this hashtable. 19 V remove(Object key) This method removes the key (and its corresponding value) from this hashtable. 20 int size() This method returns the number of keys in this hashtable. 21 String toString() This method returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters “, ” (comma and space). 22 Collection<V> values() This method returns a Collection view of the values contained in this hashtable. Methods inherited This class inherits methods from the following classes − java.util.Object Adding a Mapping to a HashTable of Integer, Integer Pair Example The following example shows the usage of Java Hashtable put() method to put few values in a Hashtable. We”ve created a Hashtable object of Integer,Integer pairs. Then few entries are added using put() method and then table is printed. package com.tutorialspoint; import java.util.Hashtable; public class HashtableDemo { public static void main(String args[]) { // create hash table Hashtable<Integer,Integer> hashtable = new Hashtable<>(); // populate hash table hashtable.put(1, 1); hashtable.put(2, 2); hashtable.put(3, 3); System.out.println(“Hashtable elements: ” + hashtable); } } Let us compile and run the above program, this will produce the following result. Hashtable elements: {3=3, 2=2, 1=1} Print Page Previous Next Advertisements ”;
Java 15 – New Features
Java 15 – New Features ”; Previous Next Java 15 is a major feature release and it has brought many JVM specific changes and language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was released on Sep 2020, just six months after Java 14 release. Java 15 is a non-LTS release. New Features in Java 15 Following are the major new features which are introduced in Java 15. JEP 360 – Sealed Classes − To provide fine grained control over the inheritance. JEP 368 – Text Blocks − A second preview feature to handle multiline strings like JSON, XML easily. JEP 375 – Pattern matching Type Check − enhancements to existing pattern matching preview feature of Java 14. JEP 371 – Hidden Classes − To allow runtime creation of non-discoverable classes. JEP 384 – Records − A preview feature enhancing a new type record introduced in Java 14. JEP 383 – Foreign Memory Access API − Enhancement to incubating feature of java 14. JEP 377, 379 – Garbage Collectors − ZDC and Shenandoah garbage collectors are now part of standard API. JEP 339 – Edwards-Curve Digital Signature Algorithm (EdDSA) − Cryptographic signatures are now implemented using EdDSA. JEP 373 – Reimplement the Legacy DatagramSocket API − legacy implementations of the java.net.DatagramSocket and java.net.MulticastSocket APIs are replaced with simpler and more modern implementations which are easy to maintain and debug. Print Page Previous Next Advertisements ”;
Java – Optional Class
Java – Optional Class ”; Previous Next Optional class was introduced in Java 8 to simplify null pointer exception handling in code. A null pointer exception can come in cases where a method or property of a null object is invoked in code. Considering a very high possibility of a null pointer exception in code, developers generally try to handle null for each and every case but still being a runtime exception, programs remain error prone and chances of missing a null check remains high. Optional instance is a container object used to contain not-null object/value. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ”available” or ”not available” instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava. Optional class provides a type check solution instead of directly checking the null value. This class acts as a wrapper over the value. Apart from handling null value, Optional class provides lots of utility methods like getting a default value in case of null value, throwing exception in case underlying value is null. Optional Class Declaration Following is the declaration for java.util.Optional<T> class − public final class Optional<T> extends Object Optional Class Methods Sr.No. Method & Description 1 static <T> Optional<T> empty() Returns an empty Optional instance. 2 boolean equals(Object obj) Indicates whether some other object is “equal to” this Optional. 3 Optional<T> filter(Predicate<? super <T> predicate) If a value is present and the value matches a given predicate, it returns an Optional describing the value, otherwise returns an empty Optional. 4 <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper) If a value is present, it applies the provided Optional-bearing mapping function to it, returns that result, otherwise returns an empty Optional. 5 T get() If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. 6 int hashCode() Returns the hash code value of the present value, if any, or 0 (zero) if no value is present. 7 void ifPresent(Consumer<? super T> consumer) If a value is present, it invokes the specified consumer with the value, otherwise does nothing. 8 boolean isPresent() Returns true if there is a value present, otherwise false. 9 <U>Optional<U> map(Function<? super T,? extends U> mapper) If a value is present, applies the provided mapping function to it, and if the result is non-null, returns an Optional describing the result. 10 static <T> Optional<T> of(T value) Returns an Optional with the specified present non-null value. 11 static <T> Optional<T> ofNullable(T value) Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. 12 T orElse(T other) Returns the value if present, otherwise returns other. 13 T orElseGet(Supplier<? extends T> other) Returns the value if present, otherwise invokes other and returns the result of that invocation. 14 <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) Returns the contained value, if present, otherwise throws an exception to be created by the provided supplier. 15 String toString() Returns a non-empty string representation of this Optional suitable for debugging. 16 boolean isEmpty() Returns true if there is a value present, otherwise false. This class inherits methods from the following class − java.lang.Object Creating Optional Class Instance Optional class provides multiple methods to create an Optional instance for a provided value/object. Following are the corresponding methods with their syntaxes followed by an example: Optional.empty() method This method returns an Optional instance with empty value. It can be used to represent an absent value instead of null. Optional emptyOptional = Optional.empty(); Optional.of() method This method returns an Optional instance with given not null value. If provided value is null, then it will throw a NullPointerException. String name = “John”; Optional valueOptional = Optional.of(name); Optional.ofNullable() method This method returns an Optional instance with given value. If provided value is null, then it returns an empty Optional Instance. Optional emptyOptional = Optional.empty(); Example: Creating Optional Instances Following example showcases the use of above methods to create Optional objects and the cases when we should use them. package com.tutorialspoint; import java.util.Optional; public class OptionalTester { public static void main(String[] args) { Integer value1 = null; Integer value2 = Integer.valueOf(10); // Optional.empty – return an empty optional object Optional<Integer> empty = Optional.empty(); //Optional.ofNullable – allows passed parameter to be null. Optional<Integer> a = Optional.ofNullable(value1); //Optional.of – throws NullPointerException if passed parameter is null Optional<Integer> b = Optional.of(value2); System.out.println(“value of a: ” + (a.isPresent() ? a.get(): “0”)); System.out.println(“value of b: ” + (b.isPresent() ? b.get(): “0”)); System.out.println(“value of empty: ” + (empty.isPresent() ? empty.get(): “0”)); } } Let us compile and run the above program, this will produce the following result − value of a: 0 value of b: 10 value of empty: 0 Checking Optional Class Instance Value Optional class provides following method to check if Optional instance has value or not. These methods should be used before using get() method to obtain the value of the Optional instance as get() method can throw null pointer exception in case underlying value is null. Optional.isPresent() method This method checks the current optional instance and returns true/false based on value being present or not. Optional emptyOptional = Optional.empty(); boolean isValuePresent = emptyOptional.isPresent(); Optional.isEmpty() method This method checks the current optional instance and returns true/false based on value being present or not. This method was added to Optional API in Java 11. Optional emptyOptional = Optional.empty(); boolean isValuePresent = emptyOptional.isEmpty(); Example: Checking Optional Instances Following example showcases the use of above methods to create Optional objects and the cases when we should use them. package com.tutorialspoint; import java.util.Optional; public class OptionalTester { public static void main(String[] args) { Integer value1 = null; Integer value2 = Integer.valueOf(10); // Optional.empty – return an empty optional object Optional<Integer> empty = Optional.empty(); //Optional.ofNullable – allows passed parameter to be null. Optional<Integer> a = Optional.ofNullable(value1); //Optional.of – throws NullPointerException if passed parameter is null Optional<Integer> b = Optional.of(value2); System.out.println(“value of a: “
Java – Stack
Java Stack Class ”; Previous Next Introduction Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. The Java Stack class represents a last-in-first-out (LIFO) stack of objects. When a stack is first created, it contains no items. In this class, the last element inserted is accessed first. Class declaration Following is the declaration for java.util.Stack class − public class Stack<E> extends Vector<E> Class constructors Sr.No. Constructor & Description 1 Stack() This constructor creates an empty stack. Class methods Sr.No. Method & Description 1 boolean empty() This method tests if this stack is empty. 2 E peek() This method looks at the object at the top of this stack without removing it from the stack. 3 E pop() This method removes the object at the top of this stack and returns that object as the value of this function. 4 E push(E item) This method pushes an item onto the top of this stack. 5 int search(Object o) This method returns the 1-based position where an object is on this stack. Methods inherited This class inherits methods from the following classes − java.util.Vector java.util.Collection java.util.Object java.util.List Example The following program illustrates several of the methods supported by Stack collection − import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println(“push(” + a + “)”); System.out.println(“stack: ” + st); } static void showpop(Stack st) { System.out.print(“pop -> “); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println(“stack: ” + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println(“stack: ” + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println(“empty stack”); } } } This will produce the following result − Output stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack Print Page Previous Next Advertisements ”;
Java – ArrayList
Java ArrayList Class ”; Previous Next Introduction The Java ArrayList class provides resizable-array and implements the List interface.Following are the important points about ArrayList − It implements all optional list operations and it also permits all elements, includes null. It provides methods to manipulate the size of the array that is used internally to store the list. The constant factor is low compared to that for the LinkedList implementation. The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. Class declaration Following is the declaration for java.util.ArrayList class − public class ArrayList<E> extends AbstractList<E> implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess Here <E> represents an Element. For example, if you”re building an array list of Integers then you”d initialize it as ArrayList<Integer> list = new ArrayList<Integer>(); Class constructors Sr.No. Constructor & Description 1 ArrayList() This constructor is used to create an empty list with an initial capacity sufficient to hold 10 elements. 2 ArrayList(Collection<? extends E> c) This constructor is used to create a list containing the elements of the specified collection. 3 ArrayList(int initialCapacity) This constructor is used to create an empty list with an initial capacity. Class methods Sr.No. Method & Description 1 boolean add(E e) This method appends the specified element to the end of this list. 2 boolean addAll(Collection<? extends E> c) This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection”s Iterator 3 void clear() This method removes all of the elements from this list. 4 Object clone() This method returns a shallow copy of this ArrayList instance. 5 boolean contains(Object o) This method returns true if this list contains the specified element. 6 void ensureCapacity(int minCapacity) This increases the capacity of this ArrayList. 7 E get(int index) This method returns the element at the specified position in this list. 8 int indexOf(Object o) This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. 9 boolean isEmpty() This method returns true if this list contains no elements. 10 Iterator<E> iterator() This method returns an iterator over the elements in this list in proper sequence. 11 int lastIndexOf(Object o) This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. 12 ListIterator<E> listIterator() This method returns an list iterator over the elements in this list in proper sequence. 13 E remove(int index) This method removes the element at the specified position in this list. 14 boolean removeAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection. 15 protected void removeIf(int fromIndex, int toIndex) This method Removes all of the elements of this collection that satisfy the given predicate. 16 boolean retainAll(Collection<?> c) Retains from this list all of its elements that are contained in the specified collection. 17 E set(int index, E element) This method replaces the element at the specified position in this list with the specified element. 18 int size() This method returns the number of elements in this list. 19 Spliterator<E> spliterator() This method creates a late-binding and fail-fast Spliterator over the elements in this list. 20 List<E> subList(int fromIndex, int toIndex) This method returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. 21 Object[] toArray() This method returns an array containing all of the elements in this list in proper sequence (from first to last element). 22 void trimToSize() This method trims the capacity of this ArrayList instance to be the list”s current size. Methods inherited This class inherits methods from the following classes − java.util.AbstractList java.lang.AbstractCollection java.util.Object java.util.List Adding, Removing Elements to ArrayList of Strings Example The following program illustrates several of the methods supported by ArrayList − package com.tutorialspoint; import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); System.out.println(“Initial size of al: ” + al.size()); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); al.add(1, “A2”); System.out.println(“Size of al after additions: ” + al.size()); // display the array list System.out.println(“Contents of al: ” + al); // Remove elements from the array list al.remove(“F”); al.remove(2); System.out.println(“Size of al after deletions: ” + al.size()); System.out.println(“Contents of al: ” + al); } } This will produce the following result − Output Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] Print Page Previous Next Advertisements ”;
Java 9 – New Features
Java 9 – New Features ”; Previous Next JAVA 9 (aka jdk 1.9) is a major release of JAVA programming language development. Its initial version was released on 21 Sep 2017. The main goals of Java 9 release were − To make JDK and Java Standard Edition platform modular based in the sense that it can be scalled down to small computing devices well. To improve the overall security of the JDK and Java Implementations. To make build process and maintainance of java code libraries and large applications easy for for JAVA SE and EE platforms. To design and implement a standard module system for the Java Platform which can be applied on both Platform and JDK easily. Following is the list of new features supported in Java 9: Module System Module System was introduced to enhance Modularity in java code to next level. A module is a self describing collection of data and code. A module can contain packages, configurations specific to particular functionality. A module provides a better access control over its contents. Java library from Java 9 is divided into multiple modules as can be seen using following command. C:UsersMahesh>java –list-modules [email protected] [email protected] [email protected] [email protected] … [email protected] [email protected] Example – Using Module Below snippet is defining a module declared in module-info.java file in root folder of the application. module com.tutorialspoint.greetings { requires com.tutorialspoint.util; requires static com.tutorialspoint.logging; requires transitive com.tutorialspoint.base; exports com.tutorialspoint.greetings.HelloWorld; opens com.tutorialspoint.greetings.HelloWorld; } Here we”ve stated that our module is dependent on three modules and exporting a public Class to be used by outside world and allows reflection to inspect a particular class. By default, private members of modules are not accessible via reflection. REPL REPL stands for Read Evaluate Print Loop. A REPL EngineJShell was introduced in Java 9 as an interactive console to run arbitrary snippet of java code in console without need to save and compile java code file. JShell reads each line entered, evaluates it and then print the result and then again becomes ready for next set of input. Example – Using JShell as REPL Following snippet shows how to create variables in JShell. semi-colon is optional. We can create objects as well in JShell. If a variable is not initialized then it is given a default value or null if it is an object reference. Once a variable is created, it can be used as shown in the last statement where we”ve used the string variable to print its value. Example In following example, we”ve created variables, evaluate expressions, created date objects. jshell> int i = 10 i ==> 10 jshell> String name = “Mahesh”; name ==> “Mahesh” jshell> Date date = new Date() date ==> Fri Feb 02 14:52:49 IST 2024 jshell> String.format(“%d pages read.”, 10); $9 ==> “10 pages read.” jshell> $9 $9 ==> “10 pages read.” jshell> name name ==> “Mahesh” Improved JavaDocs From Java 9, Java now supports HTML5 output generation and provides a search box to generated API documentation. Example In this example, we”re creating a HTML5 compliant javadoc. Consider the following code in C:/JAVA folder. Tester.java /** * @author MahKumar * @version 0.1 */ public class Tester { /** * Default method to be run to print * <p>Hello world</p> * @param args command line arguments */ public static void main(String []args) { System.out.println(“Hello World”); } } Run the javadoc tool of jdk 9 with -html5 flag to generate new type of documentation. C:JAVA> javadoc -d C:/JAVA -html5 Tester.java Loading source file Tester.java… Constructing Javadoc information… Standard Doclet version 9.0.1 Building tree for all the packages and classes… Generating C:JAVATester.html… Generating C:JAVApackage-frame.html… Generating C:JAVApackage-summary.html… Generating C:JAVApackage-tree.html… Generating C:JAVAconstant-values.html… Building index for all the packages and classes… Generating C:JAVAoverview-tree.html… Generating C:JAVAindex-all.html… Generating C:JAVAdeprecated-list.html… Building index for all classes… Generating C:JAVAallclasses-frame.html… Generating C:JAVAallclasses-frame.html… Generating C:JAVAallclasses-noframe.html… Generating C:JAVAallclasses-noframe.html… Generating C:JAVAindex.html… Generating C:JAVAhelp-doc.html… It will create the updated java documentation page in D:/test directory and you will see the following output. Multirelease JAR Multirelease JAR feature in Java 9 enhances the JAR format so that multiple, Java release-specific versions of class files can coexist in a single archive. In multi-release Jar format, a jar file can have different versions of Java classes or resources that can be maintained and used as per the platform. In JAR, a file MANIFEST.MF file has an entry Multi-Release: true in its main section. META-INF directory also contains a versions subdirectory whose subdirectories (starting with 9 for Java 9 ) store version-specific classes and resource files. Using MANIFEST.MF, we can specific Java 9 or higher version-specific classes in separate locations as shown below − Java Multi-Release Jar Files Directory Structure Example jar root – Calculator.class – Util.class – Math.class – Service.class META-INF – versions – 9 – Util.class – Math.class – 10 – Util.class – Math.class Now if JRE is not support Multi-release jar, then it will choose the root level classes to load and execute otherwise, version specific classes will be loaded. For example, if above jar is used in Java 8, then root level Util.class will be used. If same jar is executed by Java 9, then java 9 version specific class will be picked and so on. This way, third party libraries/frameworks can support new features without changing their source codes which was written targeting the lower versions. Collection Factory Methods Improvements In Java 9, New static factory methods are added to List, Set, and Map interfaces to create immutable instances of those collections. These factory methods are mainly convenience factory methods in order to create a collection in less verbose and in concise way. Example of List Interface Factory Methods Before Java 9 Here, we are
Java – Arrays
Java Arrays Class ”; Previous Next Introduction The Java Arrays class contains a static factory that allows arrays to be viewed as lists. Following are the important points about Arrays − This class contains various methods for manipulating arrays (such as sorting and searching). The methods in this class throw a NullPointerException if the specified array reference is null. Arrays Class Declaration Following is the declaration for java.util.Arrays class − public class Arrays extends Object Arrays Class Methods Sr.No. Method & Description 1 static <T> List<T> asList(T… a) This method returns a fixed-size list backed by the specified array. 2 static int binarySearch(byte[] a, byte key) This method searches the specified array of bytes for the specified value using the binary search algorithm. 3 static int binarySearch(char[] a, char key) This method searches the specified array of chars for the specified value using the binary search algorithm. 4 static int binarySearch(double[] a, double key) This method searches the specified array of doubles for the specified value using the binary search algorithm. 5 static int binarySearch(float[] a, float key) This method searches the specified array of floats for the specified value using the binary search algorithm. 6 static int binarySearch(int[] a, int key) This method searches the specified array of ints for the specified value using the binary search algorithm. 7 static int binarySearch(long[] a, int fromIndex, int toIndex, long key) This method searches a range of the specified array of longs for the specified value using the binary search algorithm. 8 static int binarySearch(Object[] a, Object key) This method searches the specified array for the specified object using the binary search algorithm. 9 static int binarySearch(short[] a, short key) This method searches the specified array of shorts for the specified value using the binary search algorithm. 10 static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) This method searches the specified array for the specified object using the binary search algorithm. 11 static int compare(boolean[] a, boolean[] b) This method compares two boolean arrays lexicographically. 12 static int compare(byte[] a, byte[] b) This method compares two byte arrays lexicographically. 13 static int compare(char[] a, char[] b) This method compares two char arrays lexicographically. 14 static int compare(double[] a, double[] b) This method compares two double arrays lexicographically. 15 static int compare(float[] a, float[] b) This method compares two float arrays lexicographically. 16 static int compare(int[] a, int[] b) This method compares two int arrays lexicographically. 17 static int compare(long[] a, long[] b) This method compares two long arrays lexicographically. 18 static int compare(short[] a, short[] b) This method compares two short arrays lexicographically. 19 compareUnsigned(byte[] a, byte[] b) This method compares two byte arrays lexicographically, numerically treating elements as unsigned. 20 compareUnsigned(int[] a, int[] b) This method compares two int arrays lexicographically, numerically treating elements as unsigned. 21 compareUnsigned(long[] a, long[] b) This method compares two long arrays lexicographically, numerically treating elements as unsigned. 22 compareUnsigned(short[] a, short[] b) This method compares two short arrays lexicographically, numerically treating elements as unsigned. 23 static boolean[] copyOf(boolean[] original, int newLength) This method copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. 24 static byte[] copyOf(byte[] original, int newLength) This method copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. 25 static char[] copyOf(char[] original, int newLength) This method copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. 26 static double[] copyOf(double[] original, int newLength) This method copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. 27 static float[] copyOf(float[] original, int newLength) This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. 28 static int[] copyOf(int[] original, int newLength) This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. 29 static long[] copyOf(long[] original, int newLength) This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. 30 static short[] copyOf(short[] original, int newLength) This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. 31 static <T> T[] copyOf(T[] original, int newLength) This method copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. 32 static <T, U> T[] copyOf(U[] original, int newLength,Class<? extends T[]> newType) This method copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. 33 static boolean[] copyOfRange(boolean[] original, int from, int to) This method copies the specified range of the specified array into a new array. 34 static byte[] copyOfRange(byte[] original, int from, int to) This method copies the specified range of the specified array into a new array. 35 static char[] copyOfRange(char[] original, int from, int to) This method copies the specified range of the specified array into a new array. 36 static double[] copyOfRange(double[] original, int from, int to) This method copies the specified range of the specified array into a new array. 37 static int[] copyOfRange(int[] original, int from, int to) This method copies the specified range of the specified array into a new array. 38 static long[] copyOfRange(long[] original, int from, int to) This method copies the specified range of the specified array into a new array. 39 static short[] copyOfRange(short[] original, int from, int to) This method copies the specified range of the specified array into a new array. 40 static <T> T[] copyOfRange(T[] original, int from, int to) This method copies the specified range of the specified array into a new array. 41 static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) This method copies the specified range of the specified array into a new array. 42 static boolean deepEquals(Object[]
Java 12 – New Features
Java 12 – New Features ”; Previous Next Java 12 is a major feature release and it has brought many language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was releasd on Mar 2019, just six months after Java 11 release. Java 12 is a non-LTS release. New Features Following are the major new features which are introduced in Java 12. JVM Changes − JEP 189, JEP 346, JEP 344, and JEP 230. Switch Expressions − A preview feature allowing switch to use lambda expression. File.mismatch() method − File Comparison is made easy via mismatch method. Compact Number Formatting − Numbers can be formatted like 2K, 3M etc easily. Teeing Collector in Stream API − A merging operator on multiple collectors. String new methods − four new methods introduced to format a string. JEP 334 − JVM Constants API introduced. JEP 305 − A preview feature allowing pattern matching for instanceOf. Garbage Collection Enhancement Print Page Previous Next Advertisements ”;