Java – Enumeration Interface ”; Previous Next The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code. Enumeration Interface Methods The methods declared by Enumeration are summarized in the following table − Sr.No. Method & Description 1 boolean hasMoreElements( ) When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated. 2 Object nextElement( ) This returns the next object in the enumeration as a generic Object reference. Example 1: Enumeration for Vector Following is an example showing usage of Enumeration for a Vector. import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration<String> days; Vector<String> dayNames = new Vector<>(); dayNames.add(“Sunday”); dayNames.add(“Monday”); dayNames.add(“Tuesday”); dayNames.add(“Wednesday”); dayNames.add(“Thursday”); dayNames.add(“Friday”); dayNames.add(“Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday Example 2: Enumeration for properties Following is an example showing usage of Enumeration for Properties to print the values. import java.util.Vector; import java.util.Enumeration; import java.util.Properties; public class EnumerationTester { public static void main(String args[]) { Enumeration<Object> days; Properties dayNames = new Properties(); dayNames.put(1, “Sunday”); dayNames.put(2,”Monday”); dayNames.put(3,”Tuesday”); dayNames.put(4,”Wednesday”); dayNames.put(5,”Thursday”); dayNames.put(6,”Friday”); dayNames.put(7,”Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday java_data_structures.htm Print Page Previous Next Advertisements ”;
Category: Java
Java – Strings
Java – Strings Class ”; Previous Next Description 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. Creating String from Char Array Example 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 ); } } This will produce the following result − 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. Getting Length of the String Example 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 − Concatenating String Example 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 Formatted 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 − Formatted String Example 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); String Methods Here is the list of methods supported by String class − 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 static String copyValueOf(char[] data) This method returns a String that represents the character sequence in the array specified. 11 boolean endsWith(String suffix) This method tests if this string ends with the specified suffix. 12 boolean equals(Object anObject) This method compares this string to the specified object. 13 boolean equalsIgnoreCase(String anotherString) This method compares this String to another String, ignoring case considerations. 14 static String format(String format, Object… args) This method returns a formatted string using the specified format string and arguments. 15 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. 16 void getChars(int srcBegin, int
Java – Stream API Improvements ”; Previous Next Streams were introduced in Java to help developers perform aggregate operations from a sequence of objects. With Java 9, few more methods are added to make streams better. takeWhile(Predicate Interface) Method Syntax default Stream<T> takeWhile(Predicate<? super T> predicate) takeWhile method takes all the values until the predicate returns false. It returns, in case of ordered stream, a stream consisting of the longest prefix of elements taken from this stream matching the given predicate. Example package com.tutorialspoint; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { Stream.of(“a”,”b”,”c”,””,”e”,”f”).takeWhile(s->!s.isEmpty()) .forEach(System.out::print); } } Output takeWhile method takes all a, b, and c values, then once string is empty, it stopped executing. abc dropWhile(Predicate Interface) Syntax default Stream<T> dropWhile(Predicate<? super T> predicate) dropWhile method throw away all the values at the start until the predicate returns true. It returns, in case of ordered stream, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements matching the given predicate. Example package com.tutorialspoint; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { Stream.of(“a”,”b”,”c”,””,”e”,”f”).dropWhile(s-> !s.isEmpty()) .forEach(System.out::print); System.out.println(); Stream.of(“a”,”b”,”c”,””,”e”,””,”f”).dropWhile(s-> !s.isEmpty()) .forEach(System.out::print); } } Output dropWhile method drops a,b and c values, then once string is empty, it takes all the values. ef ef iterate Method Syntax static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) iterate method now has hasNext predicate as parameter which stops the loop once hasNext predicate returns false. Example package com.tutorialspoint; import java.util.stream.IntStream; public class Tester { public static void main(String[] args) { IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println); } } Output 3 6 9 ofNullable Syntax static <T> Stream<T> ofNullable(T t) ofNullable method is introduced to prevent NullPointerExceptions and to avoid null checks for streams. This method returns a sequential Stream containing single element, if non-null, otherwise returns an empty Stream. Example package com.tutorialspoint; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { long count = Stream.ofNullable(100).count(); System.out.println(count); count = Stream.ofNullable(null).count(); System.out.println(count); } } Output 1 0 Print Page Previous Next Advertisements ”;
Java 8 – New Features
Java 8 – New Features ”; Previous Next JAVA 8 is a major feature release of JAVA programming language development. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided supports for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc. Following is the list of new features supported in Java 8: Lambda Expressions Lambda expression is one of the biggest feature introduced in Java. A lambda expression facilitates functional programming in Java. A lambda expression works on the principle of functional interface. A Functional interface is an interface with only one method to implement. A lambda expression provides an implementation of the functional interface method. Lambda expression simplifies functional programming a lot and makes code readable without any boilerplate code. A lambda expression can infer the type of parameter used and can return a value without a return keyword. In the case of the simple one-statement method, even curly braces can be eliminated. Example – Using Lambda Expressions Following example showcases the use of lambda expression. A lambda expression works best with a functional interface, an interface with single abstract method. We”ve defined one interface Calculator with single method operate, which can accept two parameters and return a value. In main method, we”ve implemented the Calculator interface using anonymous function first and then using a lambda expression. The operate() method is called to print the result in both cases and results are printed. package com.tutorialspoint; public class Tester { public static void main(String[] args) { // Interface implementation using anonymous class Calculator sum = new Calculator() { @Override public int operate(int a, int b) { return a + b; } }; int result = sum.operate(2,3); System.out.println(result); // Interface implementation using lambda expression Calculator sum1 = (a,b) -> a + b; result = sum1.operate(2,3); System.out.println(result); } interface Calculator { int operate(int a, int b); } } Let us compile and run the above program, this will produce the following result − 5 5 Method References Method reference is a short and concise way to call methods, static methods and even constructors without any lengthy syntax. Method references help to point to methods by their names even without specifying the arguments. Arguments are passed by the lambda expression. A method reference is described using “::” symbol. A static method can be referred using following syntax: <<class-name>>::methodName An instance method can be referred using following syntax: <<object-name>>::methodName We can invoke constructor using following syntax: <<class-name>>::new Example – Using Method References In this example, we”ve used a static method compare and an instance method compareTo to sort two arraylist of integers. We”ve used method references to represent both static and instance methods. package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class Tester { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1,2,4,9,8,7,3); System.out.println(“Sorted using static method reference”); // Use static method compare numbers = numbers.stream().sorted(Integer::compare).toList(); System.out.println(numbers); numbers = Arrays.asList(1,2,4,9,8,7,3); System.out.println(“Sorted using instance method reference” ); // Use instance method compareTo numbers = numbers.stream().sorted(Integer::compareTo).toList(); System.out.println(numbers); } } Let us compile and run the above program, this will produce the following result − Sorted using static method reference [1, 2, 3, 4, 7, 8, 9] Sorted using instance method reference [1, 2, 3, 4, 7, 8, 9] Default Methods Before Java 8, an interface could have only abstract methods. With Java 8, lambda expression were introduced. Now for backward compatability, default method capability was added so that old interfaces can leverage lambda expression without modifying their implementations. For example, List or Collection interfaces do not have ”forEach” method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same. Syntax The following is the syntax of the default method in interface in Java − public interface vehicle { default void message() { System.out.println(“I am a vehicle!”); } } Example – Using Default Method In this example, we”ve created an interface with a default method. In an implementing class, this message is not implemented and is used to print a message. package com.tutorialspoint; interface vehicle { // default method must have an implementation default void message() { System.out.println(“I am a vehicle!”); } } // implementing class need not to implement the default method // of an interface. public class Tester implements vehicle { public static void main(String args[]) { Tester tester = new Tester(); // implementing class can access the default method as its own method tester.message(); } } Let us compile and run the above program, this will produce the following result − I am a vehicle! Stream API Stream API is a new abstract layer introduced in Java 8 to process data in a declarative way. A stream represents a sequence of elements. A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on and can do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. Syntax Following is the generic syntax to use a stream <<collection-instance>>.stream().<<non-terminal-operation()>>.<<non-terminal-operation()>>.<<terminal-operation()>> Example – Using Stream In this example, we”ve created a list of strings where few entries are empty. Now using stream API, we”re filtering the empty strings and counting them. package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class Tester { public static void main(String args[]) { List<String> strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); // get stream from list using stream() method // then apply filter // lastly count the result of filter long count = strings.stream().filter(string->string.isEmpty()).count(); System.out.println(“Empty Strings: ” + count); } } Let us compile and run the above program, this will produce the following result − Empty Strings: 2 Optional Class Optional class feature was introduced in java 8 to handle Null
Java – Process API Improvements ”; Previous Next In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process”s native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes” liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits. Spawning a new Process Example In this example, we”ve created a new Process for notepad and started it using ProcessBuilder. Using ProcessHandle.Info interface, we”re getting the process information of the newly spawned process. package com.tutorialspoint; import java.time.ZoneId; import java.util.stream.Stream; import java.util.stream.Collectors; import java.io.IOException; public class Tester { public static void main(String[] args) throws IOException { ProcessBuilder pb = new ProcessBuilder(“notepad.exe”); String np = “Not Present”; Process p = pb.start(); ProcessHandle.Info info = p.info(); System.out.printf(“Process ID : %s%n”, p.pid()); System.out.printf(“Command name : %s%n”, info.command().orElse(np)); System.out.printf(“Command line : %s%n”, info.commandLine().orElse(np)); System.out.printf(“Start time: %s%n”, info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()) .toLocalDateTime().toString()).orElse(np)); System.out.printf(“Arguments : %s%n”, info.arguments().map(a -> Stream.of(a).collect( Collectors.joining(” “))).orElse(np)); System.out.printf(“User : %s%n”, info.user().orElse(np)); } } Output You will see the similar output. Process ID : 5580 Command name : C:Program FilesWindowsAppsMicrosoft.WindowsNotepad_11.2401.26.0_x64__8wekyb3d8bbweNotepadNotepad.exe Command line : Not Present Start time: 2024-04-02T17:07:14.305 Arguments : Not Present User : DESKTOPTutorialspoint Getting Current Process Information Example In this example, we”ve getting current process using ProcessHandle.current() method. Then using ProcessHandle.Info interface, we”re getting the process information of the current process. package com.tutorialspoint; import java.time.ZoneId; import java.util.stream.Stream; import java.util.stream.Collectors; import java.io.IOException; public class Tester { public static void main(String[] args) throws IOException { String np = “Not Present”; ProcessHandle currentProcess = ProcessHandle.current(); ProcessHandle.Info info = currentProcess.info(); System.out.printf(“Process ID : %s%n”, currentProcess.pid()); System.out.printf(“Command name : %s%n”, info.command().orElse(np)); System.out.printf(“Command line : %s%n”, info.commandLine().orElse(np)); System.out.printf(“Start time: %s%n”, info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()) .toLocalDateTime().toString()).orElse(np)); System.out.printf(“Arguments : %s%n”, info.arguments().map(a -> Stream.of(a).collect( Collectors.joining(” “))).orElse(np)); System.out.printf(“User : %s%n”, info.user().orElse(np)); } } Output You will see the similar output. Process ID : 5352 Command name : C:Program FilesJavajdk-21binjavaw.exe Command line : Not Present Start time: 2024-04-02T17:09:17.902 Arguments : Not Present User : DESKTOP-DTHL8BITutorialspoint Getting Child Processes Example In this example, we”ve getting current process chid processes using ProcessHandle.current().children() method. Then using ProcessHandle.Info interface, we”re getting the process information of the child processes. package com.tutorialspoint; import java.io.IOException; import java.util.stream.Stream; public class Tester { public static void main(String[] args) throws IOException { for (int i = 0; i < 3; i++) { ProcessBuilder processBuilder = new ProcessBuilder(“java.exe”, “-version”); processBuilder.inheritIO().start(); } Stream<ProcessHandle> childProcesses = ProcessHandle.current().children(); String np = “Not Present”; childProcesses.filter(ProcessHandle::isAlive).forEach( childProcess ->{ System.out.printf(“Process ID : %s%n”, childProcess.pid()); System.out.printf(“Command name : %s%n”, childProcess.info().command().orElse(np)); System.out.printf(“Command line : %s%n”, childProcess.info().commandLine().orElse(np)); } ); } } Output You will see the similar output. Process ID : 5420 Command name : C:Program FilesJavajdk-21binjava.exe Command line : Not Present Process ID : 15796 Command name : C:Program FilesJavajdk-21binjava.exe Command line : Not Present Process ID : 14180 Command name : C:Program FilesJavajdk-21binjava.exe Command line : Not Present java version “21.0.2” 2024-01-16 LTS Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58) Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing) java version “21.0.2” 2024-01-16 LTS Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58) Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing) java version “21.0.2” 2024-01-16 LTS Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58) Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing) Print Page Previous Next Advertisements ”;
AWT Tutorial
AWT Tutorial PDF Version Quick Guide Resources Job Search Discussion JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way. In this article we”ll look in AWT (Abstract Window Toolkit). Audience This tutorial is designed for Software Professionals who are willing to learn JAVA GUI Programming in simple and easy steps. This tutorial will give you great understanding on JAVA GUI Programming concepts and after completing this tutorial you will be at intermediate level of expertise from where you can take yourself at higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a basic understanding of Java programming language, text editor and execution of programs etc. Print Page Previous Next Advertisements ”;
Java – Serialization
Java – Serialization ”; Previous Next Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object”s data as well as information about the object”s type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform. Methods for Serializing and Deserializing an Object Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out − Syntax public final void writeObject(Object x) throws IOException The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object − Syntax public final Object readObject() throws IOException, ClassNotFoundException This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type. How Serialization Works in Java? To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface − Example to Demonstrate Working of Serialization in Java public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println(“Mailing a check to ” + name + ” ” + address); } } Notice that for a class to be serialized successfully, two conditions must be met − The class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it”s not. Serializing an Object The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file. When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing. Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension. Example for Serializing an Object import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = “Reyan Ali”; e.address = “Phokka Kuan, Ambehta Peer”; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream(“employee.ser”); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf(“Serialized data is saved in /tmp/employee.ser”); } catch (IOException i) { i.printStackTrace(); } } } class Employee implements java.io.Serializable { private static final long serialVersionUID = 1L; public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println(“Mailing a check to ” + name + ” ” + address); } } Output Serialized data is saved in employee.ser Deserializing an Object The following DeserializeDemo program deserializes the Employee object created in the earlier program. Study the program and try to determine its output − Example for Deserializing an Object import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream(“employee.ser”); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println(“Employee class not found”); c.printStackTrace(); return; } System.out.println(“Deserialized Employee…”); System.out.println(“Name: ” + e.name); System.out.println(“Address: ” + e.address); System.out.println(“SSN: ” + e.SSN); System.out.println(“Number: ” + e.number); } } class Employee implements java.io.Serializable { private static final long serialVersionUID = 1L; public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println(“Mailing a check to ” + name + ” ” + address); } } Output Deserialized Employee… Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101 Importing Points About Serialization in Java Here are following important points to be noted − The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can”t find a class during the deserialization of an object, it throws a ClassNotFoundException. Notice that the return value of readObject() is cast to an Employee reference. The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0. Print Page Previous Next Advertisements ”;
Java 11 – New Features
Java 11 – New Features ”; Previous Next Java 11 is the first LTS , Long Term Support feature release after Java 8. It followed the Java release cadence introduced Java 10 onwards and it was released on Sept 2018, just six months after Java 10 release. Java 9 and Java 10 are non-LTS release. Java 11 release is a LTS release. New Features Following are the major new features which are introduced in Java 11. JEP 321 − HTTP Client API standardized. JEP 330 − Launch Single-File Source-Code Programs without compilation JEP 323 − Local-Variable Syntax for Lambda Parameters JEP 181 − Nest-Based Access Control JEP 331 − Low-Overhead Heap Profiling JEP 318 − Epsilon, A No-Op Garbage Collector JEP 333 − ZGC A Scalable Low-Latency Garbage Collector Collection API Updates − New Collection.toArray(IntFunction) Default Method. String API Updates − New methods added like repeat(), isBlank(), strip() and lines(). Files API Updates − New methods added like readString(), and writeString(). Optional Updates − New method added, isEmpty(). Java 11 enhanced numerous APIs with new methods and options and removed deprecated APIs and options. We”ll see these changes in next chapters. Useful Links Java 11 Not Predicate Java 11 Removal Deprecation APIs Print Page Previous Next Advertisements ”;
Java 16 – New Features
Java 16 – New Features ”; Previous Next Java 16 is a major feature release and it has brought many JVM specific changes and language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was released on Mar 2021, just six months after Java 15 release. Java 16 is a non-LTS release. New Features in Java 16 Following are the major new features which are introduced in Java 16. JEP 338 – Vector API (Incubator) − New Vector APIs introduced allowing developers to perform the vector operations explicitly. JEP 347 – Enable C++14 Language Features − C++ 14 features can be used in c++ source code with the JDK 16. JEP 357, JEP 369 – Migrate from Mercurial to Git/GitHub − OpenJDK source code is moved from mercurial to Git/GitHub JEP 376 – ZGC – Concurrent Thread-Stack Processing − Z Garbage Collector improved by moving its thread-stack processing from safepoints to concurrent phase. JEP 380 – Unix-Domain Socket Channels − SocketChannel and ServerSocketChannel now supports Unix Domain sockets. JEP 386 – Alpine Linux Port − Now JDK is available for Alpine Linux and other Linux distributions which use musl implementation. JEP 387 – Elastic Metaspace − Metaspace memory management is improved by returning unused HotSpot class-metadata or metaspace memory to the operating system quickly, reduces the metaspace footprint, and simplify the metaspace code. JEP 388 – Windows/AArch64 Port − Now JDK can run on AArch64, on ARM hardware server or ARM based laptops. JEP 389 – Foreign Linker API (Incubator) − Java code can be called by C/C++ or vice versa using new API replacing the JNI. JEP 390 – Warnings for Value-Based Classes − Warnings are raised in case of value-based classes are synchronised using synchronize. JEP 392 – Packaging Tool − jpackage is now a standard instead of incubator feature. JEP 393 – Foreign-Memory Access API (Third Incubator) − Minor enhancements to Foreign Memory Access API. JEP 394 – Pattern Matching for instanceof − Pattern matching for instanceOf is now a standard feature. JEP 395 – Records − records are now a standard feature. JEP 396 – Strongly Encapsulate JDK Internals by Default − default mode of –illegal-access option is now deny. Earlier it was permit. JEP 397 – Sealed Classes (Second Preview) − Minor enhancements to sealed classes. Print Page Previous Next Advertisements ”;
Java – Hidden Classes
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 ”;