Java – Sealed Classes

Java – Sealed Classes and Interfaces ”; Previous Next Java 15 introduced a sealed class as a preview feature which provides a fine-grained control over inheritance. Java 16 provides some minor enhancements and keeps this feature as a Preview. With Java 17, sealed class and interface a standard features. A sealed class/interface feature is added to Java to provide developers a fine fine-grained control over inheritance. A sealed class can define the subtypes that are permitted to extend it while other classes cannot extend it. The following are salient points to consider for a sealed class − A sealed class is declared using a sealed keyword. Sealed classes allow to declaration of which class can be a subtype using the permits keyword. A class extending sealed class must be declared as either sealed, non-sealed, or final. Sealed classes help in creating a finite and determinable hierarchy of classes in inheritance. Sealed Interface An interface can be marked as sealed interface using sealed keyword and then using permits keywords, we can add the interfaces which can extend this interface. public sealed interface Person permits Employee, Manager { } Sealed Interface Example In this example, we”ve created a sealed interface Person which permits Employee and Manager interfaces to extend it. Employee and Manager interfaces have different methods to get the ID of a person. Now in order to get ID of a person, we”re using instanceof operator to check an instance being of Employee or Manager and get the corresponding ID. Thus we can see, that knowing the permissible interfaces upfront helps in development for such scenarios. package com.tutorialspoint; public class Tester { public static void main(String[] args) { // create an instance of Manager Person manager = new CorpManager(23, “Robert”); // get the id System.out.println(“Id: ” + getId(manager)); } public static int getId(Person person) { // check if person is employee then return employee id if (person instanceof Employee) { return ((Employee) person).getEmployeeId(); } // if person is manager then return manager id else if (person instanceof Manager) { return ((Manager) person).getManagerId(); } return -1; } } // a sealed interface Person which is to be inherited by Employee // and Manager interfaces sealed interface Person permits Employee, Manager { String getName(); } // Employee and Manager interfaces have to extend Person and can be sealed or non-sealed non-sealed interface Employee extends Person { int getEmployeeId(); } non-sealed interface Manager extends Person { int getManagerId(); } class CorpEmployee implements Employee { String name; int id; public CorpEmployee(int id,String name) { this.name = name; this.id = id; } public String getName() { return name; } public int getEmployeeId() { return id; } } class CorpManager implements Manager { String name; int id; public CorpManager(int id,String name) { this.name = name; this.id = id; } public String getName() { return name; } public int getManagerId() { return id; } } Let us compile and run the above program, this will produce the following result − Id: 23 Sealed Class Similar to sealed interface, a class can be marked as sealed class as well using sealed keyword and then using permits keywords, we can add the subclasses which can extend this class. public abstract sealed class Person permits Employee, Manager { } A subclass needs to have a modifier as sealed/final or non-sealed. public final class Manager extends Person { } A subclass with non-sealed is open for all classes to extend. public non-sealed class Employee extends Person { } Constraints There are few constraint on usage of sealed classes which we should notice while extending a sealed class. Permitted subclass should be part of same module as of sealed class. Permitted subclass has to extend the sealed class. A permitted subclass has to use any one of final, sealed, or non-sealed modifier. Sealed Class Example In this example, we”ve created a sealed abstract class Person which permits Employee and Manager classes to extend it. Employee and Manager classes have different methods to get the ID of a person. Now in order to get ID of a person, we”re using instanceof operator to check an instance being of Employee or Manager and get the corresponding ID. Thus we can see, that knowing the permissible SubClasses upfront helps in development for such scenarios. package com.tutorialspoint; public class Tester { public static void main(String[] args) { // create an instance of Manager Person manager = new Manager(23, “Robert”); // get the id System.out.println(“Id: ” + getId(manager)); } public static int getId(Person person) { // check if person is employee then return employee id if (person instanceof Employee) { return ((Employee) person).getEmployeeId(); } // if person is manager then return manager id else if (person instanceof Manager) { return ((Manager) person).getManagerId(); } return -1; } } // a sealed class Person which is to be inherited by Employee // and Manager classes abstract sealed class Person permits Employee, Manager { String name; String getName() { return name; } } // Employee class has to extend Person and should have a modifier final class Employee extends Person { String name; int id; Employee(int id, String name){ this.id = id; this.name = name; } int getEmployeeId() { return id; } } // We can mark a sub-class as non-sealed, so that it can be extended if required non-sealed class Manager extends Person { int id; Manager(int id, String name){ this.id = id; this.name = name; } int getManagerId() { return id; } } Let us compile and run the above program, this will produce the following result − Id: 23 Print Page Previous Next Advertisements ”;

Java – Strings

Java – String Class ”; Previous Next Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Creating Strings The most direct way to create a string is to write − String greeting = “Hello world!”; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!“. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. Example to Create Strings in Java public class StringDemo { public static void main(String args[]) { char[] helloArray = { ”h”, ”e”, ”l”, ”l”, ”o”, ”.” }; String helloString = new String(helloArray); System.out.println( helloString ); } } Output hello. Note − The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. The following program is an example of length(), method String class. Example to Get String Length in Java public class StringDemo { public static void main(String args[]) { String palindrome = “Dot saw I was Tod”; int len = palindrome.length(); System.out.println( “String Length is : ” + len ); } } This will produce the following result − Output String Length is : 17 Concatenating Strings The String class includes a method for concatenating two strings − string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in − “My name is “.concat(“Zara”); Strings are more commonly concatenated with the + operator, as in − “Hello,” + ” world” + “!” which results in − “Hello, world!” Let us look at the following example − Example to Concatenate Strings in Java public class StringDemo { public static void main(String args[]) { String string1 = “saw I was “; System.out.println(“Dot ” + string1 + “Tod”); } } This will produce the following result − Output Dot saw I was Tod Creating Format Strings You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String”s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of − Example to Create Formatted Strings in Java System.out.printf(“The value of the float variable is ” + “%f, while the value of the integer ” + “variable is %d, and the string ” + “is %s”, floatVar, intVar, stringVar); You can write − String fs; fs = String.format(“The value of the float variable is ” + “%f, while the value of the integer ” + “variable is %d, and the string ” + “is %s”, floatVar, intVar, stringVar); System.out.println(fs); Java String Class Methods The following are the built-in methods of the String class in Java with their syntaxes and usages − Sr.No. Method & Description 1 char charAt(int index) This method returns the char value at the specified index. 2 int codePointAt(int index) This method returns the character (Unicode code point) at the specified index. 3 int codePointBefore(int index) This method returns the character (Unicode code point) before the specified index. 4 int codePointCount(int beginIndex, int endIndex) This method returns the number of Unicode code points in the specified text range of this String. 5 int compareTo(String anotherString) This method compares two strings lexicographically. 6 int compareToIgnoreCase(String str) This method compares two strings lexicographically, ignoring case differences. 7 String concat(String str) This method concatenates the specified string to the end of this string. 8 boolean contains(CharSequence s) This method ceturns true if and only if this string contains the specified sequence of char values. 9 boolean contentEquals(CharSequence cs) This method compares this string to the specified CharSequence. 10 boolean contentEquals(StringBuffer sb) This method compares this string to the specified StringBuffer. 11 static String copyValueOf(char[] data) This method returns a String that represents the character sequence in the array specified. 12 static String copyValueOf(char[] data, int offset, int count) This method returns a String that represents the character sequence in the array specified. 13 boolean endsWith(String suffix) This method tests if this string ends with the specified suffix. 14 boolean equals(Object anObject) This method compares this string to the specified object. 15 boolean equalsIgnoreCase(String anotherString) This method compares this String to another String, ignoring case considerations. 16 static String format(Locale l, String format, Object… args) This method returns a formatted string using the specified locale, format string, and arguments. 17 static String format(String format, Object… args) This method returns a formatted string using the specified format string and arguments. 18 byte[] getBytes() This method encodes this String into a sequence of bytes using the platform”s default charset, storing the result into a new byte array. 19 byte[] getBytes(Charset charset) This method encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array. 20 byte[] getBytes(String charsetName) This method encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. 21 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) This method copies characters from this string into the destination character array. 22 int hashCode() This method returns a hash code

Java – URL Class

Java – URL Class ”; Previous Next What is a URL? URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Webpage or FTP directory. This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows − protocol://host:port/path?query#ref Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority. Example The following is a URL to a web page whose protocol is HTTP − https://www.amrood.com/index.htm?language=en#j2se Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80. Java URL Class The URL class is a part of the java.net package. URL class represents a Uniform Resource Locator (URL). Where, URLs are used for identifying online resources (for example: webpages, images used in the webpages, videos, files, etc.) The URL class provides several constructors and methods for creating, parsing, and manipulating URLs (or, URL objects). URL Class Declaration public final class URL extends Object implements Serializable URL Class Constructors The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java. The URL class has several constructors for creating URLs, including the following − Sr.No. Constructors & Description 1 public URL(String protocol, String host, int port, String file) throws MalformedURLException Creates a URL by putting together the given parts. 2 public URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException Creates a URL by putting together the given parts with the specified handler within a specified context. 3 public URL(String protocol, String host, String file) throws MalformedURLException Identical to the previous constructor, except that the default port for the given protocol is used. 4 public URL(String url) throws MalformedURLException Creates a URL from the given String. 5 public URL(URL context, String url) throws MalformedURLException Creates a URL by parsing together the URL and String arguments. 6 public URL(URL context, String url, URLStreamHandler handler) throws MalformedURLException Creates a URL by parsing together the URL and String arguments with the specified handler within a specified context. URL Class Methods The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following − Sr.No. Method & Description 1 public equals(Object obj) This method compares this URL for equality with another object. 2 public String getAuthority() This method returns the authority of the URL. 3 public Object getContent() This method returns the contents of this URL. 4 public Object getContent(Class<?>[] classes) This method returns the contents of this URL. 5 public int getDefaultPort() This method returns the default port for the protocol of the URL. 6 public String getFile() This method returns the filename of the URL. 7 public String getHost() This method returns the host of the URL. 8 public String getPath() This method returns the path of the URL. 9 public int getPort() This method returns the port of the URL. 10 public String getProtocol() This method returns the protocol of the URL. 11 public String getQuery() This method returns the query part of the URL. 12 public String getRef() This method returns the reference part of the URL. 13 public String getUserInfo() This method returns the userInfo part of the URL. 14 public int hashCode() This method creates and return an integer suitable for hash table indexing. 15 public URLConnection openConnection() This method returns a URLConnection instance that represents a connection to the remote object referred to by the URL. 16 public URLConnection openConnection(Proxy proxy) This method acts as openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection. 17 public InputStream openStream() This method opens a connection to this URL and returns an InputStream for reading from that connection. 18 public boolean sameFile(URL other) This method compares two URLs, excluding the fragment component. 19 public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) This method sets an application”s URLStreamHandlerFactory. 20 public String toExternalForm() This method constructs and return a string representation of this URL. 21 public String toString() This method constructs and return a string representation of this URL. 22 public String toURI() This method returns a URI equivalent to this URL. java.lang.Object Example of URL Class The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL. // File Name : URLDemo.java import java.io.IOException; import java.net.URL; public class URLDemo { public static void main(String [] args) { try { URL url = new URL(“https://www.tutorialspoint.com/index.htm?language=en#j2se”); System.out.println(“URL is ” + url.toString()); System.out.println(“protocol is ” + url.getProtocol()); System.out.println(“authority is ” + url.getAuthority()); System.out.println(“file name is ” + url.getFile()); System.out.println(“host is ” + url.getHost()); System.out.println(“path is ” + url.getPath()); System.out.println(“port is ” + url.getPort()); System.out.println(“default port is ” + url.getDefaultPort()); System.out.println(“query is ” + url.getQuery()); System.out.println(“ref is ” + url.getRef()); } catch (IOException e) { e.printStackTrace(); } } } A sample run of the this program will produce the following result − Output URL is https://www.tutorialspoint.com/index.htm?language=en#j2se protocol is https authority is www.tutorialspoint.com file name is /index.htm?language=en host is www.tutorialspoint.com path is /index.htm port is -1 default port is 443 query is language=en ref is j2se 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

Java – Text Blocks

Java – Text Blocks ”; Previous Next Java made text blocks in Java 15 as a standard feature to handle multiline strings like JSON/XML/HTML etc. It was introduced in Java 13 as a preview feature. Text Block allows to write multiline strings easily without using rn. Text Block string have same methods as string (String class methods) like contains(), indexOf(), and length() functions. Purpose of introducing text block is mainly to declare multi-line strings most efficiently. Prior to text block, we can declare multi-line strings using string concatenation, string builder append method, string join method but that approach is quite messy. As we have to use line terminators, delimiters etc to mark a new line. Text block provides a better and alternate approach to define multiline string using a “””, 3 double-quotes mark. Text Block Syntax A text block is an enhancement to existing String object with special syntax where string content should starts with “”” with newline and ends with “””. Any content within “”” will be used as-is. String textBlockJSON = “”” { “name” : “Mahesh”, “RollNO” : “32” } “””; Equivalent String can be written using older syntax as shown below: String stringJSON = “{rn” + ” “Name” : “Mahesh”,rn” + ” “RollNO” : “32”rn” + “}”; Example of Java Text Block In this example, we”ve printed the json string using text block as well as using string concatenation. package com.tutorialspoint; public class Tester { public static void main(String[] args) { String stringJSON = “{rn” + ” “Name” : “Mahesh”,rn” + ” “RollNO” : “32”rn” + “}”; System.out.println(stringJSON); String textBlockJSON = “”” { “name” : “Mahesh”, “RollNO” : “32” } “””; System.out.println(textBlockJSON); } } Output Let us compile and run the above program, this will produce the following result − { “Name” : “Mahesh”, “RollNO” : “32” } { “name” : “Mahesh”, “RollNO” : “32” } Text Block String Operations Text block is same as String and can be compared using equals() method or equal operator. // compare the content, textBlockJSON.equals(stringJSON); // compare the objects textBlockJSON == stringJSON; Text block supports all string operations like indexOf(), contains() etc. // check if text block contains a provided string or not textBlockJSON.contains(“Mahesh”); // get the length of string content textBlockJSON.length() Example: Text Block String Operations in Java In this example, we”ve performed various string operations and compared text block with an equivalent string. package com.tutorialspoint; public class Tester { public static void main(String[] args) { String stringJSON = “Mahesh”; String textBlockJSON = “”” Mahesh”””; // compare the content System.out.println(textBlockJSON.equals(stringJSON)); // compare the objects System.out.println(textBlockJSON == stringJSON); // text block supports all string operations System.out.println(“Contains: ” + textBlockJSON.contains(“Mahesh”)); System.out.println(“indexOf: ” + textBlockJSON.indexOf(“Mahesh”)); System.out.println(“Length: ” + textBlockJSON.length()); } } Output Let us compile and run the above program, this will produce the following result − true true Contains: true indexOf: 0 Length: 6 Text Block Methods stripIndent() – removes incidental white spaces from the start and end of the string. translateEscapes() – translate the escape sequences as per the string syntax. formatted() – similar to String format() method to support formatting in text block strings. Example Consider the following example − ApiTester.java public class APITester { public static void main(String[] args) { String textBlockJSON = “”” { “name” : “%s”, “RollNO” : “%s” } “””.formatted(“Mahesh”, “32”); System.out.println(textBlockJSON); } } Output { “name” : “Mahesh”, “RollNO” : “32” } Print Page Previous Next Advertisements ”;

Java – Base64 Encode Decode

Java – Base64 Encoding and Decoding ”; Previous Next The Base64 utility class was introduced in Java 8 that has inbuilt encoder and decoder for Base64 encoding and decoding. We”ve three types of Base64 encoding and decoding available. Following is a brief of these types added: Basic − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/. URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe. MIME − Output is mapped to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return ”r” followed by a linefeed ”n” as the line separator. No line separator is present to the end of the encoded output. Basic Base64 Encoding and Decoding Basic Base64 encoder encodes the provided string without adding any line feed. This encoder uses characters lying in A-Za-z0-9+/ character set. Following is the snippet explaining the use of Base64 encoder. String stringToEncode = “TutorialsPoint?java8”; // Encode using basic encoder String base64encodedString = Base64.getEncoder().encodeToString(stringToEncode.getBytes(“utf-8”)); Simple Base64 decoder decodes the Base64 encoded string by rejecting any character other than A-Za-z0-9+/. Following is the snippet explaining the use of Base64 decoder. // Decode the base64 encoded string using basic decoder byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString); // print the decoded string System.out.println(“Original String: ” + new String(base64decodedBytes, “utf-8″)); Example: Basic Base64 Encoding and Decoding in Java Following example showcases the use of Base64 basic encoder and decoder. We”ve first encoded a simple string using a encoder retrieved using Base64.getEncoder() and then returned encoded string is decoded using decoder retrieved using Base64.getDecoder() method. package com.tutorialspoint; import java.io.UnsupportedEncodingException; import java.util.Base64; public class Base64Tester { public static void main(String[] args) throws UnsupportedEncodingException { String stringToEncode = “TutorialsPoint?java”; // Encode using basic encoder String base64encodedString = Base64.getEncoder().encodeToString(stringToEncode.getBytes(“utf-8”)); System.out.println(“Encoded String: ” + base64encodedString); // Decode the base64 encoded string using basic decoder byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString); // print the decoded string System.out.println(“Decoded String: ” + new String(base64decodedBytes, “utf-8”)); } } Output Let us compile and run the above program, this will produce the following result − Encoded String: VHV0b3JpYWxzUG9pbnQ/amF2YQ== Decoded String: TutorialsPoint?java Base64 Encoding and Decoding for URL URL Base64 encoder encodes the provided URL and makes it URL and filename safe. This encoder uses characters lying in A-Za-z0-9+/ character set. It encodes using the URL and Filename safe type base64 encoding scheme. Following is the snippet explaining the use of URL Base64 encoder. String stringToEncode = “TutorialsPoint?java8”; // Encode using url encoder String base64encodedString = Base64.getUrlEncoder().encodeToString(stringToEncode.getBytes(“utf-8”)); URL Base64 decoder decodes the Base64 encoded string by rejecting any character other than A-Za-z0-9+/. It decodes using the URL and Filename safe type base64 encoding scheme. Following is the snippet explaining the use of Base64 decoder. // Decode the base64 encoded string using basic decoder byte[] base64decodedBytes = Base64.getUrlDecoder().decode(base64encodedString); // print the decoded string System.out.println(“Original String: ” + new String(base64decodedBytes, “utf-8″)); Example: Base64 Encoding and Decoding for URL in Java Following example showcases the use of Base64 URL encoder and decoder. We”ve first encoded a simple string using a encoder retrieved using Base64.getUrlEncoder() and then returned encoded string is decoded using decoder retrieved using Base64.getUrlDecoder() method. package com.tutorialspoint; import java.io.UnsupportedEncodingException; import java.util.Base64; public class Base64Tester { public static void main(String[] args) throws UnsupportedEncodingException { String stringToEncode = “TutorialsPoint?java”; // Encode using url encoder String base64encodedString = Base64.getUrlEncoder().encodeToString(stringToEncode.getBytes(“utf-8”)); System.out.println(“Encoded String: ” + base64encodedString); // Decode the base64 encoded string using url decoder byte[] base64decodedBytes = Base64.getUrlDecoder().decode(base64encodedString); // print the decoded string System.out.println(“Decoded String: ” + new String(base64decodedBytes, “utf-8″)); } } Output Let us compile and run the above program, this will produce the following result − Encoded String: VHV0b3JpYWxzUG9pbnQ_amF2YQ== Decoded String: TutorialsPoint?java Base64 Encoding and Decoding for MIME Type Content MIME Base64 encoder encodes the provided string content to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return ”r” followed by a linefeed ”n” as the line separator. No line separator is present to the end of the encoded output. Following is the snippet explaining the use of MIME Base64 encoder. String stringToEncode = “TutorialsPoint?java8”; // Encode using mime encoder String base64encodedString = Base64.getMimeEncoder().encodeToString(stringToEncode.getBytes(“utf-8”)); MIME Base64 decoder decodes the Base64 encoded string by rejecting any character other than A-Za-z0-9+/. It decodes using the MIME type base64 decoding scheme. Following is the snippet explaining the use of Base64 decoder. // Decode the base64 encoded string using basic decoder byte[] base64decodedBytes = Base64.getMIMEDecoder().decode(base64encodedString); // print the decoded string System.out.println(“Original String: ” + new String(base64decodedBytes, “utf-8″)); Example: MIME Base64 Encoding and Decoding in Java Following example showcases the use of Base64 MIME encoder and decoder. We”ve first encoded a simple string using a encoder retrieved using Base64.getMIMEEncoder() and then returned encoded string is decoded using decoder retrieved using Base64.getMIMEDecoder() method. package com.tutorialspoint; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.UUID; public class Base64Tester { public static void main(String[] args) throws UnsupportedEncodingException { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 10; ++i) { stringBuilder.append(UUID.randomUUID().toString()); stringBuilder.append(“,”); } byte[] mimeBytes = stringBuilder.toString().getBytes(“utf-8”); String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes); System.out.println(“Base64 Encoded String (MIME) : ” + mimeEncodedString); // Decode the base64 encoded string using url decoder byte[] base64decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString); // print the decoded string System.out.println(“Decoded String: ” + new String(base64decodedBytes, “utf-8”)); } } Output Let us compile and run the above program, this will produce the following result − Base64 Encoded String (MIME) : NzRmNjkyODktYzJjZS00ZmU2LWEzYTUtMmFlMWRlMDQ1ZjU4LGQyNGQzMTU5LTVmOGUtNDZhMS04 NGRkLTBiMzNlNzc4ZjNiOCw2MmM1OTEzOS1kNmQwLTQ5MmQtYmUyMi01NmEzMTk5NmRkMTAsZDZh NjBlNzctZjRjZi00Y2Q4LTk5MWEtYTY2ZDEzMzU4YjFjLGFlNDhkZmZjLTEwZjctNDk5OS05NTFj LTU5ZGY1MjcyYjczNywxY2JiZjU0Ni0zNjc1LTQ4NzAtYTYxNC01MzkyODFkNjRjYmMsMTlhNTNi ODEtODQ0OS00M2MyLTg4NmMtNDhmZThmZDZmN2E1LDQyNmRhZDE0LTEyNjItNGJhZC1hMWJlLTNm ODc4MWE1YzhiMiw2NjEwMTgzZS03MGNkLTQzZTctOTRkNC0wZDgzZmY1MzhkNWYsOWMxNmMwM2Ut ZWZmZS00Zjg2LWFkYzgtNjc3MThjYTVlYjI2LA== Decoded String: 74f69289-c2ce-4fe6-a3a5-2ae1de045f58,d24d3159-5f8e-46a1-84dd-0b33e778f3b8,62c59139-d6d0-492d-be22-56a31996dd10,d6a60e77-f4cf-4cd8-991a-a66d13358b1c,ae48dffc-10f7-4999-951c-59df5272b737,1cbbf546-3675-4870-a614-539281d64cbc,19a53b81-8449-43c2-886c-48fe8fd6f7a5,426dad14-1262-4bad-a1be-3f8781a5c8b2,6610183e-70cd-43e7-94d4-0d83ff538d5f,9c16c03e-effe-4f86-adc8-67718ca5eb26, Nested Classes of Base64 Class Following classes are provided by Base64 class. Sr.No. Nested class & Description 1 static class Base64.Decoder This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045. 2 static class Base64.Encoder This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Java – Packaging Tools

Java – Packaging Tools ”; Previous Next In Java 14, a new packaging tool, jpackage was introduced to replace javapackager. javapackager was part of JavaFX kit and was introduced in Java 8. As Java 11 onwards, JavaFX is not a standard feature of Java API, javapackager is not a part of the standard offering. jpackage serves this purpose. jpackage enables developers to package the jar file in a native installable format like exe/msi for Windows, pkg/dmg for MacOS and so on. Developer can use jlink to compress the required JDK modules to minimum modules and use the jpackage to create a lightweight image. Need of jpackager When software is to be distributed, the preferred way is to deliver an installable package to the end-user. This installable package generally contains the JDK, the modules, any dependent files, and configurations and provides the user with a familiar way to install the software. Users should not be required to install JRE or JDK as a prerequisite to run the Java application. jpackage handles all these cases and packages all the required files along with JRE/JDK into a native installer. Command Line Options for jpackager jpackage is a command line tool and provides various options to customize installable softwares. Following are some of the features that jpackager provides: Developer can provide a custom icon. Developer can provide a specific location to install the application. Developer can application arguments to be passed to the application, JVM options to be used while launching the application. Developer can set file associations to launch the application. Developer can set option to modify platform-specific menu group options to launch the application. Developer can configure multiple launchers to launch the application. Using XCode, a bundle can be signed as well. This is applicable for MacOS only though. Prerequisite Folowing are the prerequisite to use jpackager tool to prepare a installable. First requirement is to have the JDK and software application. Get platform specific packaging tool as specified below: Windows− To create EXE/MSI Installable, a third party library wix 3.0 or later is required Ubuntu Linux− To create a RPM, DEB package, we need fakeroot package. Red Hat Linux− To create a RPM, DEB package, we require rpm-build package. MacOS− We can create package using Xcode command line tools. -mac-sign option can be used to sign the package and -icon can be used to provide a customized icon. Application package should be prepared as per the platform. For each platform, we”ve to run the command separately. Create a Package We can create the package using following command: Syntax jpackage –input lib –name Tester –main-jar Tester.jar –main-class com.tutorialspoint.Tester –type msi –java-options ”–enable-preview” Where input − folder containing the required libraries. name − name of the installable package main-jar − jar file to be launched to start the application. main-class − name of the main class in the JAR to be launched. If MANIFEST.MF file in the main JAR contains the main class name then this option is not required. type − type of installable. DMG/PKG for MacOS, MSI/EXE options on Windows and DEB/RPM options on Linux. java-options − options for the Java runtime This command will create a MSI file which can be installed on Windows and application can be used like any other software. Example of a Package public class APITester { public static void main(String[] args) { System.out.println(“Welcome to TutorialsPoint.”); } } Compile and Run the program $javac APITester.java $jar cf APITester.jar APITester.class Output For windows executable, you need to download WiX Toolset v3.11.2(wix311-binaries.zip) and add the toolkit to your path. Once jar is created and path is set, put jar in a folder called lib and run the following command to create a windows MSI installer. $jpackage –input lib –name APITester –main-jar APITester.jar –main-class APITester –type msi Print Page Previous Next Advertisements ”;

Java – Dynamic CDS archive

Java – Dynamic CDS ”; Previous Next What is CDS? CDS stands for Class Data Sharing. It was introduced in JDK 5 to improve the startup time of the JVM by loading the pre-processed archive of core class and shared JVM Metadata. When JVM Initializes, it loads set of core classes, for example, java.lang package classes. Using CDS, Java supports creating a pre-processed archive of such core classes so that the normal process of initialization (expand archive, validate class, generate bytecode) can be improved by directly using pre-processed archive. Following command can be used in JDK 5 onwards to create a CDS archive to be used by JVM at startup time. $java -Xshare:dump -cp APITester.jar APITester The CDS archive will be available in JAVA installation directory. $JAVA_HOME/lib/server/classes.jsa or $JAVA_HOME/bin/server/classes.jsa When JVM is initialized and directed to use CDS, this archive will be used to load core classes instead of decompressing and verifying the classes thus improving the startup time. What is Dynamic CDS? CDS, Class Data Sharing is an important feature of JVM to boost the startup time of an application loading. As it allows to share class metadata across different JVMs, it reduces the startup time and memory footprint. Java 10 enhanced CDS by giving AppCDS, application CDS which gave developers access to include application classes in a shared archive. Java 12 set CDS archive as default. But the process of creating a CDS was tedious as developers has to go through multiple trials of their applications to create a class list as first step and then dump that class list into an archive. Then this archive can be used to share metadata between JVMs. From Java 13 onwards, now java has dynamic archiving. Now developers can generate a shared archive at the time of application exit. So trial runs are no more needed. Create Dynamic CDS? Following step showcases to create a dynamic shared archive on top of default system archive using option -XX:ArchiveClassesAtExit and passing the archive name. $java -XX:ArchiveClassesAtExit=sharedApp.jar -cp APITester.jar APITester Once generated the shared archive can be used to run the application using -XX:SharedArchiveFile option. $java -XX:SharedArchiveFile=sharedApp.jar -cp APITester.jar APITester Example Consider the following example − APITester.java public class APITester { public static void main(String[] args) { System.out.println(“Welcome to TutorialsPoint.”); } } Compile and Run the program $javac APITester.java $jar cf APITester.jar APITester.class $java -XX:ArchiveClassesAtExit=sharedApp.jsa -cp APITester.jar APITester $java -XX:SharedArchiveFile=sharedApp.jsa -cp APITester.jar APITester Output Welcome to TutorialsPoint. Print Page Previous Next Advertisements ”;