Message Digests and Password Hashing in Java: SHA-2, SHA-3 and PBKDF2
Fingerprinting data with MessageDigest: what a cryptographic hash guarantees, MD5 and SHA-1 versus SHA-2 and SHA-3, incremental and streamed hashing, HMAC for keyed integrity, and storing passwords safely with salted PBKDF2, constant-time checks, rehashing and the Java 25 KDF API.
kvi5hnuCode Sprout team member12 min readOn this page
A message digest (or cryptographic hash) turns any amount of data into a short, fixed-size value, a fingerprint. Change a single bit of the input and the fingerprint changes beyond recognition. Digests are the building block behind file integrity checks, digital signatures (next article), certificate fingerprints, Git object names and password storage. This article shows how to compute them in Java, which algorithms to use today, and why passwords need something slower than a plain hash.
What a cryptographic hash promises
A hash function suitable for security has three properties:
- Preimage resistance. Given a fingerprint, you cannot find any input that produces it.
- Second-preimage resistance. Given one message, you cannot find a different message with the same fingerprint. This is what stops someone from altering a signed contract.
- Collision resistance. You cannot find any two different messages with the same fingerprint, even when you choose both freely.
Collisions must exist (there are infinitely many inputs and only SHA-256 values), but finding one by brute force would take around attempts for a 256-bit hash, far beyond any computer that exists or is planned. A good hash also shows the avalanche effect: changing one character flips about half of the output bits.
Choosing an algorithm
| Algorithm | Output | Status |
|---|---|---|
| MD5 | 128 bits | Broken. Collisions can be produced in seconds. Only for non-security checksums. |
| SHA-1 | 160 bits | Broken for collisions (first public collision 2017, chosen-prefix collisions 2020). The JDK rejects SHA-1 in signed JARs and TLS certificates. |
| SHA-224, SHA-256, SHA-384, SHA-512 | 224–512 bits | SHA-2 family, the default choice. SHA-256 is the most common. |
| SHA-512/224, SHA-512/256 | 224, 256 bits | SHA-512 internals with a shorter output; fast on 64-bit CPUs and not vulnerable to length extension. |
| SHA3-224 ... SHA3-512 | 224–512 bits | SHA-3 (Keccak), a completely different design, available since Java 9. A good backup if SHA-2 ever weakens. |
| SHAKE128-256, SHAKE256-512 | 256, 512 bits | Extendable-output SHA-3 functions, offered with fixed output lengths. |
Algorithm names are case-insensitive strings. The set available depends on the installed security providers; you can list it at runtime, as the program at the end of this article does. The Java SE specification requires only a small core (SHA-1 and SHA-256 among them), but every OpenJDK build has all of the above.
Computing a digest
MessageDigest is both a factory and the superclass of every digest implementation:
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(data); // one shot
For data that arrives in pieces, feed it with update and finish with digest():
md.update(header);
md.update(body, 0, bodyLength);
byte[] hash = md.digest(); // pads, finishes, and resets md
After digest() the object is reset and ready for a new message; reset() does the same without producing a result. A MessageDigest is not thread-safe, so give each thread its own (they are cheap to create). clone() copies the internal state, which is handy when many messages share a prefix: hash the prefix once, then clone for each ending.
Two helper streams hash data as it passes through: DigestInputStream and DigestOutputStream. To fingerprint a large file without loading it into memory:
try (var in = new DigestInputStream(Files.newInputStream(path), md)) {
in.transferTo(OutputStream.nullOutputStream());
}
byte[] hash = md.digest();
To display hashes, use java.util.HexFormat (Java 17):
String text = HexFormat.of().formatHex(hash); // "01e2e5..."
String pretty = HexFormat.ofDelimiter(":").withUpperCase().formatHex(hash); // "01:E2:E5..."
When you compare a computed hash with an expected one in a security setting, use MessageDigest.isEqual(a, b). Its running time does not depend on the position of the first differing byte, so an attacker cannot learn the correct value byte by byte by timing your responses.
Digests are not enough on their own: HMAC
A digest proves integrity only if the fingerprint itself is safe. If an attacker can change both a file and its published SHA-256 value, nothing is detected: the algorithms are public and need no key. There are two fixes:
- Digital signatures (next article) use a private key to sign the hash, so anyone can verify but only the key holder can sign.
- HMAC (hash-based message authentication code) mixes a shared secret key into the hash. Only parties who know the key can create or check the tag.
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(keyBytes, "HmacSHA256"));
byte[] tag = mac.doFinal(message);
Never build your own keyed hash as SHA-256(key + message). With SHA-256, SHA-512 and the other Merkle–Damgård designs, an attacker who sees that value can compute the hash of key + message + padding + more without knowing the key (a length-extension attack). HMAC, SHA-3 and the truncated SHA-512/256 are not affected.
Hashing passwords
A server must be able to check passwords without storing them. The obvious idea, storing SHA-256(password), is badly wrong for two reasons:
- It is fast. A single GPU computes billions of SHA-256 hashes per second. Once a database leaks, every short or common password falls quickly to guessing.
- Equal passwords give equal hashes. Two users with the password "sunshine" have the same stored value, and precomputed tables of common-password hashes ("rainbow tables") crack them all at once.
The fixes are a salt, a random value of 16 bytes or more stored next to each hash so that every user's hash is different, and a deliberately slow function with a tunable cost. The JDK provides PBKDF2 (password-based key derivation function 2, RFC 8018):
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
var spec = new PBEKeySpec(password, salt, 600_000, 256); // char[], salt, iterations, output bits
byte[] hash = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
spec.clearPassword();
PBKDF2 runs HMAC over and over, the iteration count times. OWASP currently recommends 600,000 iterations for PBKDF2-HMAC-SHA256 (210,000 for HMAC-SHA512). Measure on your hardware and aim for a verification time your login flow can afford.

