Java 8 – New Features ”; Previous Next JAVA 8 is a major feature release of JAVA programming language development. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided supports for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc. Following is the list of new features supported in Java 8: Lambda Expressions Lambda expression is one of the biggest feature introduced in Java. A lambda expression facilitates functional programming in Java. 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. Example – Using Lambda Expressions Following example showcases the use of lambda expression. A lambda expression works best with a functional interface, an interface with single abstract method. We”ve defined one interface Calculator with single method operate, which can accept two parameters and return a value. In main method, we”ve implemented the Calculator interface using anonymous function first and then using a lambda expression. The operate() method is called to print the result in both cases and results are printed. package com.tutorialspoint; public class Tester { public static void main(String[] args) { // Interface implementation using anonymous class Calculator sum = new Calculator() { @Override public int operate(int a, int b) { return a + b; } }; int result = sum.operate(2,3); System.out.println(result); // Interface implementation using lambda expression Calculator sum1 = (a,b) -> a + b; result = sum1.operate(2,3); System.out.println(result); } interface Calculator { int operate(int a, int b); } } Let us compile and run the above program, this will produce the following result − 5 5 Method References Method reference is a short and concise way to call methods, static methods and even constructors without any lengthy syntax. 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. A static method can be referred using following syntax: <<class-name>>::methodName An instance method can be referred using following syntax: <<object-name>>::methodName We can invoke constructor using following syntax: <<class-name>>::new Example – Using Method References In this example, we”ve used a static method compare and an instance method compareTo to sort two arraylist of integers. We”ve used method references to represent both static and instance methods. 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 static method reference”); // Use static method compare numbers = numbers.stream().sorted(Integer::compare).toList(); System.out.println(numbers); numbers = Arrays.asList(1,2,4,9,8,7,3); System.out.println(“Sorted using instance method reference” ); // Use instance method compareTo numbers = numbers.stream().sorted(Integer::compareTo).toList(); System.out.println(numbers); } } Let us compile and run the above program, this will produce the following result − Sorted using static method reference [1, 2, 3, 4, 7, 8, 9] Sorted using instance method reference [1, 2, 3, 4, 7, 8, 9] Default Methods Before Java 8, an interface could have only abstract methods. With Java 8, lambda expression were introduced. Now for backward compatability, default method capability was added so that old interfaces can leverage lambda expression without modifying their implementations. For example, List or Collection interfaces do not have ”forEach” method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same. Syntax The following is the syntax of the default method in interface in Java − public interface vehicle { default void message() { System.out.println(“I am a vehicle!”); } } Example – Using Default Method In this example, we”ve created an interface with a default method. In an implementing class, this message is not implemented and is used to print a message. package com.tutorialspoint; interface vehicle { // default method must have an implementation default void message() { System.out.println(“I am a vehicle!”); } } // implementing class need not to implement the default method // of an interface. public class Tester implements vehicle { public static void main(String args[]) { Tester tester = new Tester(); // implementing class can access the default method as its own method tester.message(); } } Let us compile and run the above program, this will produce the following result − I am a vehicle! Stream API Stream API is a new abstract layer introduced in Java 8 to process data in a declarative way. A stream represents a sequence of elements. A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on and can do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. Syntax Following is the generic syntax to use a stream <<collection-instance>>.stream().<<non-terminal-operation()>>.<<non-terminal-operation()>>.<<terminal-operation()>> Example – Using Stream In this example, we”ve created a list of strings where few entries are empty. Now using stream API, we”re filtering the empty strings and counting them. package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class Tester { public static void main(String args[]) { List<String> strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); // get stream from list using stream() method // then apply filter // lastly count the result of filter long count = strings.stream().filter(string->string.isEmpty()).count(); System.out.println(“Empty Strings: ” + count); } } Let us compile and run the above program, this will produce the following result − Empty Strings: 2 Optional Class Optional class feature was introduced in java 8 to handle Null
Category: Java
Java – Process API Improvements ”; Previous Next In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process”s native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes” liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits. Spawning a new Process Example In this example, we”ve created a new Process for notepad and started it using ProcessBuilder. Using ProcessHandle.Info interface, we”re getting the process information of the newly spawned process. package com.tutorialspoint; import java.time.ZoneId; import java.util.stream.Stream; import java.util.stream.Collectors; import java.io.IOException; public class Tester { public static void main(String[] args) throws IOException { ProcessBuilder pb = new ProcessBuilder(“notepad.exe”); String np = “Not Present”; Process p = pb.start(); ProcessHandle.Info info = p.info(); System.out.printf(“Process ID : %s%n”, p.pid()); System.out.printf(“Command name : %s%n”, info.command().orElse(np)); System.out.printf(“Command line : %s%n”, info.commandLine().orElse(np)); System.out.printf(“Start time: %s%n”, info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()) .toLocalDateTime().toString()).orElse(np)); System.out.printf(“Arguments : %s%n”, info.arguments().map(a -> Stream.of(a).collect( Collectors.joining(” “))).orElse(np)); System.out.printf(“User : %s%n”, info.user().orElse(np)); } } Output You will see the similar output. Process ID : 5580 Command name : C:Program FilesWindowsAppsMicrosoft.WindowsNotepad_11.2401.26.0_x64__8wekyb3d8bbweNotepadNotepad.exe Command line : Not Present Start time: 2024-04-02T17:07:14.305 Arguments : Not Present User : DESKTOPTutorialspoint Getting Current Process Information Example In this example, we”ve getting current process using ProcessHandle.current() method. Then using ProcessHandle.Info interface, we”re getting the process information of the current process. package com.tutorialspoint; import java.time.ZoneId; import java.util.stream.Stream; import java.util.stream.Collectors; import java.io.IOException; public class Tester { public static void main(String[] args) throws IOException { String np = “Not Present”; ProcessHandle currentProcess = ProcessHandle.current(); ProcessHandle.Info info = currentProcess.info(); System.out.printf(“Process ID : %s%n”, currentProcess.pid()); System.out.printf(“Command name : %s%n”, info.command().orElse(np)); System.out.printf(“Command line : %s%n”, info.commandLine().orElse(np)); System.out.printf(“Start time: %s%n”, info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()) .toLocalDateTime().toString()).orElse(np)); System.out.printf(“Arguments : %s%n”, info.arguments().map(a -> Stream.of(a).collect( Collectors.joining(” “))).orElse(np)); System.out.printf(“User : %s%n”, info.user().orElse(np)); } } Output You will see the similar output. Process ID : 5352 Command name : C:Program FilesJavajdk-21binjavaw.exe Command line : Not Present Start time: 2024-04-02T17:09:17.902 Arguments : Not Present User : DESKTOP-DTHL8BITutorialspoint Getting Child Processes Example In this example, we”ve getting current process chid processes using ProcessHandle.current().children() method. Then using ProcessHandle.Info interface, we”re getting the process information of the child processes. package com.tutorialspoint; import java.io.IOException; import java.util.stream.Stream; public class Tester { public static void main(String[] args) throws IOException { for (int i = 0; i < 3; i++) { ProcessBuilder processBuilder = new ProcessBuilder(“java.exe”, “-version”); processBuilder.inheritIO().start(); } Stream<ProcessHandle> childProcesses = ProcessHandle.current().children(); String np = “Not Present”; childProcesses.filter(ProcessHandle::isAlive).forEach( childProcess ->{ System.out.printf(“Process ID : %s%n”, childProcess.pid()); System.out.printf(“Command name : %s%n”, childProcess.info().command().orElse(np)); System.out.printf(“Command line : %s%n”, childProcess.info().commandLine().orElse(np)); } ); } } Output You will see the similar output. Process ID : 5420 Command name : C:Program FilesJavajdk-21binjava.exe Command line : Not Present Process ID : 15796 Command name : C:Program FilesJavajdk-21binjava.exe Command line : Not Present Process ID : 14180 Command name : C:Program FilesJavajdk-21binjava.exe Command line : Not Present java version “21.0.2” 2024-01-16 LTS Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58) Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing) java version “21.0.2” 2024-01-16 LTS Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58) Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing) java version “21.0.2” 2024-01-16 LTS Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58) Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing) Print Page Previous Next Advertisements ”;
AWT Tutorial
AWT Tutorial PDF Version Quick Guide Resources Job Search Discussion JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way. In this article we”ll look in AWT (Abstract Window Toolkit). Audience This tutorial is designed for Software Professionals who are willing to learn JAVA GUI Programming in simple and easy steps. This tutorial will give you great understanding on JAVA GUI Programming concepts and after completing this tutorial you will be at intermediate level of expertise from where you can take yourself at higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a basic understanding of Java programming language, text editor and execution of programs etc. Print Page Previous Next Advertisements ”;
Java – Serialization
Java – Serialization ”; Previous Next Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object”s data as well as information about the object”s type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform. Methods for Serializing and Deserializing an Object Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out − Syntax public final void writeObject(Object x) throws IOException The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object − Syntax public final Object readObject() throws IOException, ClassNotFoundException This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type. How Serialization Works in Java? To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface − Example to Demonstrate Working of Serialization in Java public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println(“Mailing a check to ” + name + ” ” + address); } } Notice that for a class to be serialized successfully, two conditions must be met − The class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it”s not. Serializing an Object The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file. When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing. Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension. Example for Serializing an Object import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = “Reyan Ali”; e.address = “Phokka Kuan, Ambehta Peer”; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream(“employee.ser”); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf(“Serialized data is saved in /tmp/employee.ser”); } catch (IOException i) { i.printStackTrace(); } } } class Employee implements java.io.Serializable { private static final long serialVersionUID = 1L; public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println(“Mailing a check to ” + name + ” ” + address); } } Output Serialized data is saved in employee.ser Deserializing an Object The following DeserializeDemo program deserializes the Employee object created in the earlier program. Study the program and try to determine its output − Example for Deserializing an Object import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream(“employee.ser”); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println(“Employee class not found”); c.printStackTrace(); return; } System.out.println(“Deserialized Employee…”); System.out.println(“Name: ” + e.name); System.out.println(“Address: ” + e.address); System.out.println(“SSN: ” + e.SSN); System.out.println(“Number: ” + e.number); } } class Employee implements java.io.Serializable { private static final long serialVersionUID = 1L; public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println(“Mailing a check to ” + name + ” ” + address); } } Output Deserialized Employee… Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101 Importing Points About Serialization in Java Here are following important points to be noted − The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can”t find a class during the deserialization of an object, it throws a ClassNotFoundException. Notice that the return value of readObject() is cast to an Employee reference. The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0. Print Page Previous Next Advertisements ”;
Java – Compact Number Formatting ”; Previous Next Java 12 introduces compact formatting where we can format long numbers for decimals, currency, or percentages into short form or long form. For example 1000 to 1K. This is very useful where we”ve limited space or requirements to show numbers in short form like K for thousand, M for million B for Billon, and so on. We can use custom strings as well to display large numbers. Create a CompactNumberFormat Instance To create an instance of CompactNumberFormat for a locale, you can use the related built-in method of NumberFormat. NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); Here we”re creating a formatter for US Locale and short format style, that means 1000 will be represented by 1K. Similarly we can create an instance for Long Format as shown below. NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG); In this case, 1000 will be represented by 1 thousand and so. Format the Value Once formatter is created, we can use format() method to get the required formatted number string. //1000 will be formatted as 1K String formatted = formatter.format(1000) //1000000 will be formatted as 1M formatted = formatter.format(1000000) Example of Compact Number Formatting In following example, we”re printing long as well as short formatted string retrived using compact number formatting. package com.tutorialspoint; import java.text.NumberFormat; import java.util.Locale; public class Tester { public static void main(String[] args) { // Create the formatter instance for Long format NumberFormat formatter = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.LONG); System.out.println(“Long Formats”); // get the formatted strings System.out.println(formatter.format(1000)); System.out.println(formatter.format(1000 * 1000)); System.out.println(formatter.format(1000 * 1000 * 1000)); // Create the formatter instance for Short format formatter = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.SHORT); // get the formatted strings System.out.println(“Short Formats”); System.out.println(formatter.format(1000)); System.out.println(formatter.format(1000 * 1000)); System.out.println(formatter.format(1000 * 1000 * 1000)); } } Let us compile and run the above program, this will produce the following result − Long Formats 1 thousand 1 million 1 billion Short Formats 1K 1M 1B Compact Number Formatting and Fraction Digits By default fraction digit is set as zero, but we can set minimum fraction digits as well using following method. NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); formatter.setMinimumFractionDigits(3); // It will print 10.012K System.out.println(formatter.format(10012)); Example: Compact Number Formatting with Fractions In following example, we”re printing long as well as short formatted string retrived using compact number formatting. package com.tutorialspoint; import java.text.NumberFormat; import java.util.Locale; public class Tester { public static void main(String[] args) { // Create the formatter instance for Short format NumberFormat formatter = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.SHORT); System.out.println(“Without using Fractions”); // get the formatted strings System.out.println(formatter.format(10012)); System.out.println(formatter.format(10000012)); // set the minimum 2 fraction digits to display formatter.setMinimumFractionDigits(2); System.out.println(“Using Fractions”); // get the formatted strings System.out.println(formatter.format(10012)); System.out.println(formatter.format(10000012)); } } Let us compile and run the above program, this will produce the following result − Without using Fractions 10K 10M Using Fractions 10.01K 10.00M Print Page Previous Next Advertisements ”;
Java 13 – New Features
Java 13 – New Features ”; Previous Next Java 13 is a major feature release and it has brought many JVM specific changes to JAVA and few language specific changes. It followed the Java release cadence introduced Java 10 onwards and it was releasd on Sept 2019, just six months after Java 12 release. Java 13 is a non-LTS release. New Features in Java 13 Following are the major new features which are introduced in Java 13. JEP 354 – Switch Expressions – A preview feature allowing switch to use return values via yield. JEP 355 – Text Blocks – A preview feature to handle multiline strings like JSON, XML easily. String new methods – New Methods added to string to handle text blocks. JEP 353 – Socket API Reimplementation – Underlying API is rewritten. FileSystems.newFileSystem() – Three new methods added to make it easy to use. DOM/SAX Factories – New methods added to add namespace support. Dynamic CDS Archive – CDS archive can be created easily. JEP 351 – ZGC Enhancements – ZGC enhanced to return unused heap memory to operating system. Java 13 have introduced three new methods to java.nio.file.FileSystems to treat the content of a file as a file system easily. newFileSystem(Path) newFileSystem(Path, Map<String, ?>) newFileSystem(Path, Map<String, ?>, ClassLoader) Following are other major changes added to language. java.time – Japanese era name added javax.crypto – MS Cryptography Next Generation (CNG)support javax.security – jdk.sasl.disabledMechanisms property added disabling SASL mechanisms javax.xml.crypto – String constants introduced to represent Canonical XML 1.1 URIs javax.xml.parsers – Methods added to instantiate DOM and SAX factories for namespaces support Unicode support is upgraded to version 12.1 Kerberos principal name canonicalization support added, cross-realm referrals are supported. API marked for Removal SocketImpl implementations prior to JDK 1.4 javax.security.cert API rmic javadoc tool old features Other details are available at following link − APIs proposed for removal. Print Page Previous Next Advertisements ”;
Java – Enumeration
Java – Enumeration Interface ”; Previous Next The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code. Enumeration Interface Methods The methods declared by Enumeration are summarized in the following table − Sr.No. Method & Description 1 boolean hasMoreElements( ) When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated. 2 Object nextElement( ) This returns the next object in the enumeration as a generic Object reference. Example 1: Enumeration for Vector Following is an example showing usage of Enumeration for a Vector. import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration<String> days; Vector<String> dayNames = new Vector<>(); dayNames.add(“Sunday”); dayNames.add(“Monday”); dayNames.add(“Tuesday”); dayNames.add(“Wednesday”); dayNames.add(“Thursday”); dayNames.add(“Friday”); dayNames.add(“Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday Example 2: Enumeration for properties Following is an example showing usage of Enumeration for Properties to print the values. import java.util.Vector; import java.util.Enumeration; import java.util.Properties; public class EnumerationTester { public static void main(String args[]) { Enumeration<Object> days; Properties dayNames = new Properties(); dayNames.put(1, “Sunday”); dayNames.put(2,”Monday”); dayNames.put(3,”Tuesday”); dayNames.put(4,”Wednesday”); dayNames.put(5,”Thursday”); dayNames.put(6,”Friday”); dayNames.put(7,”Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday java_data_structures.htm Print Page Previous Next Advertisements ”;
Java – Pattern Matching
Java – Pattern Matching with instanceof Operator ”; Previous Next Java 14 introduces instanceof operator to have type test pattern as is a preview feature. Type test pattern has a predicate to specify a type with a single binding variable. It is a standard feature of Java from Java 17 onwards. Syntax with Enhanced instanceof operator In following code snippet, we”ve used instanceof operator to test person object being an Employee as well assign person object to Employee reference e which is then used to perform operation on Employee object. if (person instanceof Employee e) { return e.getEmployeeId(); } Before this enhancement, developers have to typecast the object as shown below: Syntax without Enhanced instanceof operator In following code snippet, we”re showing regular approach of testing person object with Employee class and then in if block, we”re typecasting the person to Employee e to perform operation on Employee object. if (person instanceof Employee) { // Unnecessary casting Employee e = (Employee)person; return e.getEmployeeId(); } Example – Old Syntax In this example, we”ve defined classes Person, Employee and Manager. Employee and Manager extends Person class. In APITester class, we”ve defined a method getId() which takes Person as input and using instanceof operator, we”re testing the type of object as either Employee or Manager and then based on the result of if block, we”re typecasting the object to either Employee or Manager and return the employeeId or managerId accordingly. package com.tutorialspoint; public class APITester { public static void main(String[] args) { // Create a Manager Instance Person manager = new Manager(23, “Robert”); // Get and print Id of the manager System.out.println(getId(manager)); } // using instanceof operator // to test type of Person to be Employee or Manager public static int getId(Person person) { // If person is Employee, assign it to e // in next statement if (person instanceof Employee) { // Unnecessary typecasting Employee e = (Employee)person; return e.getEmployeeId(); } // If person is Manager, assign it to m // in same statement else if (person instanceof Manager) { // Unnecessary typecasting Manager m = (Manager)person; return m.getManagerId(); } return -1; } } abstract sealed class Person permits Employee, Manager { String name; String getName() { return name; } } final class Employee extends Person { String name; int id; Employee(int id, String name){ this.id = id; this.name = name; } int getEmployeeId() { return id; } } non-sealed class Manager extends Person { int id; Manager(int id, String name){ this.id = id; this.name = name; } int getManagerId() { return id; } } Output Let us compile and run the above program, this will produce the following result − 23 Example – New Syntax In this example, we”ve defined classes Person, Employee and Manager. Employee and Manager extends Person class. In APITester class, we”ve defined a method getId() which takes Person as input and using instanceof operator, we”re testing the type of object as either Employee or Manager and then within same if block, we”re assigning the object to either Employee or Manager without typecasting and return the employeeId or managerId accordingly. package com.tutorialspoint; public class APITester { public static void main(String[] args) { // Create a Manager Instance Person manager = new Manager(23, “Robert”); // Get and print Id of the manager System.out.println(getId(manager)); } // using instanceof operator // to test type of Person to be Employee or Manager public static int getId(Person person) { // If person is Employee, assign it to e // in same statement if (person instanceof Employee e) { return e.getEmployeeId(); } // If person is Manager, assign it to m // in same statement else if (person instanceof Manager m) { return m.getManagerId(); } return -1; } } abstract sealed class Person permits Employee, Manager { String name; String getName() { return name; } } final class Employee extends Person { String name; int id; Employee(int id, String name){ this.id = id; this.name = name; } int getEmployeeId() { return id; } } non-sealed class Manager extends Person { int id; Manager(int id, String name){ this.id = id; this.name = name; } int getManagerId() { return id; } } Output Let us compile and run the above program, this will produce the following result − 23 Print Page Previous Next Advertisements ”;
Java – Default Methods
Java – Default Methods in Interfaces ”; Previous Next Java Default Methods Java introduced a new concept of default method implementation in interfaces in Java 8. Prior to Java8, an interface could have only abstract methods. Default method capability was added for backward compatibility so that old interfaces could be used to leverage the lambda expression capability of Java 8. For example, List or Collection interfaces do not have ”forEach” method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same. Syntax The following is the syntax of the default method in interface in Java – public interface vehicle { default void print() { System.out.println(“I am a vehicle!”); } } Java Default Method Example package com.tutorialspoint; interface vehicle { // default method must have an implementation default void print() { System.out.println(“I am a vehicle!”); } } // implementing class needs not to implement the default method // of an interface. public class Tester implements vehicle { public static void main(String args[]) { Tester tester = new Tester(); // implementing class can access the default method as its own method tester.print(); } } Let us compile and run the above program, this will produce the following result − I am a vehicle! Default Methods in Multiple Inheritance With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved. public interface vehicle { default void print() { System.out.println(“I am a vehicle!”); } } public interface fourWheeler { default void print() { System.out.println(“I am a four wheeler!”); } } First solution is to create an own method that overrides the default implementation. public class car implements vehicle, fourWheeler { public void print() { System.out.println(“I am a four wheeler car vehicle!”); } } Example: Overriding default method of interfaces with own implementation In this example, we”ve created two interfaces with same default method print(). As Car class is implementing both the interfaces, so it has to override the default method otherwise compiler will complain for duplicate default methods. After overriding the default method with own implementation, we can easily use the print method of the Car class as shown below: package com.tutorialspoint; interface Vehicle { default void print() { System.out.println(“I am a vehicle!”); } } interface FourWheeler { default void print() { System.out.println(“I am a four wheeler!”); } } class Car implements Vehicle, FourWheeler { // overriding the default method will resolve the ambiguity public void print() { System.out.println(“I am a four wheeler car vehicle!”); } } public class Tester { public static void main(String args[]) { Car car = new Car(); car.print(); } } Let us compile and run the above program, this will produce the following result − I am a four wheeler car vehicle! Second solution is to call the default method of the specified interface using super. public class car implements vehicle, fourWheeler { public void print() { vehicle.super.print(); } } Example: Calling default method of interfaces In this example, we”ve created two interfaces with same default method print(). As Car class is implementing both the interfaces, so it has to override the default method otherwise compiler will complain for duplicate default methods. After overriding the default method with own implementation, we can easily use the print method of the Car class as shown below: package com.tutorialspoint; interface Vehicle { default void print() { System.out.println(“I am a vehicle!”); } } interface FourWheeler { default void print() { System.out.println(“I am a four wheeler!”); } } class Car implements Vehicle, FourWheeler { // use the default method of a interface public void print() { FourWheeler.super.print(); } } public class Tester { public static void main(String args[]) { Car car = new Car(); car.print(); } } Let us compile and run the above program, this will produce the following result − I am a four wheeler! Static Default Methods in Java An interface can also have static default methods from Java 8 onwards. These static methods acts as helper or utility functions and helps in better encapsulation of code. public interface vehicle { default void print() { System.out.println(“I am a vehicle!”); } static void blowHorn() { System.out.println(“Blowing horn!!!”); } } Example: Calling static default method of interface In this example, we”ve created two interfaces with same default method print(). As Car class is implementing both the interfaces, so it has to override the default method. After overriding the default method with calls to interfaces implementation, we”ve called the static method directly as shown below: package com.tutorialspoint; interface Vehicle { default void print() { System.out.println(“I am a vehicle!”); } static void blowHorn() { System.out.println(“Blowing horn!!!”); } } interface FourWheeler { default void print() { System.out.println(“I am a four wheeler!”); } } class Car implements Vehicle, FourWheeler { public void print() { // call the Vehicle interface default print method Vehicle.super.print(); FourWheeler.super.print(); // call the Vehicle interface static blowHorn method Vehicle.blowHorn(); System.out.println(“I am a car!”); } } public class Tester { public static void main(String args[]) { Vehicle vehicle = new Car(); vehicle.print(); // call the Vehicle interface static blowHorn method Vehicle.blowHorn(); } } Let us compile and run the above program, this will produce the following result − I am a vehicle! I am a four wheeler! Blowing horn!!! I am a car! Blowing horn!!! Print Page Previous Next Advertisements ”;
Java – Recursion
Java – Recursion ”; Previous Next Java – Recursion Recursion is a programming technique where a method calls itself to perform a sub-operation as necessary. The method which is calling itself is termed as a recursive function. Recursion is primary used to break big problems into smaller problems and then solving them recursively. Recursion technique makes code more readable and expressive. Example Consider the following case − // recursive method public int sum(int n){ // recursive method call return n == 1 ? 1 : n + sum(n-1); } In this case, we”re getting sum of n natural numbers using recursion which can be tabulated as n + sum of n – 1 numbers. Using recursion, we are adding the result of sum of n-1 natural numbers with n to get the required result. As a recursive function calls itself, there must be a base condition based on which the recursive method can stop calling itself indefinitely. If base condition is not present or never comes true, then it will cause a stack overflow in program. In above example, we”re having a base condition of n being 1. public int sum(int n){ // base condition if(n == 1){ return 1; } // recursive call return n + sum(n-1); } If we call this function with a negative int value, then it will cause a stack overflow error. How Recursion Works in Java? In Java, variables, method call, references are stored in stack whereas objects are allotted memory in heap. Whenever a method is called, its details are pushed to the stack like value of the argument passed, any local variable, computation etc. During recursive call, whenever a method calls itself, its entry is pushed to the stack till the base condition terminates the flow. When base condition comes true, and method starts returning the value, the result of sub call is popped from the stack and so on till the all entries of method is popped from the stack. Let”s understand this with an example. Example package com.tutorialspoint; public class Tester { public static void main(String[] args) { Tester tester = new Tester(); int result = tester.sum(5); System.out.println(“Sum: ” + result); } public int sum(int n){ System.out.println(“Input: ” + n); int result; // base condition if(n == 1){ result = 1; System.out.println(“Base condition fulfilled.”); }else { // recursive call result = n + sum(n-1); } System.out.println(“Result: ” + result); return result; } } Output Let us compile and run the above program, this will produce the following result − Input: 5 Input: 4 Input: 3 Input: 2 Input: 1 Base condition fulfilled. Result: 1 Result: 3 Result: 6 Result: 10 Result: 15 Sum: 15 In this program, we can see easily that during recursive calls, initially input value is getting printed till the base condition is fulfilled as method calls are being pushed to stack. Once base condition is fulfilled, the recursive calls finished and method result is getting popped from the stack as evident from the output. Java Recursion Examples 1. Calculating Factorial Using Recursion factorial is a mathematical expression which represents the following formulation. n! = n * (n-1)! This kind of the problems are perfect candidates to be solved using recursion. Consider the following code snippet. fact(n) = n * fact(n-1) Here a fact() is method which is to return the factorial of a given natural number. Now before implementing the fact(), we should think on base conditions are well which should be as following. 1! = 1 Now let”s see the complete example for factorial using recursion. package com.tutorialspoint; public class Tester { public static void main(String[] args) { Tester tester = new Tester(); // call the recursive method to get the factorial int result = tester.fact(5); System.out.println(“Factorial: ” + result); } // recursive method public int fact(int n) { // if base condition is not true, make a recursive call return n == 1 ? 1: n * fact(n-1); } } Output Let us compile and run the above program, this will produce the following result − Factorial: 120 2. Calculating Sum of Fibonacci Series Using Recursion fibbonacci series is a very important and interesting series in mathematics. It represents the follwing equation − F(n) = F(n-1) + F(n-2) Here, we cand say, fibbonacci number represents the sum of its predecessor and the next predecessor. A fibbonacci series is of form 0, 1, 1, 2, 3, 5 and s on. Using recursion, we can easily compute the fibbonacci number. Consider the following code snippet. fibo(n) = fibo(n-1) + fibo(n-2) Here a fibo() is method which is to return the fibonacci of a given whole number. Now before implementing the fibo(), we should think on base conditions are well which should be as following. fibo(0) = 0; fibo(1) = 1; Now let”s see the complete example for fibonacci number computation using recursion. package com.tutorialspoint; public class Tester { public static void main(String[] args) { Tester tester = new Tester(); int result = tester.fibo(5); System.out.println(“Fibbonacci: ” + result); } public int fibo(int n) { return n <= 1 ? n : fibo(n-1) + fibo(n-2); } } Output Let us compile and run the above program, this will produce the following result − Fibbonacci: 5 Advantages of Using Recursion in Java Following are the advantages of using recursion in Java: Cleaner code Using recursion makes code easy to understand and keeps code clean. Instead of using multiple if and loops conditions, recursion helps in writing code in functional way. Recursive algorithm For certain problem, like tree traversal, tower of hanoi problem etc, recursion is the best apporach to code the solution. Reduces time complexity Recursive program helps in reducing time taken in searches on large datasets. Disadvantages of Using Recursion in Java Following are the disadvantages of using recursion in Java: Expertise Recursion although is a cleaner approach but required high amount of expertise and understanding of the problem statement and proposed solution. An incorrectly implemented recursion may cause performance issues and may be