Java – Hidden Classes ”; Previous Next Java 15 has introduced hidden classes which cannot be used directly by other classes bytecode. These hidden classes are intended to be used by frameworks that generate classes at runtime and use them using reflection. A hidden class is defined as a member of the Based Access Control Context and it can be unloaded irrespective of other classes. This proposal, JEP 371, aims at the improvement of all languages on JVM by providing a standard API to define hidden classes that are not discoverable and have a limited lifecycle. JDK frameworks or external frameworks can generate classes dynamically which can generate hidden classes. JVM languages rely heavily on dynamic class generation for flexibility and efficiency. Goals Following is the list of targetted goals of this enhancement: Frameworks should be able to define classes as non-discoverable implementation details of the framework, These classes can neither be linked to other classes nor discoverable using reflection. Extend Access Control Nest with non-discoverable classes. Aggressive unloading of hidden classes will help frameworks to define as many hidden classes as required without degrading the performance. Deprecate the non-standard API, misc.Unsafe::defineAnonymousClass, to be removed in future releases. Creating a Hidden Class In order to create a hidden class, we must create a Lookup instance as shown below: MethodHandles.Lookup lookup = MethodHandles.lookup(); Once lookup instance is available, we can use defineHiddenClass() method to create hidden class using bytearray of hidden class. Class<?> hiddenClass = lookup.defineHiddenClass(getByteArray(), true, ClassOption.NESTMATE).lookupClass(); Bytearray of hidden class can be retrieved using classpath of the hidden class. public static byte[] getByteArray() throws IOException { InputStream stream = Util.class.getClassLoader().getResourceAsStream(“com/tutorialspoint/Util.class”); byte[] bytes = stream.readAllBytes(); return bytes; } Once hiddenClass class is loaded, we can create its instance using getConstructor() method. Object hiddenClassObj = hiddenClass.getConstructor().newInstance(); Using hidden class instance, we can get the method and then execute it as shown below: Method method = hiddenClassObj.getClass().getDeclaredMethod(“square”, Integer.class); // call the method and get result Object result = method.invoke(hiddenClassObj, 3); As hidden class is hidden and cannot be instantiated using reflection, its hidden property is true and canonical name is null. Example to Create and Use a Hidden Class Following example shows the creation and use of a hidden class. First we”ve created a public class Util as shown below: package com.tutorialspoint; public class Util { public Integer square(Integer n) { return n * n; } } Now we”ve created this class as a hidden class and accesed its method to get the square of a number. package com.tutorialspoint; import java.io.IOException; import java.io.InputStream; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup.ClassOption; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Tester { public static void main(String args[]) throws IllegalAccessException, IOException, InstantiationException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { // create the lookup object MethodHandles.Lookup lookup = MethodHandles.lookup(); // define the hidden class using the byte array of Util class // Using NESTMATE option so that hidden class has access to // private members of classes in same nest Class<?> hiddenClass = lookup.defineHiddenClass(getByteArray(), true, ClassOption.NESTMATE).lookupClass(); // get the hidden class object Object hiddenClassObj = hiddenClass.getConstructor().newInstance(); // get the hidden class method Method method = hiddenClassObj.getClass().getDeclaredMethod(“square”, Integer.class); // call the method and get result Object result = method.invoke(hiddenClassObj, 3); // print the result System.out.println(result); // as hidden class is not visible to jvm, it will print hidden System.out.println(hiddenClass.isHidden()); // canonical name is null thus this class cannot be instantiated using reflection System.out.println(hiddenClass.getCanonicalName()); } public static byte[] getByteArray() throws IOException { InputStream stream = Util.class.getClassLoader().getResourceAsStream(“com/tutorialspoint/Util.class”); byte[] bytes = stream.readAllBytes(); return bytes; } } Let us compile and run the above program, this will produce the following result − 9 true null Print Page Previous Next Advertisements ”;
Category: Java
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 – Multi-catch Block
Java Multiple Catch Blocks ”; Previous Next Multiple Catch Blocks in Java Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown from a particular code section. A try block can have multiple catch blocks to handle multiple exceptions. Syntax: Multiple Catch Blocks try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Points to Remember while using Multiple Catch Blocks Only one type of exception can be handled at a time. In protected, only one type of exception will be raised, so it will be handled in relevant catch block only. Order of catch block is very important. Order should be from specific exception to generic one. In case of parent exception block comes before the child exception block, compiler will complain and will throw compile time error. Example of Java Multiple Catch Blocks Here is code segment showing how to use multiple try/catch statements. In this example, we”re creating an error by dividing a value by 0. As it is not an ArrayIndexOutOfBoundsException, next catch block handles the exception and prints the details. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“ArrayIndexOutOfBoundsException thrown :” + e); }catch (Exception e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Handling Multiple Exceptions Using Multiple Catch Blocks In this code segment, we”re showing how to use another example of multiple try/catch statements. In this example, we”re creating an error by dividing a value by 0 and handling it using ArithmeticException. Example package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArithmeticException e) { System.out.println(“ArithmeticException thrown :” + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“ArrayIndexOutOfBoundsException thrown :” + e); }catch (Exception e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output ArithmeticException thrown :java.lang.ArithmeticException: / by zero Out of the block Handling Multiple Exceptions Within A Single Catch Block Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it − Syntax catch (IOException|FileNotFoundException ex) { logger.log(ex); throw ex; Example Here is code segment showing how to use multiple catch in a single statement. In this example, we”re creating an error by dividing a value by 0. In single statement, we”re handling ArrayIndexOutOfBoundsException and ArithmeticException. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Print Page Previous Next Advertisements ”;
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 ”;