Store everything needed to check the password again in one record, for example:
pbkdf2-sha256$600000$<salt in base64>$<hash in base64>
To verify a login, parse the record, run PBKDF2 on the typed password with the stored salt and iteration count, and compare with MessageDigest.isEqual. Because the iteration count is in the record, you can raise it later: when a user logs in successfully with an old record, compute a new hash with the current settings and save it. The demo's needsRehash method shows the test.
Handling the password itself
- Keep passwords in
char[], notString, so you can wipe them withArrays.fillafter use. AStringstays in memory until the garbage collector reclaims it.PBEKeySpeccopies the array; callclearPassword()when done. - Give the same error and similar timing for "unknown user" and "wrong password" (article 82's login module does this).
- Rate-limit login attempts. Slow hashing makes offline cracking expensive; it does not stop online guessing.
Deriving keys from keys: the KDF API
Java 25 finalized the Key Derivation Function API (javax.crypto.KDF, JEP 510), with HKDF (RFC 5869) as its first algorithm. HKDF turns already-strong key material, such as the shared secret of a key exchange, into one or more keys for specific purposes. It is fast by design and must not be used on passwords; PBKDF2 stays in SecretKeyFactory.
KDF hkdf = KDF.getInstance("HKDF-SHA256");
var params = HKDFParameterSpec.ofExtract()
.addIKM(sharedSecret).addSalt(salt)
.thenExpand("encryption key v1".getBytes(), 32);
SecretKey key = hkdf.deriveKey("AES", params);
The program
The program lists the digest algorithms of the running JDK, hashes one message with several of them, measures the avalanche effect, hashes in pieces and through a DigestInputStream, computes HMAC tags, and then stores and verifies passwords with salted PBKDF2. The salts are fixed hex values so that the output is the same on every run; the second-to-last section uses SecureRandom, as real code should, and prints only results that do not depend on the random value.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Solution {
static final HexFormat HEX = HexFormat.of();
static String hex(byte[] b) { return HEX.formatHex(b); }
static byte[] utf8(String s) { return s.getBytes(StandardCharsets.UTF_8); }
static byte[] digest(String alg, byte[] data) throws NoSuchAlgorithmException {
return MessageDigest.getInstance(alg).digest(data);
}
static int differentBits(byte[] a, byte[] b) {
int n = 0;
for (int i = 0; i < a.length; i++) n += Integer.bitCount((a[i] ^ b[i]) & 0xFF);
return n;
}
// ---------------------------------------------------------------- password hashing
static final int ITERATIONS = 600_000; // OWASP figure for PBKDF2-HMAC-SHA256
static final int SALT_BYTES = 16, HASH_BYTES = 32;
static byte[] pbkdf2(char[] password, byte[] salt, int iterations) throws GeneralSecurityException {
var spec = new PBEKeySpec(password, salt, iterations, 8 * HASH_BYTES);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
/** Stored form: algorithm$iterations$salt$hash, all text. */
static String hashPassword(char[] password, byte[] salt) throws GeneralSecurityException {
Base64.Encoder b64 = Base64.getEncoder().withoutPadding();
return "pbkdf2-sha256$" + ITERATIONS + "$" + b64.encodeToString(salt) + "$"
+ b64.encodeToString(pbkdf2(password, salt, ITERATIONS));
}
static boolean verify(char[] password, String stored) throws GeneralSecurityException {
String[] parts = stored.split("\\$");
if (parts.length != 4 || !parts[0].equals("pbkdf2-sha256")) return false;
int iterations = Integer.parseInt(parts[1]);
byte[] salt = Base64.getDecoder().decode(parts[2]);
byte[] expected = Base64.getDecoder().decode(parts[3]);
return MessageDigest.isEqual(pbkdf2(password, salt, iterations), expected);
}
static boolean needsRehash(String stored) {
return Integer.parseInt(stored.split("\\$")[1]) < ITERATIONS;
}
public static void main(String[] args) throws Exception {
System.out.println("== MessageDigest algorithms in this JDK ==");
var names = new TreeSet<String>();
for (Provider p : Security.getProviders())
for (Provider.Service s : p.getServices())
if (s.getType().equals("MessageDigest")) names.add(s.getAlgorithm());
System.out.println(names);
System.out.println("\n== Same input, different algorithms ==");
byte[] msg = utf8("Pay Alice 100 euros\n");
for (String alg : List.of("MD5", "SHA-1", "SHA-256", "SHA-512/256", "SHA3-256")) {
byte[] h = digest(alg, msg);
System.out.printf("%-11s %3d bits %s%n", alg, h.length * 8, hex(h));
}
System.out.println("SHA-512 512 bits " + hex(digest("SHA-512", msg)).substring(0, 32) + "...");
System.out.println("\n== The avalanche effect ==");
byte[] a = digest("SHA-256", utf8("Pay Alice 100 euros\n"));
byte[] b = digest("SHA-256", utf8("Pay Alice 900 euros\n"));
System.out.println("100: " + hex(a));
System.out.println("900: " + hex(b));
System.out.println("bits that differ: " + differentBits(a, b) + " of 256");
System.out.println("empty input: " + hex(digest("SHA-256", new byte[0])));
System.out.println("\n== Incremental updates, clone, reset ==");
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(utf8("Pay Alice "));
MessageDigest snapshot = (MessageDigest) md.clone(); // remember state after the prefix
md.update(utf8("100 euros\n"));
System.out.println("pieces == whole: " + Arrays.equals(md.digest(), a));
snapshot.update(utf8("900 euros\n"));
System.out.println("clone continues: " + Arrays.equals(snapshot.digest(), b));
System.out.println("digest length " + md.getDigestLength() + " bytes, provider " + md.getProvider().getName());
System.out.println("\n== Hashing a file as a stream ==");
Path file = Files.createTempFile("digest", ".txt");
try {
Files.write(file, utf8("line\n".repeat(100_000)));
MessageDigest fileMd = MessageDigest.getInstance("SHA-256");
try (var in = new DigestInputStream(new BufferedInputStream(Files.newInputStream(file)), fileMd)) {
in.transferTo(OutputStream.nullOutputStream());
}
byte[] streamed = fileMd.digest();
System.out.println(Files.size(file) + " bytes -> " + hex(streamed));
System.out.println("same as hashing readAllBytes: "
+ Arrays.equals(streamed, digest("SHA-256", Files.readAllBytes(file))));
} finally {
Files.delete(file);
}
System.out.println("\n== Keyed hashes: HMAC ==");
byte[] key = utf8("a key shared by sender and receiver, 32+ bytes");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
byte[] tag = mac.doFinal(msg);
System.out.println("tag: " + hex(tag));
mac.init(new SecretKeySpec(utf8("a different key the attacker guessed......"), "HmacSHA256"));
System.out.println("wrong key: " + hex(mac.doFinal(msg)));
System.out.println("\n== Why plain SHA-256 is wrong for passwords ==");
// Two users with the same password get the same unsalted hash
System.out.println("alice sha256(\"sunshine\") = " + hex(digest("SHA-256", utf8("sunshine"))).substring(0, 24) + "...");
System.out.println("bob sha256(\"sunshine\") = " + hex(digest("SHA-256", utf8("sunshine"))).substring(0, 24) + "...");
System.out.println("\n== PBKDF2 with a salt per user ==");
byte[] saltAlice = HEX.parseHex("6b1f0c55d6a2e03c94f1b2a7c3d8e941"); // fixed so output is repeatable;
byte[] saltBob = HEX.parseHex("0e9d4f7a21c6b58833a0e5d2f6c17b04"); // real code: SecureRandom
String alice = hashPassword("sunshine".toCharArray(), saltAlice);
String bob = hashPassword("sunshine".toCharArray(), saltBob);
System.out.println("alice: " + alice);
System.out.println("bob: " + bob);
System.out.println("alice, \"sunshine\": " + verify("sunshine".toCharArray(), alice));
System.out.println("alice, \"Sunshine\": " + verify("Sunshine".toCharArray(), alice));
System.out.println("\n== Upgrading the work factor ==");
Base64.Encoder b64 = Base64.getEncoder().withoutPadding();
String old = "pbkdf2-sha256$10000$" + b64.encodeToString(saltBob) + "$"
+ b64.encodeToString(pbkdf2("hunter2".toCharArray(), saltBob, 10_000));
System.out.println("old record verifies: " + verify("hunter2".toCharArray(), old)
+ ", needs rehash: " + needsRehash(old));
System.out.println("new record needs rehash: " + needsRehash(alice));
System.out.println("\n== A random salt (the value changes every run) ==");
byte[] salt = new byte[SALT_BYTES];
new SecureRandom().nextBytes(salt);
String r1 = hashPassword("sunshine".toCharArray(), salt);
System.out.println("salt length " + salt.length + ", verifies: " + verify("sunshine".toCharArray(), r1));
System.out.println("\n== HKDF through the KDF API (Java 25): keys from keys, not from passwords ==");
KDF hkdf = KDF.getInstance("HKDF-SHA256");
var params = HKDFParameterSpec.ofExtract()
.addIKM(new SecretKeySpec(HEX.parseHex("000102030405060708090a0b0c0d0e0f"), "Generic"))
.addSalt(utf8("session-salt"))
.thenExpand(utf8("encryption key v1"), 32);
System.out.println("derived: " + hex(hkdf.deriveData(params)));
}
}
== MessageDigest algorithms in this JDK ==
[MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256, SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128-256, SHAKE256-512]
== Same input, different algorithms ==
MD5 128 bits c29313ceeaa0e37cd888dc1239c443ca
SHA-1 160 bits 3188fccd518106648415d1d7e5d0ccdec572e568
SHA-256 256 bits 01e2e542079859e5d7c88df0b854e49506863c8b68fc7498c747ce7e06571fc2
SHA-512/256 256 bits d862402eccbcaef111b30ea627d872344c4e3c2f8a92b7ac0155f3e2fed33b73
SHA3-256 256 bits 018a0c63b5c437c245a46265ea3a31c879f6a07602cb71932e366b492dfe3f50
SHA-512 512 bits 09d23e271c12cc69827dd8f2e81eecf2...
== The avalanche effect ==
100: 01e2e542079859e5d7c88df0b854e49506863c8b68fc7498c747ce7e06571fc2
900: 5ed5091dc63c15f303065ab0193b48e154fa72af29b5eae7eeb1f39d0af640ea
bits that differ: 130 of 256
empty input: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
== Incremental updates, clone, reset ==
pieces == whole: true
clone continues: true
digest length 32 bytes, provider SUN
== Hashing a file as a stream ==
500000 bytes -> b90ce2c5650f20882ee67791841be927fd121163e7c5a5df4d790ab450c87960
same as hashing readAllBytes: true
== Keyed hashes: HMAC ==
tag: c947216c7c80d68d5875317512b85a38b9aecebfa2f0eb896a6301e1d9693df8
wrong key: 0393683252ba42788b5c1c5c42dc60bbd98bc3226a925b96169c9c1f64eeb8f8
== Why plain SHA-256 is wrong for passwords ==
alice sha256("sunshine") = a941a4c4fd0c01cddef61b8b...
bob sha256("sunshine") = a941a4c4fd0c01cddef61b8b...
== PBKDF2 with a salt per user ==
alice: pbkdf2-sha256$600000$ax8MVdai4DyU8bKnw9jpQQ$03moQzMeOXul+wjHlsIdhWCj6gJxSwGmBLZIUPSJ70Y
bob: pbkdf2-sha256$600000$Dp1PeiHGtYgzoOXS9sF7BA$3zWXPmb8/VH7aPqkHX21coBS0r53PYESewCmilT3vX8
alice, "sunshine": true
alice, "Sunshine": false
== Upgrading the work factor ==
old record verifies: true, needs rehash: true
new record needs rehash: false
== A random salt (the value changes every run) ==
salt length 16, verifies: true
== HKDF through the KDF API (Java 25): keys from keys, not from passwords ==
derived: 79e66e14db6697f18d48cd62e45ba7a789b0d32c7f1dcaf4995fd7990d33fed9
Points to notice:
SHA-256of the empty input is alwayse3b0c442...b855; recognizing it in logs often reveals a bug where nothing was hashed.- Changing "100" to "900" flipped 130 of 256 bits, close to the ideal half.
- Alice and Bob chose the same password. Their plain SHA-256 values are identical, but their PBKDF2 records differ completely because the salts differ.
Common questions
Is MD5 or SHA-1 ever acceptable? For non-security uses, such as checksums against accidental corruption or cache keys, they still work. For anything an attacker might target (signatures, certificates, integrity of downloads, passwords), use SHA-256 or stronger. Practical collisions exist for both MD5 and SHA-1.
How do I compute a file's SHA-256 like sha256sum?
Read the file through a DigestInputStream (or feed update with chunks), then print HexFormat.of().formatHex(md.digest()). The result matches sha256sum and shasum -a 256 output.
Can I "decrypt" a hash? No. Hashes are one-way. "Hash crackers" guess inputs and compare hashes, which works only for short or predictable inputs like weak passwords. That's why passwords need salts and slow hash functions.
What iteration count should I use for PBKDF2? OWASP currently suggests 600,000 for PBKDF2-HMAC-SHA256. Time a verification on your production hardware; around a quarter to half a second per login is a common budget. Store the count with the hash so you can raise it later.
Should I use bcrypt, scrypt or Argon2 instead?
If you can add a dependency, Argon2id is the best choice today; bcrypt is fine and widely available (Spring Security's BCryptPasswordEncoder). Use PBKDF2 when you need FIPS compliance or no dependencies.
What's a "pepper"? A secret key, stored outside the database (for example in a hardware security module or the application's configuration), mixed into password hashes with HMAC. It protects hashes if only the database leaks. It complements a salt; it doesn't replace one.
API reference
| Class / method | Purpose |
|---|---|
MessageDigest.getInstance(alg) | Get a digest by name, such as "SHA-256" or "SHA3-256". |
update(byte), update(byte[]), update(byte[], off, len), update(ByteBuffer) | Feed data. |
digest(), digest(byte[]) | Finish and return the hash; resets the object. |
reset(), clone(), getDigestLength(), getAlgorithm(), getProvider() | Manage and inspect the object. |
MessageDigest.isEqual(a, b) | Constant-time comparison. |
DigestInputStream, DigestOutputStream | Hash data while reading or writing it. |
HexFormat.of().formatHex(b) / parseHex(s) | Hex conversion (Java 17). |
Mac.getInstance("HmacSHA256"), init(key), doFinal(data) | Keyed hash (HMAC). |
PBEKeySpec(password, salt, iterations, bits) | Parameters for PBKDF2. |
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded() | Compute a password hash. |
SecureRandom.nextBytes(b) | Random salt. |
KDF.getInstance("HKDF-SHA256"), HKDFParameterSpec, deriveKey, deriveData | Key derivation from strong keys (Java 25). |
Security.getProviders(), Provider.getServices() | List installed algorithms. |
Summary
- A cryptographic hash gives a fixed-size fingerprint; it should resist preimages, second preimages and collisions.
- Use SHA-256 or another SHA-2 or SHA-3 function. MD5 and SHA-1 are broken for security.
MessageDigestsupports one-shot and incremental hashing;digest()resets the object. UseDigestInputStreamfor large files,HexFormatfor display andMessageDigest.isEqualfor comparison.- A plain digest does not protect against an attacker who can replace both data and hash. Use HMAC with a secret key, or a digital signature. Never use
hash(key + message). - Store passwords as salted, slow hashes: PBKDF2-HMAC-SHA256 with about 600,000 iterations, a random 16-byte salt per user, and the parameters stored with the hash so they can be raised later. Argon2id is stronger but needs a library.
- The Java 25 KDF API provides HKDF for deriving keys from strong secrets, never from passwords.
Practice Questions
1. A download page lists a file and its SHA-256 value on the same web server. What does checking the hash protect against, and what does it not?
It detects accidental corruption and tampering on a mirror or in transit, if the hash came from a trustworthy place. If an attacker controls the web server, they can replace both the file and the hash, and the check passes. Protection against that needs a signature made with a key the attacker does not have, such as a signed release file, or a hash obtained over a separate trusted channel.
2. You hash a 4 GB file with md.digest(Files.readAllBytes(path)). What goes wrong, and what should you write instead?
readAllBytes tries to load the whole file into one array; arrays are limited to about 2 GB, so it throws OutOfMemoryError (or needs a huge heap for smaller large files). Stream the data instead: wrap the input stream in a DigestInputStream and call transferTo(OutputStream.nullOutputStream()), or loop over a buffer calling md.update(buffer, 0, n), then call md.digest().
3. Why is SHA-256(secretKey + message) a bad authentication tag, and what should replace it?
SHA-256 is vulnerable to length extension: from the hash of key + message, an attacker can compute a valid hash of key + message + padding + extra without knowing the key, so they can append data and forge a valid tag. Use HMAC (Mac.getInstance("HmacSHA256")), which is designed to be a secure keyed hash.
4. Explain the purpose of the salt and the iteration count in PBKDF2. Why must both be stored with the hash?
The salt makes each user's hash unique even for equal passwords, so an attacker cannot crack many accounts with one guess or use precomputed tables. The iteration count makes each guess expensive. The salt is not secret, and verification needs both values to recompute the same hash from the typed password. Storing the iteration count also lets you raise it over time and rehash users when they next log in.
5. A colleague proposes HKDF from the new KDF API for password hashing because "it is a key derivation function too". What do you say?
HKDF is designed to be fast. It assumes its input already has high entropy (a shared secret from a key exchange, for example) and only extracts and expands it. Passwords have low entropy, so a fast function lets attackers test billions of guesses per second. Passwords need a deliberately slow, salted function: PBKDF2 with a high iteration count, or a memory-hard function such as Argon2id.
Previous: User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
Next: Digital Signatures in Java: Signing and Verifying with RSA, EdDSA and ML-DSA
Related reading
- User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
- Writing a Class Loader and Bytecode Verification in Java
- Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces
- The Java Scripting API: Script Engines, Bindings and Invocable
- Compiling Java Code in Memory: Custom File Objects and Dynamic Code Generation

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.