Java – Characters

Java – Character Class ”; Previous Next Normally, when we work with characters, we use primitive data types char. Example char ch = ”a”; // Unicode for uppercase Greek omega character char uniChar = ”u039A”; // an array of chars char[] charArray ={ ”a”, ”b”, ”c”, ”d”, ”e” }; Use of Character Class in Java However in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class Character for primitive data type char. Java Character Class The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor − Character ch = new Character(”a”); The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way. Example of Java Character Class // Here following primitive char ”a” // is boxed into the Character object ch Character ch = ”a”; // Here primitive ”x” is boxed for method test, // return is unboxed to char ”c” char c = test(”x”); Escape Sequences A character preceded by a backslash () is an escape sequence and has a special meaning to the compiler. The newline character (n) has been used frequently in this tutorial in System.out.println() statements to advance to the next line after the string is printed. Following table shows the Java escape sequences − Escape Sequence Description t Inserts a tab in the text at this point. b Inserts a backspace in the text at this point. n Inserts a newline in the text at this point. r Inserts a carriage return in the text at this point. f Inserts a form feed in the text at this point. ” Inserts a single quote character in the text at this point. “ Inserts a double quote character in the text at this point. \ Inserts a backslash character in the text at this point. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. Example: Escape Sequences If you want to put quotes within quotes, you must use the escape sequence, “, on the interior quotes − public class Test { public static void main(String args[]) { System.out.println(“She said “Hello!” to me.”); } } Output She said “Hello!” to me. Character Class Declaration Following is the declaration for java.lang.Character class − public final class Character extends Object implements Serializable, Comparable<Character> Field Following are the fields for java.lang.Character class − static byte COMBINING_SPACING_MARK − This is the General category “Mc” in the Unicode specification. static byte CONNECTOR_PUNCTUATION − This is the General category “Pc” in the Unicode specification. static byte CONTROL − This is the General category “Cc” in the Unicode specification. static byte CURRENCY_SYMBOL − This is the General category “Sc” in the Unicode specification. static byte DASH_PUNCTUATION − This is the General category “Pd” in the Unicode specification. static byte DECIMAL_DIGIT_NUMBER − This is the General category “Nd” in the Unicode specification. static byte DIRECTIONALITY_ARABIC_NUMBER − This is the Weak bidirectional character type “AN” in the Unicode specification. static byte DIRECTIONALITY_BOUNDARY_NEUTRAL − This is the Weak bidirectional character type “BN” in the Unicode specification. static byte DIRECTIONALITY_COMMON_NUMBER_SEPARATOR − This is the Weak bidirectional character type “CS” in the Unicode specification. static byte DIRECTIONALITY_EUROPEAN_NUMBER − This is the Weak bidirectional character type “EN” in the Unicode specification. static byte DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR − This is the Weak bidirectional character type “ES” in the Unicode specification. static byte DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR − This is the Weak bidirectional character type “ET” in the Unicode specification. static byte DIRECTIONALITY_LEFT_TO_RIGHT − This is the Strong bidirectional character type “L” in the Unicode specification. static byte DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING − This is the Strong bidirectional character type “LRE” in the Unicode specification. static byte DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE − This is the Strong bidirectional character type “LRO” in the Unicode specification. static byte DIRECTIONALITY_NONSPACING_MARK − This is the Weak bidirectional character type “NSM” in the Unicode specification. static byte DIRECTIONALITY_OTHER_NEUTRALS − This is the Neutral bidirectional character type “ON” in the Unicode specification. static byte DIRECTIONALITY_PARAGRAPH_SEPARATOR − This is the Neutral bidirectional character type “B” in the Unicode specification. static byte DIRECTIONALITY_POP_DIRECTIONAL_FORMAT − This is the Weak bidirectional character type “PDF” in the Unicode specification. static byte DIRECTIONALITY_RIGHT_TO_LEFT − This is the Strong bidirectional character type “R” in the Unicode specification. static byte DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC − This is the Strong bidirectional character type “AL” in the Unicode specification. static byte DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING − This is the Strong bidirectional character type “RLE” in the Unicode specification. static byte DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE − This is the Strong bidirectional character type “RLO” in the Unicode specification. static byte DIRECTIONALITY_SEGMENT_SEPARATOR − This is the Neutral bidirectional character type “S” in the Unicode specification. static byte DIRECTIONALITY_UNDEFINED − This is the Undefined bidirectional character type. static byte DIRECTIONALITY_WHITESPACE − This is the Neutral bidirectional character type “WS” in the Unicode specification. static byte ENCLOSING_MARK − This is the General category “Me” in the Unicode specification. static byte END_PUNCTUATION − This is the General category “Pe” in the Unicode specification. static byte FINAL_QUOTE_PUNCTUATION − This

