Java – Applet Basics

Java – Applet Basics ”; Previous Next An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal. There are some important differences between an applet and a standalone Java application, including the following − An applet is a Java class that extends the java.applet.Applet class. A main() method is not invoked on an applet, and an applet class will not define main(). Applets are designed to be embedded within an HTML page. When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user”s machine. A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment. The JVM on the user”s machine creates an instance of the applet class and invokes various methods during the applet”s lifetime. Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed. Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file. Life Cycle of an Applet in Java Four methods in the Applet class gives you the framework on which you build any serious applet − init − This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed. start − This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. stop − This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet. destroy − This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet. paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt. Flow of Java Applet Life Cycle Applet life cycle methods are called automatically. The following diagram shows the flow of an applet life cycle. A Simple Java Applet “Hello, World” Following is a simple applet named HelloWorldApplet.java − import java.applet.*; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint (Graphics g) { g.drawString (“Hello World”, 25, 50); } } These import statements bring the classes into the scope of our applet class − java.applet.Applet java.awt.Graphics Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to. The Applet Class Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context. These include methods that do the following − Get applet parameters Get the network location of the HTML file that contains the applet Get the network location of the applet class directory Print a status message in the browser Fetch an image Fetch an audio clip Play an audio clip Resize the applet Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet”s execution. The viewer may − Request information about the author, version, and copyright of the applet Request a description of the parameters the applet recognizes Initialize the applet Destroy the applet Start the applet”s execution Stop the applet”s execution The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary. The “Hello, World” applet is complete as it stands. The only method overridden is the paint method. Invoking an Applet An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser. The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes the “Hello, World” applet − <html> <title>The Hello, World Applet</title> <hr> <applet code = “HelloWorldApplet.class” width = “320” height = “120”> If your browser was Java-enabled, a “Hello, World” message would appear here. </applet> <hr> </html> Note − You can refer to HTML Applet Tag to understand more about calling applet from HTML. The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with an </applet> tag. If an applet takes parameters, values may be passed for the parameters by adding <param> tags between <applet> and </applet>. The browser ignores text and other tags between the applet tags. Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears between the tags, not related to the applet, is visible in non-Java-enabled browsers. The viewer or browser looks for the compiled Java code at the location of the document. To specify otherwise, use the codebase attribute of the <applet> tag as shown − <applet codebase = “https://amrood.com/applets” code = “HelloWorldApplet.class” width = “320” height = “120”> If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period character (.) to separate package/class components. For example − <applet = “mypackage.subpackage.TestApplet.class” width = “320” height = “120”> Getting Applet Parameters The following example demonstrates how to make an applet respond to setup parameters specified in the document. This applet displays a checkerboard pattern

Java – Collection Factory Methods

