Java – SortedSet Interface ”; Previous Next The SortedSet interface extends Set and declares the behavior of a set sorted in an ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods summarized in the following table − Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set. SortedSet Interface Methods Sr.No. Method & Description 1 Comparator comparator( ) Returns the invoking sorted set”s comparator. If the natural ordering is used for this set, null is returned. 2 Object first( ) Returns the first element in the invoking sorted set. 3 SortedSet headSet(Object end) Returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set. 4 Object last( ) Returns the last element in the invoking sorted set. 5 SortedSet subSet(Object start, Object end) Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object. 6 SortedSet tailSet(Object start) Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object. Operations on SortedSet Interface Creating a SortedSet TreeSet class implements the SortedSet interface. We can use the TreeSet constructor to create a SortedSet instance. Following is the syntax to create a SortedSet instance: Syntax // Create the sorted set SortedSet<String> set = new TreeSet<>(); Here we”re creating a sorted set of String values. This map will store the unique string values. If a duplicate value is added, then that will be discarded. Adding Value to a SortedSet SortedSet provides an add() method, which can be used to add value to a SortedSet instance. Whenever a value is added to the set, it is checked against the existing values. If the set is modified then method will return true otherwise false will be returned. Syntax public boolean add(E e) Where E represents the element to be added. If element is already present, then no action will be performed and method will return false. Example // Add elements to the set set.add(“b”); set.add(“c”); set.add(“a”); Getting value from a SortedSet In order to get values from a SortedSet, we”ve to get the iterator object from the SortedSet using the iterator() method. Once the iterator object is available then that object can be used to retrieve values present in the SortedSet. Example // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); System.out.println(element.toString()); } Deleting a value from a SortedSet Using the remove(value) method, we can remove the value/object stored in the SortedSet easily. Syntax public boolean remove(Object value) if value is not present in the set, then it will return false otherwise it will remove the value and return true. set.remove(“a”); Iterating SortedSet SortedSet entries can be easily navigated. SortedSet provides a method iterator() which provides an iterator to navigate all the entries of the set. Syntax public Iterator<E> iterator() Where E is the type of objects to be iterated. Example // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); System.out.println(element.toString()); } Examples of SortedSet Interface Adding Element to a SortedSet Example SortedSet have its implementation in various classes like TreeSet. Following is an example of a TreeSet class with add operation− import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; public class SortedSetDemo { public static void main(String[] args) { // Create the sorted set SortedSet<String> set = new TreeSet<>(); // Add elements to the set set.add(“b”); set.add(“c”); set.add(“a”); // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); System.out.println(element.toString()); } } } Output a b c Removing Element from a SortedSet Example SortedSet have its implementation in various classes like TreeSet. Following is an example of a TreeSet class with add and remove operation − import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; public class SortedSetDemo { public static void main(String[] args) { // Create the sorted set SortedSet<String> set = new TreeSet<>(); // Add elements to the set set.add(“b”); set.add(“c”); set.add(“a”); set.add(“d”); set.add(“e”); set.add(“f”); // remove elements set.remove(“c”); set.remove(“f”); // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); System.out.println(element.toString()); } } } Output a b d e Clearing a SortedSet Example SortedSet have its implementation in various classes like TreeSet. Following is an example of a TreeSet class with add and clear operation − import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; public class SortedSetDemo { public static void main(String[] args) { // Create the sorted set SortedSet<String> set = new TreeSet<>(); // Add elements to the set set.add(“b”); set.add(“c”); set.add(“a”); set.add(“d”); set.add(“e”); set.add(“f”); System.out.println(set); // remove elements set.clear(); System.out.println(set); } } Output [a, b, c, d, e, f] [] Advantages of SortedSet Interface SortedSet ensures that the map is always sorted in ascending order of the values. Whenever a key-value pair is added to the SortedSet, it is re-sorted Being sorted and unique, SortedSet is very efficient in searches We can customize the sorting mechanism by using a comparator on the value type. Disadvantages of SortedSet Interface As a SortedSet instance has to be sorted every time an entry is added or changed, it becomes a performance bottleneck where changes are very frequent. In such cases, SortedSet is not preferred. As SortedSet maintains unique records only, we cannot use this collection where duplicate entries can occur in the data set. Print Page Previous
Category: Java
Java – Functional Interfaces
Java – Functional Interfaces ”; Previous Next Functional interfaces were introduced in Java 8 along with lambda expression and method references. These three features were added to boost functional programming in Java and to write clean, readable code. Before Java 8, a lot of boilerplate code had to be written to cover basic functionality. For example, in order to call a function, first we had to create a class with the required method, create a class instance, and the instance, needed to invoke the method or another way was to use an anonymous class with the corresponding method. With lambda expression, we can avoid the need for both concrete as well as anonymous class objects. A functional interface assists one step ahead, as a lambda expression can implement the functional interface easily as only one method is to be implemented. Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method compareTo() is used for comparison purposes. But it can have any number of default and static methods. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package. @FunctionalInterface Annotation By functionality, any interface having a single abstract method is a functional interface. Java provides a @FunctionalInterface annotation to mark an interface as a functional interface so that the compiler can check if an interface is a functional interface or not. This annotation is optional and is primarily to add a compiler check and to increase the code readability and maintenance. Types of Functional Interfaces in Java There are primarily four types of functional interfaces in Java. Predicate Functional Interface A predicate functional interface is the one whose method accepts one argument and will return either true or false. A predicate functional interface is mainly used in comparison to sort elements or to filter a value based on certain condition(s) applied on the input passed. Java provides predicate functional interfaces for primitives as well as IntPredicate, DoublePredicate, and LongPredicate, which accept only Integer, Double, and Long respectively. Usage Predicate predicate = (value) -> value != 0; // or Predicate predicate = (value) -> test(value); In above snippet predicate function is to return either true/false based on the value passed. Example In this example, we’re using a predicate functional interface to filter odd numbers from a list of integers with the help of a lambda expression. package com.tutorialspoint; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class Tester { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8); Predicate<Integer> isEvenNumber = n -> n %2 == 0; numbers = numbers.stream().filter(isEvenNumber).toList(); System.out.println(numbers); } } Let us compile and run the above program, this will produce the following result − [2, 4, 6, 8] Consumer Functional Interface A consumer functional interface is one whose method accepts one argument and will not return anything. A consumer functional interface is mainly used for side-effect operations. For example, to print an element, to add a salutation, etc. There are other variants of Consumer as well like BiConsumer. A BiConsumer functional interface can accept two parameters. Java provides consumer functional interfaces for primitives as well as IntConsumer, DoubleConsumer, and LongConsumer, which accept only Integer, Double, and Long respectively. Usage Consumer consumer = (value) -> System.out.println(value); // Or Consumer consumer1 = System.out::println; // Or Consumer consumer2 = (value) -> accept(value); Example In this example, we’re using consumer functional interface to print all numbers from a list of integers with the help of a lambda expression and a method reference. package com.tutorialspoint; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class Tester { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8); Consumer<Integer> consumer = (value) -> System.out.println(value); Consumer consumer1 = System.out::println; System.out.println(“Printing using consumer functional interface as lambda expression”); numbers.forEach(consumer); System.out.println(“Printing using consumer functional interface as method reference”); numbers.forEach(consumer1); } } Let us compile and run the above program, this will produce the following result − Printing using consumer functional interface as lambda expression 1 2 3 4 5 6 7 8 Printing using consumer functional interface as method reference 1 2 3 4 5 6 7 8 Supplier Functional Interface The supplier functional interface is the one whose method does not have any arguments to pass and will return a value. A supplier functional interface is mainly used to generate values lazily. For example, to get a random number, to generate a sequence of numbers, etc. Usage Supplier supplier = () -> Math.random() * 10; // or Supplier supplier1 = () -> get(); Example In this example, we’re using supplier functional interface to get a random number with the help of a lambda expression. package com.tutorialspoint; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; public class Tester { public static void main(String args[]) { Supplier<Integer> supplier = () -> (int)(Math.random() * 10); List<Integer> randomNumbers = new ArrayList<>(); // generate 10 random numbers for(int i = 0; i< 10; i++) { randomNumbers.add(supplier.get()); } System.out.println(randomNumbers); } } Let us compile and run the above program, this will produce the following result − [0, 8, 8, 8, 8, 5, 7, 5, 5, 9] Function Functional Interface Function functional interface is one whose method accepts one argument and will return a value. A function functional interface is mainly used to get the processed value. For example, to get the square of an element, to trim string values, etc. There are other variants of Function as well like BiFunction. A BiFunction functional interface can accept two parameters. Java provides function functional interfaces for primitives as well as IntFunction, DoubleFunction, and LongFunction, which accept only Integer, Double, and Long respectively. There are two more utility interfaces, UnaryOperator which extend the Function interface, and BinaryOperator which extends the BiFunction interface. Usage Function function = (value) -> Math.random() * 10; // or Function function1 = (value) -> apply(value); Example In this example, we’re using function functional interface to get a list of squares of numbers with the help of a
Java – Map Interface
Java – Map Interface ”; Previous Next Map Interface The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Several methods throw a NoSuchElementException when no items exist in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map. An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map. Map Interface Methods Sr.No. Method & Description 1 void clear( ) Removes all key/value pairs from the invoking map. 2 boolean containsKey(Object k) Returns true if the invoking map contains k as a key. Otherwise, returns false. 3 boolean containsValue(Object v) Returns true if the map contains v as a value. Otherwise, returns false. 4 Set entrySet( ) Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map. 5 boolean equals(Object obj) Returns true if obj is a Map and contains the same entries. Otherwise, returns false. 6 Object get(Object k) Returns the value associated with the key k. 7 int hashCode( ) Returns the hash code for the invoking map. 8 boolean isEmpty( ) Returns true if the invoking map is empty. Otherwise, returns false. 9 Set keySet( ) Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map. 10 Object put(Object k, Object v) Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned. 11 void putAll(Map m) Puts all the entries from m into this map. 12 Object remove(Object k) Removes the entry whose key equals k. 13 int size( ) Returns the number of key/value pairs in the map. 14 Collection values( ) Returns a collection containing the values in the map. This method provides a collection-view of the values in the map. Classes that Implement Map The following are the classes that implement a Map to use the functionalities of a Map – HashMap EnumMap LinkedHashMap WeakHashMap TreeMap Interfaces that Extend Map The following are the interfaces that extend the Map interface – SortedMap NavigableMap ConcurrentMap Examples of Map Interface Example 1 Map has its implementation in various classes like HashMap. Following is an example to explain map functionality − import java.util.HashMap; import java.util.Map; public class CollectionsDemo { public static void main(String[] args) { Map<String, String> m1 = new HashMap<>(); m1.put(“Zara”, “8”); m1.put(“Mahnaz”, “31”); m1.put(“Ayan”, “12”); m1.put(“Daisy”, “14”); System.out.println(); System.out.println(” Map Elements”); System.out.print(“t” + m1); } } Output Map Elements {Daisy = 14, Ayan = 12, Zara = 8, Mahnaz = 31} Example 2 Map has its implementation in various classes like TreeMap which sorts the entries based on keys. Following is an example to explain map functionality using TreeMap − import java.util.Map; import java.util.TreeMap; public class CollectionsDemo { public static void main(String[] args) { Map<String, String> m1 = new TreeMap<>(); m1.put(“Zara”, “8”); m1.put(“Mahnaz”, “31”); m1.put(“Ayan”, “12”); m1.put(“Daisy”, “14”); System.out.println(); System.out.println(” Map Elements”); System.out.print(“t” + m1); } } Output Map Elements {Ayan=12, Daisy=14, Mahnaz=31, Zara=8} Example 3 Map has its implementation in various classes like HashMap. Following is an example to explain map functions using HashMap to add and remove elements to the map− import java.util.HashMap; import java.util.Map; public class CollectionsDemo { public static void main(String[] args) { Map<String, String> m1 = new HashMap<>(); m1.put(“Zara”, “8”); m1.put(“Mahnaz”, “31”); m1.put(“Ayan”, “12”); m1.put(“Daisy”, “14”); System.out.println(); System.out.println(” Map Elements”); System.out.print(“t” + m1); m1.remove(“Daisy”); System.out.println(” Map Elements”); System.out.print(“t” + m1); } } Output Map Elements {Daisy=14, Ayan=12, Zara=8, Mahnaz=31} Map Elements {Ayan=12, Zara=8, Mahnaz=31} java_collections.htm Print Page Previous Next Advertisements ”;
Java – Set Interface
Java – Set Interface ”; Previous Next A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Set Interface Methods The methods declared by Set are summarized in the following table − Sr.No. Method & Description 1 add( ) Adds an object to the collection. 2 clear( ) Removes all objects from the collection. 3 contains( ) Returns true if a specified object is an element within the collection. 4 isEmpty( ) Returns true if the collection has no elements. 5 iterator( ) Returns an Iterator object for the collection, which may be used to retrieve an object. 6 remove( ) Removes a specified object from the collection. 7 size( ) Returns the number of elements in the collection. Set Interface Examples Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Below are some of the implementations of the Set interface in Java. Example to Implement Set Using HashSet Following is an example to explain Set functionality using HashSet − import java.util.HashSet; import java.util.Set; public class SetDemo { public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); } catch(Exception e) {} } } Output [34, 22, 10, 60, 30] Example to Implement Set Using TreeSet Following is an example to explain Set functionality using TreeSet − import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class SetDemo { public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); TreeSet<Integer> sortedSet = new TreeSet<>(set); System.out.println(“The sorted list is:”); System.out.println(sortedSet); System.out.println(“The First element of the set is: “+ (Integer)sortedSet.first()); System.out.println(“The last element of the set is: “+ (Integer)sortedSet.last()); } catch(Exception e) {} } } Output [34, 22, 10, 60, 30] The sorted list is: [10, 22, 30, 34, 60] The First element of the set is: 10 The last element of the set is: 60 Example to Implement Set Using LinkedHashSet Following is an example to explain Set functionality using LinkedHashSet opearations − import java.util.LinkedHashSet; import java.util.Set; public class SetDemo { public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new LinkedHashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); } catch(Exception e) {} } } Output [34, 22, 10, 60, 30] java_collections.htm Print Page Previous Next Advertisements ”;
Java – Private Interface Methods ”; Previous Next Private and static private interface methods were introduced in Java 9. Being a private method, such a method cannot be accessed via implementing class or sub-interface. These methods were introduced to allow encapsulation where the implementation of certain methods will be kept in the interface only. It helps to reduce duplicity, increase maintainability, and to write clean code. Interface Prior to Java 8 Prior to Java 8, interface can have only abstract method and constant variables. So implementing class has to implement the same. See the below example. Example package com.tutorialspoint; interface util { public int sum(int a, int b); } public class Tester implements util { public static void main(String[] args) { Tester tester = new Tester(); System.out.println(tester.sum(2, 3)); } @Override public int sum(int a, int b) { return a + b; } } Output Let us compile and run the above program, this will produce the following result − 5 In the above example, we can see that implementing class has to implement the method as it is implement the interface. Default Method in Interface from Java 8 With Java 8, default methods were introduced where we can provide the default implementation of the method and implementing class is not needed to implement the same. This feature was introduced to facilitate lambda expression where existing collection framework can work with newly introduced functional interfaces without implementing all the methods of the interfaces. This helped in avoiding re-writing of collection framework. See the below example: Example package com.tutorialspoint; interface util { public default int sum(int a, int b) { return a + b; } } public class Tester implements util { public static void main(String[] args) { Tester tester = new Tester(); System.out.println(tester.sum(2, 3)); } } Output Let us compile and run the above program, this will produce the following result − 5 Private Method in Interface from Java 9 From java 9, interfaces are enhanced further to have private methods. Now Java 9 onwards, we can have private as well as private static methods in interface. This helps in encapsulating the functionality and helps to keep integrity of the method. As private method cannot be inherited, they can be used in public methods of the interface as shown below example: Example package com.tutorialspoint; interface util { public default int operate(int a, int b) { return sum(a, b); } private int sum(int a, int b) { return a + b; } } public class Tester implements util { public static void main(String[] args) { Tester tester = new Tester(); System.out.println(tester.operate(2, 3)); } } Output Let us compile and run the above program, this will produce the following result − 5 Private Static Method in Interface from Java 9 Similarly, we can have private static method which can be called from static and non-static methods. See the example below: Example package com.tutorialspoint; interface util { public default int operate(int a, int b) { return sum(a, b); } private static int sum(int a, int b) { return a + b; } } public class Tester implements util { public static void main(String[] args) { Tester tester = new Tester(); System.out.println(tester.operate(2, 3)); } } Output Let us compile and run the above program, this will produce the following result − 5 A private static method cannot call non-static method in an interface and it is not accessible outside the interface. Even implementing class cannot access the private static method. Print Page Previous Next Advertisements ”;
Java – How to Use Comparable? ”; Previous Next Java Comparable Interface Comparable interface is a very important interface which can be used by Java Collections to compare custom objects and sort them. Using comparable interface, we can sort our custom objects in the same way how wrapper classes, string objects get sorted using Collections sorting methods. Using comparable, we can make the elements as sortable. Comparable Interface Methods The Comparable interface defines a methods: compareTo(). The compareTo() method, shown here, compares the passed object for order − The compare() Method int compareTo(Object obj) obj is the object to be compared. This method returns zero if the objects are equal. It returns a positive value if current object is greater than obj. Otherwise, a negative value is returned. By overriding compareTo(), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can implement a comparison method that reverses the outcome of a comparison. The equals() Method The equals() method, shown here, tests whether an object equals the invoking comparator − boolean equals(Object obj) obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals() is unnecessary, and most simple comparators will not do so. Comparable Interface to Sort Custom Object In this example, we”re using Comparable interface to sort a custom object Dog based on comparison criterias. Example import java.util.ArrayList; import java.util.Collections; import java.util.List; class Dog implements Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { // compare the name using alphabetical order return (this.name).compareTo(d.name); } @Override public String toString() { return this.name + “,” + this.age; } } public class ComparableDemo { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<>(); list.add(new Dog(“Shaggy”, 3)); list.add(new Dog(“Lacy”, 2)); list.add(new Dog(“Roger”, 10)); list.add(new Dog(“Tommy”, 4)); list.add(new Dog(“Tammy”, 1)); Collections.sort(list); // Sorts the array list System.out.println(“Sorted by name:”); // printing the sorted list of names System.out.print(list); } } Output This will produce the following result − Sorted by name: [Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4] Note − Sorting of the Arrays class is as the same as the Collections. Comparable Interface to Sort Custom Object in Reverse Order Example In this example, we”re using Collections.reverseOrder() method to reverse sort the Dog objects. import java.util.ArrayList; import java.util.Collections; import java.util.List; class Dog implements Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return (this.name).compareTo(d.name); } @Override public String toString() { return this.name + “,” + this.age; } } public class ComparableDemo { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<>(); list.add(new Dog(“Shaggy”, 3)); list.add(new Dog(“Lacy”, 2)); list.add(new Dog(“Roger”, 10)); list.add(new Dog(“Tommy”, 4)); list.add(new Dog(“Tammy”, 1)); Collections.sort(list, Collections.reverseOrder()); // Sorts the array list System.out.println(“Sorted by name in reverse order:”); // printing the sorted list of names System.out.print(list); } } Output This will produce the following result − Sorted by name in reverse order: [Tommy,4, Tammy,1, Shaggy,3, Roger,10, Lacy,2] Example In this example, we”re using Comparable interface to sort Dog objects based on their ages. import java.util.ArrayList; import java.util.Collections; import java.util.List; class Dog implements Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return this.age – d.age; } @Override public String toString() { return this.name + “,” + this.age; } } public class ComparableDemo { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<>(); list.add(new Dog(“Shaggy”, 3)); list.add(new Dog(“Lacy”, 2)); list.add(new Dog(“Roger”, 10)); list.add(new Dog(“Tommy”, 4)); list.add(new Dog(“Tammy”, 1)); Collections.sort(list); // Sorts the array list System.out.println(“Sorted by age:”); // printing the sorted list by age System.out.print(list); } } Output This will produce the following result − Sorted by age: [Tammy,1, Lacy,2, Shaggy,3, Tommy,4, Roger,10] Print Page Previous Next Advertisements ”;
Java – REPL (JShell)
Java – REPL (JShell) ”; Previous Next Introduction to REPL (JShell) REPL stands for Read Evaluate Print Loop. JShell was introduced in Java 9 which is an interactive console. JShell as REPL allows to run arbitrary snippet of java code in console without need to save and compile java code file. This facility is very important to test codes quickly like evaluating regular expression, checking formating of strings, date formats etc. JShell reads each line entered, evaluates it and then print the result and then again becomes ready for next set of input. Advantages of Using JShell This capability of JShell gives developers following advantages – No editor is needed to write a Java program. JShell itself works as editor and executes the Java code. Using JShell, there is no requirement to save a Java file, compile and execute code cycle. Code can be directly tested in JShell without saving anything. Compilation is not needed prior to execution of code. If any compile-time or runtime error occurs, start fresh. Running JShell Open command prompt and type jshell. D:test>jshell | Welcome to JShell — Version 20.0.2 | For an introduction type: /help intro With JShell, we can test methods, classes, expressions as well. In following examples, let”s explore some of the features of JShell. Create and Invoke Method in JShell Following snippet showing a sample “Hello World” program in JShell. Here, we”ve created a method greet() which has a single statement to print a message as “Hello World!”. As next, we”ve invoked the method greet() and result is printed on the console. Hello World Example in JShell jshell> void greet() { System.out.println(“Hello World!”);} | created method greet() jshell> greet() Hello World! jshell> Creating Variables in JShell 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 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> long l l ==> 0 jshell> List list list ==> null jshell> name name ==> “Mahesh” Evaluate Expression in JShell Following snippet shows how to evaluate an expression using JShell. Here we”ve passed a statement which returns a formatted string. JShell automatically created a String variable $9 and assigned it the result. As next statement, we”ve printed. Example jshell> String.format(“%d pages read.”, 10); $9 ==> “10 pages read.” jshell> $9 $9 ==> “10 pages read.” Jshell Built-In Commands JShell provides various commands to list the variables created, methods created, imports used etc. Some of the important JShell commands are – /drop – This command drops code snippets identified by name, ID, or ID range. /edit – This command opens an editor. /env – This command displays the environment settings. /exit – This command exists from the tool. /history – This command displays the history of the tool. /help – This command displays the command”s help. /imports – This command displays the current active imports. Example: Demonstrating /help Command We can view all commands using /help option. jshell> /help | Type a Java language expression, statement, or declaration. | Or type one of the following commands: | /list [<name or id>|-all|-start] | list the source you have typed | /edit <name or id> | edit a source entry | /drop <name or id> | delete a source entry | /save [-all|-history|-start] <file> | Save snippet source to a file | /open <file> | open a file as source input | /vars [<name or id>|-all|-start] | list the declared variables and their values | /methods [<name or id>|-all|-start] | list the declared methods and their signatures | /types [<name or id>|-all|-start] | list the type declarations … Example: Demonstrating /vars Command In following example, we”ve used /vars command to print the variables declared during a session. C:UsersMahesh>jshell | Welcome to JShell — Version 20.0.2 | For an introduction type: /help intro jshell> int i = 10 i ==> 10 jshell> String name=”Mahesh” name ==> “Mahesh” jshell> /vars | int i = 10 | String name = “Mahesh” jshell> Example: Demonstrating /imports Command We can use /imports command to check the imports available in JShell as shown below: jshell> /imports | import java.io.* | import java.math.* | import java.net.* | import java.nio.file.* | import java.util.* | import java.util.concurrent.* | import java.util.function.* | import java.util.prefs.* | import java.util.regex.* | import java.util.stream.* jshell> Exiting JShell We can use /exit command to exit JShell as shown below: Example jshell> /exit | Goodbye C:UsersMahesh> Print Page Previous Next Advertisements ”;
Java – URLConnection Class
Java – URLConnection Class ”; Previous Next Java URLConnection Class java.net.URLConnection, is an abstract class whose subclasses represent the various types of URL connections. Instances of this class can be used both to read from and to write to the resource referenced by the URL. For example − If you connect to a URL whose protocol is HTTP, the URL.openConnection() method returns an HttpURLConnection object. If you connect to a URL that represents a JAR file, the URL.openConnection() method returns a JarURLConnection object, etc. Steps to make a connection to a URL Following are the steps to make a connectiion to the URL and start processing. Invoke URL.openConnection() method to get connection object. Update setup parameters and general request properties as required using connection object various setter methods. Create a connection to remote object using connect() method of connection object. Once remote object is available, access the content/headers of the remote object. URLConnection Class Declaration public abstract class URLConnection extends Object URLConnection Class Fields Sr.No. Field & Description 1 protected boolean allowUserInteraction If true, this URL is being examined in a context in which it makes sense to allow user interactions such as popping up an authentication dialog. 2 protected boolean connected If false, this connection object has not created a communications link to the specified URL. 3 protected boolean doInput This variable is set by the setDoInput method. 3 protected boolean doOutput This variable is set by the setDoOutput method. 4 protected long ifModifiedSince Some protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time. 5 protected URL url The URL represents the remote object on the World Wide Web to which this connection is opened. 6 protected boolean useCaches If true, the protocol is allowed to use caching whenever it can. URLConnection Class Methods The URLConnection class has many methods for setting or determining information about the connection, including the following − Sr.No. Method & Description 1 void addRequestProperty(String key, String value) Adds a general request property specified by a key-value pair. 2 boolean getAllowUserInteraction() Returns the value of the allowUserInteraction field for this object. 3 int getConnectTimeout() Returns setting for connect timeout. 4 Object getContent() Retrieves the contents of this URL connection. 5 Object getContent(Class[] classes) Retrieves the contents of this URL connection. 6 String getContentEncoding() Returns the value of the content-encoding header field. 7 int getContentLength() Returns the value of the content-length header field. 8 long getContentLengthLong() Returns the value of the content-length header field as long. 9 String getContentType() Returns the value of the content-type header field. 10 long getDate() Returns the value of the date header field. 11 static boolean getDefaultAllowUserInteraction() Returns the default value of the allowUserInteraction field. 12 boolean getDefaultUseCaches() Returns the default value of a URLConnection”s useCaches flag. 13 static boolean getDefaultUseCaches(String protocol) Returns the default value of the useCaches flag for the given protocol. 14 boolean getDoInput() Returns the value of this URLConnection”s doInput flag. 15 boolean getDoOutput() Returns the value of this URLConnection”s doOutput flag. 16 long getExpiration() Returns the value of the expires header field. 17 static FileNameMap getFileNameMap() Loads filename map (a mimetable) from a data file. 18 String getHeaderField(int n) Returns the value for the nth header field. 19 String getHeaderField(String name) Returns the value of the named header field. 20 long getHeaderFieldDate(String name, long Default) Returns the value of the named field parsed as date. 21 int getHeaderFieldInt(String name, int Default) Returns the value of the named field parsed as a number. 22 String getHeaderFieldKey(int n) Returns the key for the nth header field. 23 long getHeaderFieldLong(String name, long Default) Returns the value of the named field parsed as a number. 24 Map<String,List<String>> getHeaderFields() Returns an unmodifiable Map of the header fields. 25 long getIfModifiedSince() Returns the value of this object”s ifModifiedSince field. 26 InputStream getInputStream() Returns an input stream that reads from this open connection. 27 int getLastModified() Returns the value of the last-modified header field. 28 OutputStream getOutputStream() Returns an output stream that writes to this connection. 29 Permission getPermission() Returns a permission object representing the permission necessary to make the connection represented by this object. 30 int getReadTimeout() Returns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout of infinity). 31 Map<String,List<String>> getRequestProperties() Returns an unmodifiable Map of general request properties for this connection. 32 String getRequestProperty(String key) Returns the value of the named general request property for this connection. 33 URL getURL() Returns the value of this URLConnection”s URL field. 34 boolean getUseCaches() Returns the value of this URLConnection”s useCaches field. 35 static String guessContentTypeFromName(String fname) Tries to determine the content type of an object, based on the specified “file” component of a URL. 36 static String guessContentTypeFromStream(InputStream is) Tries to determine the type of an input stream based on the characters at the beginning of the input stream. 37 void setAllowUserInteraction(boolean allowuserinteraction) Set the value of the allowUserInteraction field of this URLConnection. 38 void setConnectTimeout(int timeout) Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. 39 static void setContentHandlerFactory(ContentHandlerFactory fac) Sets the ContentHandlerFactory of an application. 40 static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value. 41 void setDefaultUseCaches(boolean defaultusecaches) Sets the default value of the useCaches field to the specified value. 42 static void setDefaultUseCaches(String protocol, boolean defaultVal) Sets the default value of the useCaches field for the named protocol to the given value. 43 void setDoInput(boolean doinput) Sets the value of the doInput field for this URLConnection to the specified value. 44 void setDoOutput(boolean dooutput) Sets the value of the doOutput field for this URLConnection to the specified value. 45 static void setFileNameMap(FileNameMap map) Sets the FileNameMap. 46 void setIfModifiedSince(long ifmodifiedsince) Sets the value of the ifModifiedSince field of this URLConnection to the specified value. 47 void setReadTimeout(int timeout) Sets the read timeout to
Java – Starting a Thread
Java – Starting a Thread ”; Previous Next Starting a Thread Once a Thread object is created, you can start it by calling start() method, which executes a call to run() method. Following is a simple syntax of start() method − void start(); Syntax of Starting a Thread The following is the syntax of starting a thread – thread_obj.start(); Here, thread_obj is an object to the Thread class, and start() is the method of the Thread class. Start a Thread by Implementing Runnable Interface In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. Example package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Start a Thread by Extending Thread Class Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. Example package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Start a Thread (with Demonstrating sleep() method) In this example, we”re creating couple of objects of ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. Using sleep() method, we”re introducing the delay in processing. Example package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Dead Print Page Previous Next Advertisements ”;
Java – Queue Interface
Java – Queue Interface ”; Previous Next Queue Interface The Queue interface is provided in java.util package and it implements the Collection interface. The queue implements FIFO i.e. First In First Out. This means that the elements entered first are the ones that are deleted first. A queue is generally used to hold elements before processing them. Once an element is processed then it is removed from the queue and next item is picked for processing. Queue Interface Declaration public interface Queue<E> extends Collection<E> Queue Interface Methods Following is the list of the important queue methods that all the implementation classes of the Queue interface implement − Sr.No. Method & Description 1 boolean add(E e) This method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available. 2 E element() This method retrieves, but does not remove, the head of this queue. 3 boolean offer(E e) This method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. 4 E peek() This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. 5 E poll() This method retrieves and removes the head of this queue, or returns null if this queue is empty. 6 E remove() This method retrieves and removes the head of this queue. Methods Inherited This interface inherits methods from the following interfaces − java.util.Collection java.lang.Iterable Classes that Implement Queue The following are the classes that implement a Queue to use the functionalities of a Queue – LinkedList ArrayDeque PriorityQueue Interfaces that Extend Queue The following are the interfaces that extend the Queue interface – Deque BlockingQueue BlockingDeque Example of Queue Interface In this example, we”re using a LinkedList instance to show queue add, peek and size operations. package com.tutorialspoint; import java.util.LinkedList; import java.util.Queue; public class QueueDemo { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); q.add(6); q.add(1); q.add(8); q.add(4); q.add(7); System.out.println(“The queue is: ” + q); int num1 = q.remove(); System.out.println(“The element deleted from the head is: ” + num1); System.out.println(“The queue after deletion is: ” + q); int head = q.peek(); System.out.println(“The head of the queue is: ” + head); int size = q.size(); System.out.println(“The size of the queue is: ” + size); } } Output The queue is: [6, 1, 8, 4, 7] The element deleted from the head is: 6 The queue after deletion is: [1, 8, 4, 7] The head of the queue is: 1 The size of the queue is: 4 Print Page Previous Next Advertisements ”;