Java – Lambda Expressions

Java – Lambda Expressions ”; Previous Next Java Lambda Expressions Lambda expressions were introduced in Java 8 and were touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies development a lot. A lambda expression works on the principle of functional interface. A Functional interface is an interface with only one method to implement. A lambda expression provides an implementation of the functional interface method. Lambda expression simplifies functional programming a lot and makes code readable without any boilerplate code. A lambda expression can infer the type of parameter used and can return a value without a return keyword. In the case of the simple one-statement method, even curly braces can be eliminated. Lambda Expression Syntax A lambda expression is characterized by the following syntax. parameter -> expression body Characteristics of Java Lambda Expression Following are the important characteristics of a lambda expression. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter. Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required. Optional curly braces − No need to use curly braces in expression body if the body contains a single statement. Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value. Java Lambda Expression Example In this example, we”ve one functional interface MathOperation with a method operate which can accept two int parameters, perform the operation and return the result as int. Using lambda expression, we”ve created four different implementations of MathOperation operate method to add,subtract,multiply and divide two integers and get the relative result. Then we”ve another functional interface GreetingService with a method sayMessage, which we”ve used to print a message to the console. package com.tutorialspoint; public class JavaTester { public static void main(String args[]) { JavaTester tester = new JavaTester(); //with type declaration MathOperation addition = (int a, int b) -> a + b; //with out type declaration MathOperation subtraction = (a, b) -> a – b; //with return statement along with curly braces MathOperation multiplication = (int a, int b) -> { return a * b; }; //without return statement and without curly braces MathOperation division = (int a, int b) -> a / b; System.out.println(“10 + 5 = ” + tester.operate(10, 5, addition)); System.out.println(“10 – 5 = ” + tester.operate(10, 5, subtraction)); System.out.println(“10 x 5 = ” + tester.operate(10, 5, multiplication)); System.out.println(“10 / 5 = ” + tester.operate(10, 5, division)); //without parenthesis GreetingService greetService1 = message -> System.out.println(“Hello ” + message); //with parenthesis GreetingService greetService2 = (message) -> System.out.println(“Hello ” + message); greetService1.sayMessage(“Mahesh”); greetService2.sayMessage(“Suresh”); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } } Output Let us compile and run the above program, this will produce the following result − 10 + 5 = 15 10 – 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh Following are the important points to be considered in the above example. Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we”ve used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService. Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java. Scope of Java Lambda Expression Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time. Using Constant in Lambda Expression In this example, we”ve one functional interface GreetingService with a method sayMessage, which we”ve used to print a message to the console. Now in Java Tester class, we”ve one final class field salutation having a value “Hello! “. Now in lambda expression, we can use this field being final without any error. Example to Use Constant in Lambda Expression public class JavaTester { final static String salutation = “Hello! “; public static void main(String args[]) { GreetingService greetService1 = message -> System.out.println(salutation + message); greetService1.sayMessage(“Mahesh”); } interface GreetingService { void sayMessage(String message); } } Output Let us compile and run the above program, this will produce the following result − Hello! Mahesh Using Lambda Expression in Collections From Java 8 onwards, almost all collections are enhanced to accept lambda expression to perform operations on them. For example, to iterate a list, filter a list, to sort a list and so on. In this example, we”re showcasing how to iterate a list of string and print all the elements and how to print only even numbers in a list using lambda expressions. Example to Use Lambda Expression in Collections package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class JavaTester { public static void main(String args[]) { // prepare a list of strings List<String> list = new ArrayList<>(); list.add(“java”); list.add(“html”); list.add(“python”); // print the list using a lambda expression // here we”re passing a lambda expression to forEach // method of list object list.forEach(i -> System.out.println(i)); List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); numbers.add(6); numbers.add(7); numbers.add(8); System.out.println(numbers); // filter the list using a lambda expression // here we”re passing a lambda expression to removeIf // method of list object where we can checking // if number is divisible by 2 or not numbers.removeIf( n -> n%2 != 0); System.out.println(numbers); } } Output Let us compile and run the above program, this will produce the following result − java html python [1, 2, 3, 4, 5, 6, 7, 8] [2, 4, 6, 8]

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

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 – 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 – Comparable Interface in Java

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 ”;