Java – Collection Factory Methods ”; Previous Next Factory Methods for Collection In Java 9, collections were enhanced to have few new methods to create immutable list in an easy and concise way. These new factory methods were added to List, Set, and Map interfaces to create immutable instances. These factory methods are mainly convenience factory methods in order to create a collection in less verbose and in concise way. Syntax Before Java 9, following syntax was used to create a immutable list. List unmodifiableList = Collections.unmodifiableList(arrayList); Where arrayList is a mutable list instance. So we are required to create a list and then using unmodifiableList() we get an immutable instance from which we cannot add/remove an element. Factory Methods of List Interface Now from Java 9, following methods can be used to create a immutable list. static <E> List<E> of(); static <E> List<E> of(E e1); static <E> List<E> of(E… elements) static <E> List<E> of(E e1, E e2); static <E> List<E> of(E e1, E e2, E e3); static <E> List<E> of(E e1, E e2, E e3, E e4); static <E> List<E> of(E e1, E e2, E e3, E e4, E e5); static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6); static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7); static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8); static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8,E e9); static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8,E e9, E e10); Syntax So from Java 9 onwards, following syntax can be used to create a immutable list. of(E… elements) method can be used to have more than 10 elements in an immutable list. List<String> unmodifiableList = List.of(“A”, “B”, “C”); Example of List Interface Factory Methods Before Java 9 Here, we are creating unmodifiable list before Java 9. package com.tutorialspoint; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Tester { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add(“A”); list.add(“B”); list.add(“C”); list = Collections.unmodifiableList(list); System.out.println(list); } } Let us compile and run the above program, this will produce the following result − [A, B, C] Example of List Interface Factory Methods in Java 9 Here, we are creating unmodifiable list in Java 9. package com.tutorialspoint; import java.util.List; public class Tester { public static void main(String[] args){ List<String> list = List.of(“A”,”B”,”C”); System.out.println(list); } } Let us compile and run the above program, this will produce the following result − [A, B, C] Factory Methods of Set Interface On similar pattern, Set interface is having these new methods to create a unmodifiable Set to get an instance of a set from which we cannot add/remove an element. static <E> Set<E> of(); static <E> Set<E> of(E e1); static <E> Set<E> of(E… elements) static <E> Set<E> of(E e1, E e2); static <E> Set<E> of(E e1, E e2, E e3); static <E> Set<E> of(E e1, E e2, E e3, E e4); static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5); static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6); static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7); static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8); static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8,E e9); static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8,E e9, E e10); Syntax So from Java 9 onwards, following syntax can be used to create a immutable set. of(E… elements) method can be used to have more than 10 elements in an immutable set. Set<String> unmodifiableSet = Set.of(“A”, “B”, “C”); Example of Set Interface Factory Methods Before Java 9 Here, we are creating unmodifiable set before Java 9. package com.tutorialspoint; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Tester { public static void main(String[] args){ Set<String> set = new HashSet<>(); set.add(“A”); set.add(“B”); set.add(“C”); set = Collections.unmodifiableSet(set); System.out.println(set); } } Let us compile and run the above program, this will produce the following result − [A, B, C] Example of Set Interface Factory Methods in Java 9 Here, we are creating unmodifiable set in Java 9. package com.tutorialspoint; import java.util.Set; public class Tester { public static void main(String[] args){ Set<String> set = Set.of(“A”,”B”,”C”); System.out.println(set); } } Let us compile and run the above program, this will produce the following result − [A, B, C] Factory Methods of Map Interface In case of Map interface, we”ve ofEntries(…) can be used to accept var args parameter other than of() methods as shown below. static <K,V> Map<K,V> of(); static <K,V> Map<K,V> of(K k1, V v1); static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>… entries) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8);

Java – Autoboxing and Unboxing

