Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

programs and code snippets to showcase the might of Java platform (Java API and JLS), algorithms implemented using Java language, and types and methods useful for countless projects

NotificationsYou must be signed in to change notification settings

rishiraj88/JavaCoreSnippets

Repository files navigation

  • programs and code snippets to showcase the might and versatility of Java platform (as of Core Java API), algorithms implemented using Java language (out of JavaSE), and the types & methods to refer & use in other projects and repositories

  • First of all, let's have a look at some of the updates and advancements in Java library (aptly called Java API).

What's available in Java 24 API

  • improvement in performance and memory management
    • Generational Shenandoah (garbage collector)JEP-404
  • security and cryptography
    • key derivation function APIJEP-478
    • quantum-resistant DSAJEP-497 and moreJEP-496
  • modernized Java APIsJEP-404
    • ahead-of-time class loading and linkingJEP-483
    • class file APIJEP-484
    • more flexible pipelines with stream gatherersJEP-485
  • JVM changes
    • compact object headersJEP-450
    • restricted use of JNIJEP-472
    • Security Manager is now disabled.JEP-486
  • languages and syntax
    • switch, instanceof and primitive typesJEP-488
    • ScopedValue to share immutable data between caller thread and child threadsJEP-487
    • flexible constructor bodies (with prologue and epilogue)JEP-492
    • module importJEP-494
    • linking runtime image without JMODJEP-493
  • more structured concurrency and threading
  • deprecation and "end-of-life"
    • 32-bit x86 port deprecatedJEP-501
    • removal of support for Windows (32-bit x86)JEP-479

What's available in Java 21 API

New features available in Java 21 which we missed in Java 17 and earlier versions. Features, which are most notable and stand as the best candidates for frequent use, are listed below:

  • Virtual threads (from Java 19)Virtual threads demo
  • Usage ofrecord types in conditionals. Very useful withif(reference instance Type) tests.
if(publicParameter instanceof SpecificType) {}
  • labels forswitch cases. These are very similar toinstanceof checks.
case TierOne test -> future = test.callActionOne();case TierTwo test -> future = test.callActionTwo();
  • String literals (a preview feature) to build parameterized text strings. These are similar to string literals / template strings of modern JavaScript and f-strings of python. The template processorSTR is automatically imported and is available to use without any explicit import or declaration. More template processors includeRAW andFMT. Remember"fmt" of Go (Golang)?
String vmUserName = localSystem.retrieveUserName();String helloVitrualWorld = STR."Hola \{vmUserName}";
  • One major pathchanger about Java Collection Framework is: the introduction of "sequenced collections":SequencedCollection,SequencedSet andSequencedMap.
public interface SequencedCollection extends Collection // since 21public interface SequencedMap extends Map // since 21public interface SequencedSet extends SequencedCollection, Set // since 21
  • My favorite as it is about security and encryption: Key Encapsulation Mechanism (KEP) to secure symmetric keys.
  • TODO: Add updated screenshots
  • Implementation examples are in the project code underJava21API along with the checklist of which of the features have been tested.

What's available in Java 17 API

New features available in Java 17 over Java 14. Features, which are most notable and stand as the best candidates for frequent use, are listed below:

  • restore always-Strict floating-point semantics: It ensures same results of floating-point calculations on every platform.
  • enhanced pseudo-random number generators: class java.util.Random implements interface java.util.random.RandomGenerator. Such new implementations of pseudo random number generators allow for better support for stream-based programming.
  • new macOS rendering pipeline
  • macOS/AArch64 port
  • deprecate the Applet API for removal
  • strongly encapsulate JDK internals
  • pattern matching for switch (preview)Pattern matching with switch
  • remove RMI activation
  • sealed classes
  • remove the experimental AOT and JIT compilers
  • deprecate the Security Manager for removal
  • Foreign Function and Memory API (incubator)
  • Vector API (second incubator)
  • context-specific deserialization filters

TODO

To add the screenshots for Java 17 features to README for quick illustration. Screenshots are already inassets directory.

What's available in Java 14 API