Java – Autoboxing and Unboxing ”; Previous Next Java Autoboxing Autoboxing is a technique used by Java compiler to automatically convert a primitive value to its wrapper counterpart. For example, when an int value is assigned to an Integer wrapper object, compiler automatically converts the int value to the object without any need to explicitly cast the int value or by calling any method to convert int to Integer object. Autoboxing is also known as boxing. // Autoboxing Integer obj = 10; // Explicit casting Integer obj2 = Integer.valueOf(10) In both cases, the wrapper objects are initialized with an int value. In first case, autoboxing is playing role and second case, we”re explicitly casting int value to Integer wrapper object. Compiler uses autoboxing in following scenarios − If a primitive value is passed as an argument to a function which is expecting a wrapper class object. If a primitive value is assigned to a variable of the type of wrapper class. Example of Autoboxing in Java In this example, we”ve created a list of Integer as List can contain only objects. Now while adding the item to this list, we”re not creating any Integer object but we”re just passing the primitive int values. Java compiler automatically handles the conversion and program compiles successfully. We”ve used another case of assigning a char primitive value to Character object which works as well. package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); for(int i = 0; i< 10; i++){ // autoboxing by passing as an argument // int value is converted to Integer // by compiler during compilation list.add(i); } System.out.println(list); char c = ”a”; //autoboxing by assigning a char to Character object Character ch = c; System.out.println(ch); } } Output Let us compile and run the above program without any command line argument, this will produce the following result − [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a Java Unboxing Unboxing is reverse of autoboxing. Unboxing is used by Java compiler to convert a wrapper object to its primitive counterpart. For example when an Integer object is passed to a method as argument but the method called is expecting an int variable, then compiler automatically converts the Integer object to int value and then pass it to the mathod called. Similarly Java compilier unboxes the wrapper value if it is assigned to a primitive variable. Thus we are not required to explicitly get the int value from the wrapper object. Integer obj = Integer.valueOf(10); // Unboxing int i = obj; // Explicit value deduction i = obj.intValue(); In both cases, the primitive values are initialized with an int value. In first case, unboxing is playing role and second case, we”re explicitly getting int value from an Integer wrapper object. Compiler uses unboxing in following scenarios − If a wrapper class object is passed as an argument to a function which is expecting a primitive value. If a wrapper class object is assigned to a variable of primitive type. Example of Unboxing in Java In this example, we”ve created an Integer object and initilized it with a value of 10. This object is passed to abs() method which is expecting an int, a primitive variable. Java compiler automatically handles the conversion and program compiles successfully. We”ve used another case of assigning a Integer object to int variable which works as well. package com.tutorialspoint; public class Tester { public static void main(String[] args) { Integer integer = Integer.valueOf(-10); // unboxing by passing as an argument // Integer object is converted to int // by compiler during compilation int i = abs(integer); System.out.println(i); //unboxing by assigning an Integer object to int variable int j = integer; System.out.println(j); } private static int abs(int i){ return (i < 0)? -i: i; } } Output Let us compile and run the above program without any command line argument, this will produce the following result − 10 -10 Mapping of Primitive and Wrapper Objects Sr. No. Primitive Wrapper method to get value 1 byte Byte byteValue() 2 short Short shortValue() 3 int Integer intValue() 4 long Long longValue() 5 float Float floatValue() 6 double Double doubleValue() 7 char Character charValue() 8 boolean Boolean booleanValue() Print Page Previous Next Advertisements ”;

Java – Command-Line Arguments

Java – Command Line Arguments ”; Previous Next In Java, command line arguments is a way to pass inputs to the java program during application execution. Command line arguments can be passed by multiple ways to Java application or program. Most commonly, command line arguments are passed from console where a java program is executed. command-line arguments, provided during program execution, are captured in the main() method as a string array. Passing & Accessing Command Line Arguments Consider the below syntax of passing command-line arguments: javac tester.java java tester arg1 arg2 arg3 Here we”ve compiled one java file namely tester.java and while running the tester class using java, we”re passing three arguments which are separated by space. We can pass any number of command line arguments to java program. The Java Virtual Machine (JVM) encapsulates these inputs into the args[] array. We can check the number of arguments passed using args.length. In case no command line argument is present, then this array is empty. class Tester { public static void main(String[] args){ … } } We can pass Strings, integers and any other primitive value using command line arguments. Each argument passed is available in the array in the order of entry, starting from args[0]. Benefits of Command Line arguments Command line arguments allows to configure the application behavior by passing the arguments before start of the application. Batch processes are one of the example where command line arguments are heavily used to execute java commands with configuration parameters. This mechanism enables dynamic parameterization of Java programs through console inputs, enhancing versatility and interactivity. Command line arguments facilites user input retrieval and manipulation in case of console based applications Example of Single Command Line Argument In this example, we”re checking if exactly one argument is passed to represent name. In case, no arguments are passed or more than one argument is passed, we print the error message as invalid number of arguments passed. Otherwise, we”re printing the name with a salutation. public class Tester { // args array represents the command line arguments passed public static void main(String[] args) { // if only one argument is passed if(args.length == 1) { String name = args[0]; System.out.println(“Welcome ” + name + “!”); }else { // otherwise print an error message System.out.println(“Invalid Command line argument(s) passed.”); } } } Output Let us compile and run the above program without any command line argument, this will produce the following result − D:test>javac Tester.java D:test>java Tester Invalid Command line argument(s) passed. Here, we”ve compiled the java code using javac command and then run using java command without any command line argument. Let”s run the java command again with required parameter. D:test>java Tester Mahesh Welcome Mahesh! Example of Multiple Command Line Arguments In this example, we”re checking if exactly two arguments are passed to represent name and age. Age being a number, we”re parsing the argument using parseInt() method. In case, no arguments are passed or more than two arguments are passed, we print the error message as invalid number of arguments passed. Otherwise, we”re printing the name and age received. public class Tester { // args array represents the command line arguments passed public static void main(String[] args) { // if two arguments are passed if(args.length == 2) { String name = args[0]; // parse the age as int int age = Integer.parseInt(args[1]); System.out.println(“Name: ” + name + “, age: ” + age); }else { // otherwise print an error message System.out.println(“Invalid Command line argument(s) passed.”); } } } Output Let us compile and run the above program without any command line argument, this will produce the following result − D:test>javac Tester.java D:test>java Tester Invalid Command line argument(s) passed. Here, we”ve compiled the java code using javac command and then run using java command without any command line argument. Let”s run the java command again with required parameters. D:test>java Tester Mahesh 40 Name: Mahesh, age: 40 Conclusion Java command-line arguments are very useful to create parameterized java programs which can accept the parameters dynamically. Users have runtime control over the behavior of the program as arguments can be passed to the main() method. With command line arguments, we can manage program”s output, set setup parameters, and specify input files at runtime without any compile time dependencies. We can pass command-line arguments in many ways to a java program. Various IDEs supports providing the arguments in their execution configurations. Also, they are easy to employ. When you run the code, it can be set in the program”s configuration file or supplied on the command line. Print Page Previous Next Advertisements ”;

Java – SortedSet Interface

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

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 – Sending Email

Java – Sending Email ”; Previous Next To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. You can download latest version of JavaMail (Version 1.2) from Java”s standard website. You can download latest version of JAF (Version 1.1.1) from Java”s standard website. Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH. Send a Simple E-mail Here is an example to send a simple e-mail from your machine. It is assumed that your localhost is connected to the Internet and capable enough to send an e-mail. Example // File Name SendEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail { public static void main(String [] args) { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Now set the actual message message.setText(“This is actual message”); // Send message Transport.send(message); System.out.println(“Sent message successfully….”); } catch (MessagingException mex) { mex.printStackTrace(); } } } Output Compile and run this program to send a simple e-mail − $ java SendEmail Sent message successfully…. If you want to send an e-mail to multiple recipients then the following methods would be used to specify multiple e-mail IDs − void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException Here is the description of the parameters − type − This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example: Message.RecipientType.TO addresses − This is an array of e-mail ID. You would need to use InternetAddress() method while specifying email IDs. Send an HTML E-mail Here is an example to send an HTML e-mail from your machine. Here it is assumed that your localhost is connected to the Internet and capable enough to send an e-mail. This example is very similar to the previous one, except here we are using setContent() method to set content whose second argument is “text/html” to specify that the HTML content is included in the message. Using this example, you can send as big as HTML content you like. Example // File Name SendHTMLEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendHTMLEmail { public static void main(String [] args) { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Send the actual HTML message, as big as you like message.setContent(“<h1>This is actual message</h1>”, “text/html”); // Send message Transport.send(message); System.out.println(“Sent message successfully….”); } catch (MessagingException mex) { mex.printStackTrace(); } } } Compile and run this program to send an HTML e-mail − Output $ java SendHTMLEmail Sent message successfully…. Send Attachment in E-mail Here is an example to send an e-mail with attachment from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an e-mail. Example // File Name SendFileEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendFileEmail { public static void main(String [] args) { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(“This is message body”); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = “file.txt”; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart ); // Send message Transport.send(message); System.out.println(“Sent message successfully….”); } catch (MessagingException mex) { mex.printStackTrace(); } } } Compile and run this program to send an HTML e-mail − Output $ java SendFileEmail Sent message successfully…. User Authentication Part If it is required to provide user ID and Password to the e-mail server for authentication purpose, then you can set these properties as follows − props.setProperty(“mail.user”, “myuser”); props.setProperty(“mail.password”, “mypwd”); Rest of the e-mail sending mechanism would remain as explained above. Print Page Previous Next Advertisements ”;

Java – Method References

Java – Method References ”; Previous Next Method references were introduced in java 8. Method reference is a special type of lambda expression. It fulfils the purpose of a lambda expression by increasing the readability and to write a neat code. A method reference works in case of functional interfaces. Wherever, we are calling a method of a functional interface with a lambda expression, we can use method reference. Method references help to point to methods by their names even without specifying the arguments. Arguments are passed by the lambda expression. A method reference is described using “::” symbol. Types of Java Method References A method reference can be used to point the following types of methods − Static methods Instance methods Constructors using new operator (TreeSet::new) Method Reference for Static Method A static method can be referred using “::” symbol easily without creating any instance of the class, and by using class name. Syntax <<class-name>>::methodName Example: Reference to a Static Method In this example, we’re referencing static method of out class to print the elements in three ways. First approach is regular approach to print the elements using for loop. Second approach is to use a lambda expression in for each loop. Third approach is using method reference in for each loop to print all the elements. package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String args[]) { List<String> names = new ArrayList<>(); names.add(“Mahesh”); names.add(“Suresh”); names.add(“Ramesh”); names.add(“Naresh”); names.add(“Kalpesh”); System.out.println(“Printing using for each loop”); // Approach 1: for loop to print all elements for (String name: names) { System.out.println(name); } System.out.println(“Printing using for each loop with lambda expression”); // Approach 2: lambda expression to print the elements in for each loop names.forEach(s->System.out.println(s)); System.out.println(“Printing using for each loop with method reference” ); // Approach 3: Method reference to print elements in for each loop names.forEach(System.out::println); } } Output Let us compile and run the above program, this will produce the following result − Printing using for each loop Mahesh Suresh Ramesh Naresh Kalpesh Printing using for each loop with lambda expression Mahesh Suresh Ramesh Naresh Kalpesh Printing using for each loop with method reference Mahesh Suresh Ramesh Naresh Kalpesh Method Reference for Instance Method Similar to static methods, we can refer to instance method of an object using Method reference. Syntax <<object-name>>::methodName Example: Reference to an Instance Method In this example, we’re referencing instance method of Integer class to compare the elements in two ways. First approach is regular approach to compare the elements using sorted method with a lambda expression having explicit method call. Second approach is using method reference. package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class Tester { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1,2,4,9,8,7,3); System.out.println(“Sorted using lambda expression”); numbers = numbers.stream().sorted((a,b) -> a.compareTo(b)).toList(); System.out.println(numbers); numbers = Arrays.asList(1,2,4,9,8,7,3); System.out.println(“Sorted using method reference” ); numbers = numbers.stream().sorted(Integer::compareTo).toList(); System.out.println(numbers); } } Output Let us compile and run the above program, this will produce the following result − Sorted using lambda expression [1, 2, 3, 4, 7, 8, 9] Sorted using method reference [1, 2, 3, 4, 7, 8, 9] Method Reference for Constructor We can use method reference to invoke constructor as well. This is similar to static method invocation but here we”re using new instead of method name. Syntax <<class-name>>::new Example: Reference to a Constructor In this example, we’re creating new objects of Student class based on names of the students while iterating the list of student names. package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class Tester { public static void main(String args[]) { List<String> studentNames = Arrays.asList(“Mahesh”,”Suresh”,”Ramesh”,”Robert”,”Jon”); // create the list of student objects from names Student[] students = studentNames.stream().map(Student::new).toArray(Student[]::new); List<String> list = Arrays.asList(students); System.out.println(list); } } class Student{ String name; Student(String name){ this.name = name; } public String toString(){ return this.name; } } Output Let us compile and run the above program, this will produce the following result − [Mahesh, Suresh, Ramesh, Robert, Jon] Print Page Previous Next Advertisements ”;

Java – Socket Programming

Java – Socket Programming ”; Previous Next Socket Programming in Java Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket. The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. Steps of Socket Programming in Java The following steps occur when establishing a TCP connection between two computers using sockets − The server instantiates a ServerSocket object, denoting which port number communication is to occur on. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to. The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client”s socket. After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client”s OutputStream is connected to the server”s InputStream, and the client”s InputStream is connected to the server”s OutputStream. TCP is a two-way communication protocol, hence data can be sent across both streams at the same time. Advantages of Java Socket Programming Platform Independence − One of the biggest advantages of Java Sockets is that they are platform-independent. This means that the same Java code can be run on multiple operating systems and devices without the need for modification. This allows for easy deployment of network-based applications across different systems and ensures that the application can be run on different devices without the need for platform-specific code. Easy to Use − Java Sockets are also relatively easy to use, even for developers who are new to network programming. The Java API provides a simple, consistent interface for creating and managing sockets, which makes it easy to implement network-based applications without needing to understand the underlying network protocols. Scalability − Java Sockets are highly scalable, making them suitable for large-scale network-based applications. They can easily handle thousands of simultaneous connections and can be used to create distributed systems that can handle high levels of traffic. Security − Java Sockets provide built-in support for secure communication, including SSL and TLS encryption. This makes it easy to create secure network-based applications and ensures that sensitive data is protected while in transit. Multithreading − Java Sockets support multithreading, which means that multiple threads can be used to handle multiple connections simultaneously. This improves the performance of network-based applications and allows them to handle a large number of requests without becoming overloaded. Disadvantages of Java Socket Programming Complexity − While Java Sockets are relatively easy to use, they can still be complex to implement, particularly for developers who are new to network programming. This complexity can make it difficult to debug and troubleshoot network-based applications, which can be time-consuming and frustrating. Latency − Java Sockets can introduce latency into network-based applications, particularly when dealing with large amounts of data. This can be a problem for applications that require real-time communication, such as online gaming or video conferencing. Resource Intensive − Java Sockets can be resource-intensive, particularly when dealing with large numbers of connections or large amounts of data. This can be a problem for systems with limited resources, such as mobile devices or embedded systems. Limited Protocol Support − Java Sockets support a limited number of network protocols, which can be a limitation for certain types of network-based applications. This can make it difficult to create applications that need to communicate with other systems using proprietary protocols. Potential for Security Vulnerabilities − Java Sockets, like any network-based application, are vulnerable to security threats, such as hacking and man-in-the-middle attacks. Careful attention must be paid to security when designing and implementing Java Socket-based systems to ensure that sensitive data is protected and potential vulnerabilities are identified and addressed. Socket Programming Applications Chat Applications − Java Sockets are often used to create chat applications, such as instant messaging programs and online chat rooms. These types of applications typically use a client-server architecture, where clients connect to a central server to send and receive messages. File Transfer Applications − Java Sockets can also be used to create file transfer applications, such as peer-to-peer file sharing programs. These types of applications use a peer-to-peer architecture, where each device acts as both a client and a server. This allows for direct communication between devices, which can improve the speed and reliability of file transfers. Remote Control Applications − Java Sockets can also be used to create remote control applications, such as remote desktop software. These types of applications use a client-server architecture, where a client connects to a remote server to control the desktop of the server. This allows users to access and control their desktop from any device with an internet connection. Multiplayer Games − Java Sockets are also commonly used to create multiplayer games, such as online role-playing games and first-person shooters. These types of applications typically use a client-server architecture, where clients connect to a central server to play the game. The server acts as the intermediary between clients, handling communication and game logic. IoT Applications − Java Sockets can also be used in IoT (Internet of Things) applications, such as smart home systems. These types of applications use a client-server architecture, where IoT devices connect to a central server

Java – List Interface

Java – List Interface ”; Previous Next List Interface The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following table. Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another. Declaration of Java List Interface The following is the declaration of a List interface in Java: public interface List<E> extends Collection<E>; Creating a Java list A Java list is created using the List interface. The syntax is as follows – List<Obj> list = new ArrayList<Obj> (); Example of List Interface The following example demonstrates an example of List interface in Java – import java.util.*; // The Main class public class Main { public static void main(String[] args) { // Creating two lists using List interface List < Integer > list1 = new ArrayList < Integer > (); List < Integer > list2 = new ArrayList < Integer > (); // Adding elements to list 1 list1.add(0, 10); list1.add(1, 20); // Printing list 1 System.out.println(“list1 : ” + list1); // Adding elements to list 2 list2.add(10); list2.add(20); list2.add(30); // Adding all elements of list 2 in list 1 list1.addAll(1, list2); // Printing list 2 System.out.println(“list2 : ” + list2); // Removes an element from list 1 (from index 1) list1.remove(1); // Printing list 1 System.out.println(“list1 after removing an element: ” + list1); // get() method System.out.println(“list1 using get() : ” + list1.get(2)); // Replacing element list1.set(0, 50); // Printing the list 1 System.out.println(“list1 : ” + list1); } } Output list1 : [10, 20] list2 : [10, 20, 30] list1 after removing an element: [10, 20, 30, 20] list1 using get() : 30 list1 : [50, 20, 30, 20] List Interface Methods The following are the methods of List Interface in Java – Sr.No. Method & Description 1 void add(int index, Object obj) Inserts obj into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. 2 boolean addAll(int index, Collection c) Inserts all elements of c into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise. 3 Object get(int index) Returns the object stored at the specified index within the invoking collection. 4 int indexOf(Object obj) Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned. 5 int lastIndexOf(Object obj) Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned. 6 ListIterator listIterator( ) Returns an iterator to the start of the invoking list. 7 ListIterator listIterator(int index) Returns an iterator to the invoking list that begins at the specified index. 8 Object remove(int index) Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one. 9 Object set(int index, Object obj) Assigns obj to the location specified by index within the invoking list. 10 List subList(int start, int end) Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object. More Examples of List Interface Example: Java List using ArrayList The above interface has been implemented using ArrayList. Following is the example to explain few methods from various class implementation of the above collection methods − import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<String> a1 = new ArrayList<>(); a1.add(“Zara”); a1.add(“Mahnaz”); a1.add(“Ayan”); System.out.println(” ArrayList Elements”); System.out.print(“t” + a1); } } Output ArrayList Elements [Zara, Mahnaz, Ayan] Example: Java List using LinkedList The above interface has been implemented using LinkedList. Following is the example to explain few methods from various class implementation of the above collection methods − import java.util.LinkedList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<String> a1 = new LinkedList<>(); a1.add(“Zara”); a1.add(“Mahnaz”); a1.add(“Ayan”); System.out.println(” LinkedList Elements”); System.out.print(“t” + a1); } } Output LinkedList Elements [Zara, Mahnaz, Ayan] Example: Adding Element to Java List The above interface has been implemented using ArrayList. Following is another example to explain few methods from various class implementation of the above collection methods − import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<String> a1 = new ArrayList<>(); a1.add(“Zara”); a1.add(“Mahnaz”); a1.add(“Ayan”); System.out.println(” ArrayList Elements”); System.out.print(“t” + a1); // remove second element a1.remove(1); System.out.println(“n ArrayList Elements”); System.out.print(“t” + a1); } } Output ArrayList Elements [Zara, Mahnaz, Ayan] ArrayList Elements [Zara, Ayan] Print Page Previous Next Advertisements ”;