The additional and formally introduced features available in Java 14. These are the features added to JLS in the versions later to version 11. Most frequently used features are:

  • Enhancedinstanceof operator for safe type conversion: Now useif (obj instanceof String str) instead ofif (obj instanceof String) to get a pre-cooked variablestr of typeString, for example, to utilise inside the concerned code block.InstanceOf Pattern Matching
  • More explanatory NullPointerException message. Run the super-methodmain ofNullPointerExceptionPlus to get:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.toString()" because the return value of "java14.RoleClass.getPrivileges()" is nullat java14.NullPointerExceptionPlus.main(NullPointerExceptionPlus.java:7)

NullPointerExceptionNullPointerException

  • Record as a Type: a smarter tool to fulfill the need of final classes. Example:record UserRecord(String name, String userId, int pin) {}Record as a Type
  • More consiceswitch. It returns a value, so it is aptly called a switch expression. Example:
return switch(inputNumber) {case 0 -> "zero";case 1,3,5,7,9 -> "odd";case 2,4,6,8,10 -> "even";default -> "Go take some rest.";};

switch Expression

  • Text block to assign pre-formatted, with indentation, literal value to a String reference. The value can be supplied without using a reference variable, too. Example:
String strTextBlock = """Das sind die 10 besten Arbeitgeber:innen Deutschlands    Platz 1: dm-drogerie markt GmbH + Co. KG    Platz 2: Techniker Krankenkasse    Platz 3: Ford-Werke GmbH    Platz 4: Porsche AG    Platz 5: Evonik Industries AG    Platz 6: Merck KgaA    Platz 7: Bayer AG    Platz 8: BMW Group    Platz 9: Deloitte    Patz 10: Roche Deutschland Holding GmbHUnd diese Arbeitgeber:innen sind f�r Frauen am bestenFazit: Es lohnt sich Firmen-Bewertungen zu checken""";

TextBlock for preformatted String literalsTextBlock for preformatted String literals

Java 11 API

The nice features available in Java 11 over our good old friend Java 8. Most notable additions are:

  • MethodT[] Collection.toArray(IntFunction<T[]> generator ) to use instead of first generating a stream and then invokingA[] Stream.toArray(IntFunction<A[]> generator);Collection toArray(generator)
  • MethodsString Files.readString(Path.of(filePath)) andPath Files.writeString(Path.of(strFilePath),"string content", StandardOpenOption).Files methods: readString() and writeString()
  • Classjava.net.http.HttpClient capable of making GET, PUT, POST requests easily.Convenient HttpClientConvenient HttpClient
  • Running a Java class directly withjava command as in$ java MainClass.java without generating a.class file a priori.Running Java program with java interpreter command directly
  • Usage ofvar keyword for variable declaration in lambda expressions: (@Nonnull var a,@Nullable var b) -> System.out.println(a + b)Local var declaration in lambda
  • MethodOptional.isEmpty() to check if the contained value is null. Its definition straight from Java API is:public boolean isEmpty() { return value == null; }Optional isEmpty() method
  • A number of new methods foster our most-loved classjava.lang.String. These are:isBlank(),strip(),stripLeading(),stripTrailing(),repeat(intCount)New methods in String classNew methods in String class

Java Core Snippets

Code fragments and executable programs testing many variants and conditions with standard language features of Java API. Some of the.java files here are:

  • ArrayIntersection.java
  • DefaultElementValue.java
  • ExceptionsFinally.java
  • FindDuplicatesInArrayByMap.java
  • FindDuplicatesInArrayByStream.java
  • Main.java
  • MainInterface.java
  • MedianOfTwoArrays.java
  • SecondLargest.java
  • SingleInArray.java
  • StreamCollectMethods.java
  • SuperThisChild.java
  • ZeroAndNonZero.java
  • innerclasses/{InnerClassInitInOuterClass.java}
  • stream/{Address.java Customer.java StreamMappingDemo.java}

Gists

Guidelines on the preferred usage of major Java 8 features and API methods:

  • Java 8 DateTime code samples.md
  • Java 8 Functional Interfaces in Java API.md
  • Java Concurrency API.md
  • Java Stream collector-s methods.md

Notes

  • PoC implementations of the gists will keep on adding gradually.

About

programs and code snippets to showcase the might of Java platform (Java API and JLS), algorithms implemented using Java language, and types and methods useful for countless projects

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp