Text Boundaries, Line Endings, Console and Encodings in Java
Splitting text correctly with BreakIterator and grapheme clusters, handling line endings, choosing and detecting character encodings after UTF-8 became the default (JEP 400), console encodings, stdin and stdout properties, strict decoding, the UTF-8 byte order mark, and the encoding of source files.
kvi5hnuCode Sprout team member12 min readOn this page
Java strings are Unicode, but the outside world is not that tidy. Text must be cut into characters, words, sentences and lines according to language rules. Files and consoles use byte encodings that may not be UTF-8. Line endings differ between platforms, and some files start with an invisible byte order mark. This article collects these "text at the edges" problems and the APIs that handle them.
What is a character?
Java offers three different answers, and they disagree as soon as text goes beyond basic Latin:

- A
charis a UTF-16 code unit.length()andcharAtcount these. Characters outside the Basic Multilingual Plane, including most emoji, take two code units (a surrogate pair). - A code point is one Unicode character number.
codePointCount,codePoints()andCharacter.toCharswork with these. - A grapheme cluster is what a reader perceives as one character:
efollowed by a combining accent, a family emoji made of three people joined by zero-width joiners, a flag made of two regional indicator symbols.
For the string é 👨👩👧 🇩🇪 (with a decomposed é), the counts are 16 code units, 11 code points and 5 grapheme clusters. Any operation that a user can see, such as truncating a name to 20 "characters", moving a cursor, reversing a string or counting characters for a text limit, should work on grapheme clusters. StringBuilder.reverse handles surrogate pairs but not combining marks: reversing é + a moves the accent onto the wrong letter.
Three ways to find grapheme clusters:
String[] clusters = s.split("\\b{g}"); // regex boundary
Matcher m = Pattern.compile("\\X").matcher(s); // one cluster per match
BreakIterator it = BreakIterator.getCharacterInstance(locale);
BreakIterator
java.text.BreakIterator finds boundaries in text. There are four kinds, each from a static factory that takes an optional locale:
| Factory | Boundaries between |
|---|---|
getCharacterInstance | grapheme clusters |
getWordInstance | words and the runs of spaces and punctuation between them |
getSentenceInstance | sentences |
getLineInstance | positions where a line may be wrapped |
The iteration protocol is old-fashioned: call setText, then first() and next() until next() returns BreakIterator.DONE. Each pair of consecutive positions delimits a segment:
BreakIterator it = BreakIterator.getSentenceInstance(locale);
it.setText(text);
for (int start = it.first(), end = it.next(); end != BreakIterator.DONE;
start = end, end = it.next()) {
String sentence = text.substring(start, end);
}
There are also last()/previous() for going backwards, following(offset) and preceding(offset) for the boundary nearest a position, and isBoundary(offset).
What the iterators do and do not do:
- Words. The word iterator returns both words and separators; you decide which segments to keep, for example those that contain a letter or digit. It keeps
Don't,e-mailand3.14together but splitsC++intoCand++. For Thai, which is written without spaces, the locale-specific iterator uses a dictionary to find words. - Sentences. The rules are statistical, not linguistic.
9 a.m. Thenis handled correctly, but in English the abbreviationMr.followed by a capitalized name ends a sentence. Treat sentence boundaries as a good guess. - Lines. The line iterator gives legal wrap points (after spaces, after hyphens, between CJK characters). Your code decides which one to use for a given width; the demo contains a small word-wrap function.
The JDK's break iterators are based on Unicode rules but are not updated as aggressively as ICU's. For demanding text processing, ICU4J's BreakIterator follows the latest Unicode segmentation rules (UAX #29).
Line endings
Windows text files traditionally end lines with \r\n, Unix-like systems with \n, and very old Mac files with \r. Java handles this on input:
BufferedReader.readLine,Files.readAllLines,Files.linesandString.lines()accept all three terminators and strip them.split("\n")does not: on a Windows file, each line keeps a trailing\r. Usesplit("\\R"), where\Rmatches any Unicode line break sequence.
On output, println and the %n format specifier write System.lineSeparator(), which is \r\n on Windows and \n elsewhere. A \n inside a string is written as is. Neither choice is always right: platform line endings suit files meant for local tools, while protocols and many file formats require a fixed terminator regardless of platform (HTTP and SMTP use \r\n, most Unix tools and JSON Lines use \n). Decide per format and write the terminator explicitly when it matters.
Character encodings
UTF-8 is the default since Java 18
Until Java 17, APIs that convert between bytes and characters without an explicit charset (FileReader, FileWriter, InputStreamReader(in), String.getBytes(), new String(bytes), Scanner(file), PrintStream(file)) used the platform encoding, such as windows-1252 on Western Windows systems or Shift_JIS on Japanese ones. The same program produced different files on different machines. JEP 400 changed the default charset to UTF-8 on all platforms in Java 18. (Files.readString, Files.newBufferedReader and the other NIO methods had always defaulted to UTF-8.)
Related system properties:
| Property | Meaning |
|---|---|
file.encoding | the default charset; UTF-8 unless started with -Dfile.encoding=COMPAT, which restores the pre-18 behaviour |
native.encoding (17) | the encoding the operating system would use, for when you deliberately want to read local legacy files |
stdout.encoding, stderr.encoding (19) | encoding of System.out and System.err, matched to the console when there is one |
stdin.encoding (25) | encoding for reading System.in |
sun.jnu.encoding | encoding of file names; internal, not changeable |
The rule for robust code is simple: always pass a charset when converting between bytes and text, using StandardCharsets.UTF_8 or Charset.forName("windows-1252") for legacy data. All the old convenience constructors now have overloads that take a Charset.
When the encoding is wrong
Decoding bytes with the wrong charset produces mojibake: the UTF-8 bytes of Café read as windows-1252 come out as Café. Encoding characters that the target charset cannot represent gives ? with getBytes: € does not exist in ISO-8859-1 or IBM437, and 日本 does not exist in any of the single-byte charsets.
How errors are handled depends on the API:
new String(bytes, cs)andgetBytes(cs)silently replace bad input with U+FFFD or?.Files.readString,Files.readAllLinesandFiles.newBufferedReaderreport errors withMalformedInputException(a subclass ofCharacterCodingException).- A
CharsetDecoderorCharsetEncoderlets you choose withonMalformedInputandonUnmappableCharacter:REPORT,REPLACEorIGNORE. UseREPORTwhen silent data corruption is unacceptable.canEncode(char)checks in advance.
Encoding detection is guesswork. There is no reliable way to tell windows-1252 from ISO-8859-15 by looking at the bytes. If you receive files from many sources, require UTF-8, or record the encoding in metadata (an HTTP Content-Type header, an XML declaration).
The console
The terminal is a separate source of encoding trouble. On Windows, the classic cmd console uses an OEM code page such as IBM437 (code page 437) or 850, which differs from the ANSI code page windows-1252 used for files. Since Java 19, System.out and System.err use the console's encoding (stdout.encoding), so characters that exist in the console code page are shown correctly. Characters that don't exist there, such as € in code page 437, still become ?. The real fix is to switch the console to UTF-8 (chcp 65001 on Windows, or Windows Terminal with a UTF-8 profile).
For input:
System.console()returns aConsole(ornullwithout a terminal). Itsreader(),readLineandreadPassworddecode with the console's encoding,charset()(Java 17) reports it, andisTerminal()(Java 22) tells you whether input and output really are a terminal. Java 23 addedLocale-takingformat,printf,readLineandreadPasswordoverloads.new Scanner(System.in)uses the default charset (UTF-8), which may not match the console. Usenew Scanner(System.in, System.getProperty("stdin.encoding"))on Java 25, or read throughSystem.console().reader().java.lang.IO(Java 25) offersIO.printlnandIO.readln, which decodeSystem.inwithstdin.encoding(falling back to UTF-8) and are the simplest choice for small programs.
The byte order mark
U+FEFF at the start of a text stream is a byte order mark (BOM). In UTF-16 it tells the reader whether the file is big-endian (FE FF) or little-endian (FF FE). In UTF-8, where byte order does not exist, the bytes EF BB BF are optional and only signal "this is UTF-8". Many Windows programs, notably Excel when saving "CSV UTF-8", write them.
Java's UTF-8 decoder does not remove a BOM. The character U+FEFF arrives as the first character of the text, where it is invisible and breaks comparisons: the first header of a CSV file is then not name but \uFEFFname. Handle it yourself, either by checking the first character of the decoded text or by peeking at the bytes with a PushbackInputStream, as the demo does. The UTF-16 charset, by contrast, does consume a BOM and uses it to pick the byte order.
The compiler does not skip a BOM either: compiling a UTF-8 source file that starts with one fails with error: illegal character: '\ufeff'. Configure editors to save Java sources as UTF-8 without BOM.
Source file encoding
Java source files are text, so they have an encoding too. Since Java 18, javac reads sources as UTF-8 by default; before that it used the platform encoding, and a project written on a Japanese Windows machine could fail to compile elsewhere. Use javac -encoding windows-1252 (or the corresponding Maven and Gradle settings) only for legacy sources. Class files are always portable: they store strings in a modified UTF-8 format.
If a source file must stay ASCII, write other characters as Unicode escapes such as \u00E9. Be aware that the compiler replaces \uXXXX escapes before parsing, everywhere in the file, including comments, which is why // see C:\users fails to compile.
The program
The demo segments sentences, words and graphemes, wraps a paragraph, compares line-splitting methods, encodes the same text in five charsets, shows replacement versus strict decoding, and finally writes a windows-1252 file and a UTF-8 file with a BOM to a temporary directory and reads them back.
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.nio.file.*;
import java.text.BreakIterator;
import java.util.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) throws IOException {
System.out.println("== BreakIterator: sentences ==");
String text = "Mr. Smith paid $3.50 at 9 a.m. Then he left! Did he return? Nobody knows.";
print(segments(BreakIterator.getSentenceInstance(Locale.US), text));
System.out.println("\n== BreakIterator: words (only segments with a letter or digit) ==");
String words = "Don't split e-mail, 3.14 or C++; naïve café!";
List<String> w = new ArrayList<>();
for (String seg : segments(BreakIterator.getWordInstance(Locale.US), words))
if (seg.codePoints().anyMatch(Character::isLetterOrDigit)) w.add(seg);
System.out.println(w);
System.out.println("Thai has no spaces: " + segments(BreakIterator.getWordInstance(Locale.forLanguageTag("th")),
"\u0E2A\u0E27\u0E31\u0E2A\u0E14\u0E35\u0E04\u0E23\u0E31\u0E1A").size() + " segment(s)");
System.out.println("\n== Characters: code units, code points, grapheme clusters ==");
String family = "e\u0301 \uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC67 \uD83C\uDDE9\uD83C\uDDEA";
System.out.println("length() = " + family.length());
System.out.println("codePointCount = " + family.codePointCount(0, family.length()));
System.out.println("BreakIterator chars = " + segments(BreakIterator.getCharacterInstance(), family).size());
System.out.println("split(\\b{g}) = " + family.split("\\b{g}").length);
Matcher m = Pattern.compile("\\X").matcher(family);
int clusters = 0;
while (m.find()) clusters++;
System.out.println("\\X matches = " + clusters);
String reversedWrong = new StringBuilder("e\u0301a").reverse().toString();
System.out.println("StringBuilder.reverse moves the accent: " + codes(reversedWrong));
System.out.println("\n== Line breaks for wrapping ==");
String para = "Internationalization is often abbreviated i18n, because there are eighteen letters between i and n.";
System.out.println(wrap(para, 30));
System.out.println("\n== Line endings ==");
String mixed = "one\r\ntwo\nthree\rfour";
System.out.println("lines(): " + mixed.lines().toList());
System.out.println("split(\"\\n\") keeps \\r: " + Arrays.stream(mixed.split("\n"))
.map(s -> s.replace("\r", "\\r")).toList());
System.out.println("split(\"\\R\"): " + Arrays.toString(mixed.split("\\R")));
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
pw.printf("A%nB%n");
pw.println("C");
}
String expected = "A" + System.lineSeparator() + "B" + System.lineSeparator() + "C" + System.lineSeparator();
System.out.println("%n and println use System.lineSeparator(): " + sw.toString().equals(expected));
System.out.println("\n== Charsets ==");
System.out.println("default charset is UTF-8 (Java 18+): " + Charset.defaultCharset().equals(StandardCharsets.UTF_8));
String sample = "Café €5 \u2014 \u65E5\u672C";
for (Charset cs : List.of(StandardCharsets.UTF_8, StandardCharsets.UTF_16BE, StandardCharsets.ISO_8859_1,
Charset.forName("windows-1252"), Charset.forName("IBM437"))) {
byte[] bytes = sample.getBytes(cs);
System.out.printf("%-12s %2d bytes -> %s%n", cs.name(), bytes.length, new String(bytes, cs));
}
byte[] utf8 = "Café".getBytes(StandardCharsets.UTF_8);
System.out.println("UTF-8 bytes read as windows-1252 (mojibake): " + new String(utf8, Charset.forName("windows-1252")));
System.out.println("\n== Strict decoding ==");
byte[] bad = {'O', 'K', (byte) 0xC3, '!', (byte) 0xFF};
System.out.println("new String(...) replaces: " + codes(new String(bad, StandardCharsets.UTF_8)));
CharsetDecoder strict = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
strict.decode(ByteBuffer.wrap(bad));
} catch (CharacterCodingException e) {
System.out.println("REPORT decoder: " + e.getClass().getSimpleName());
}
CharsetEncoder latin1 = StandardCharsets.ISO_8859_1.newEncoder();
System.out.println("ISO-8859-1 canEncode('€'): " + latin1.canEncode('€'));
try {
latin1.encode(CharBuffer.wrap("5 €"));
} catch (CharacterCodingException e) {
System.out.println("encoder: " + e.getClass().getSimpleName());
}
System.out.println("\n== Files with explicit encodings and a BOM ==");
Path dir = Files.createTempDirectory("i18n");
try {
Path legacy = dir.resolve("legacy.txt");
Files.writeString(legacy, "Prix: 5 €\n", Charset.forName("windows-1252"));
System.out.println("windows-1252 file bytes: " + Files.size(legacy)
+ ", read back: " + Files.readString(legacy, Charset.forName("windows-1252")).strip());
try {
Files.readString(legacy);
} catch (MalformedInputException e) {
System.out.println("readString(UTF-8) on it: MalformedInputException");
}
Path withBom = dir.resolve("bom.csv");
byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
Files.write(withBom, bom);
Files.writeString(withBom, "name,city\nZoë,Zürich\n", StandardOpenOption.APPEND);
String raw = Files.readString(withBom);
String header = raw.lines().findFirst().orElseThrow();
System.out.println("first char U+" + Integer.toHexString(raw.charAt(0)).toUpperCase()
+ ", header.equals(\"name,city\"): " + header.equals("name,city"));
try (BufferedReader in = newBomAwareReader(withBom)) {
System.out.println("after skipping BOM: " + in.readLine().equals("name,city") + ", " + in.readLine());
}
} finally {
try (var files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}
static BufferedReader newBomAwareReader(Path p) throws IOException {
var in = new PushbackInputStream(Files.newInputStream(p), 3);
byte[] head = new byte[3];
int n = in.readNBytes(head, 0, 3);
boolean bom = n == 3 && (head[0] & 0xFF) == 0xEF && (head[1] & 0xFF) == 0xBB && (head[2] & 0xFF) == 0xBF;
if (!bom && n > 0) in.unread(head, 0, n);
return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
}
static List<String> segments(BreakIterator it, String s) {
it.setText(s);
List<String> out = new ArrayList<>();
for (int start = it.first(), end = it.next(); end != BreakIterator.DONE; start = end, end = it.next())
out.add(s.substring(start, end));
return out;
}
static String wrap(String s, int width) {
BreakIterator it = BreakIterator.getLineInstance(Locale.US);
it.setText(s);
StringBuilder out = new StringBuilder();
int lineStart = 0;
int lastGood = 0;
for (int b = it.next(); b != BreakIterator.DONE; b = it.next()) {
if (s.substring(lineStart, b).stripTrailing().length() > width && lastGood > lineStart) {
out.append(s, lineStart, lastGood).append('\n');
lineStart = lastGood;
}
lastGood = b;
}
return out.append(s.substring(lineStart)).toString().lines()
.map(l -> "|" + l.stripTrailing()).reduce((a, b) -> a + "\n" + b).orElse("");
}
static void print(List<String> segs) {
segs.forEach(seg -> System.out.println("[" + seg + "]"));
}
static String codes(String s) {
StringJoiner sj = new StringJoiner(" ");
s.codePoints().forEach(cp -> sj.add(cp < 128 && cp > 32 ? String.valueOf((char) cp) : String.format("U+%04X", cp)));
return sj.toString();
}
}
== BreakIterator: sentences ==
[Mr. ]
[Smith paid $3.50 at 9 a.m. ]
[Then he left! ]
[Did he return? ]
[Nobody knows.]
== BreakIterator: words (only segments with a letter or digit) ==
[Don't, split, e-mail, 3.14, or, C, naïve, café]
Thai has no spaces: 2 segment(s)
== Characters: code units, code points, grapheme clusters ==
length() = 16
codePointCount = 11
BreakIterator chars = 5
split(\b{g}) = 5
\X matches = 5
StringBuilder.reverse moves the accent: a U+0301 e
== Line breaks for wrapping ==
|Internationalization is often
|abbreviated i18n, because
|there are eighteen letters
|between i and n.
== Line endings ==
lines(): [one, two, three, four]
split("\n") keeps \r: [one\r, two, three\rfour]
split("\R"): [one, two, three, four]
%n and println use System.lineSeparator(): true
== Charsets ==
default charset is UTF-8 (Java 18+): true
UTF-8 21 bytes -> Café €5 — 日本
UTF-16BE 24 bytes -> Café €5 — 日本
ISO-8859-1 12 bytes -> Café ?5 ? ??
windows-1252 12 bytes -> Café €5 — ??
IBM437 12 bytes -> Café ?5 ? ??
UTF-8 bytes read as windows-1252 (mojibake): Café
== Strict decoding ==
new String(...) replaces: O K U+FFFD ! U+FFFD
REPORT decoder: MalformedInputException
ISO-8859-1 canEncode('€'): false
encoder: UnmappableCharacterException
== Files with explicit encodings and a BOM ==
windows-1252 file bytes: 10, read back: Prix: 5 €
readString(UTF-8) on it: MalformedInputException
first char U+FEFF, header.equals("name,city"): false
after skipping BOM: true, Zoë,Zürich
Common questions
How do I truncate a string to N characters without breaking emoji?
Truncate at a grapheme boundary: iterate with BreakIterator.getCharacterInstance() (or the \X regex) and cut after the Nth cluster. substring(0, n) can split surrogate pairs and combining sequences, producing broken characters.
How do I count the "length" of user input for a limit like 280 characters?
Decide what the limit means. Code points (s.codePointCount(0, s.length())) are a common, stable choice; grapheme clusters match what users see. length() counts UTF-16 units, so one emoji may count as 2 or more.
How do I read a file whose encoding I don't know?
Ask the producer, or check metadata first. As a heuristic: try strict UTF-8 decoding with a CharsetDecoder set to CodingErrorAction.REPORT; if it succeeds, it's almost certainly UTF-8. Otherwise fall back to the most likely legacy encoding, such as windows-1252. Libraries like ICU4J's CharsetDetector guess with statistics.
Why does my CSV header not match "name"?
The file probably starts with a UTF-8 BOM, so the first header is \uFEFFname. Strip a leading \uFEFF after reading the first line.
Why does System.out.println("€") print ? on Windows?
The console code page doesn't contain the character. Run chcp 65001 or use Windows Terminal with UTF-8, or set -Dstdout.encoding=UTF-8 when the console really uses UTF-8.
Do I still need -Dfile.encoding=UTF-8?
Not since Java 18; UTF-8 is the default. -Dfile.encoding=COMPAT restores the old platform-dependent behavior for legacy applications that rely on it.
API reference
| Method | Purpose |
|---|---|
BreakIterator.getCharacterInstance/getWordInstance/getSentenceInstance/getLineInstance([locale]) | boundary iterators |
setText, first, next, last, previous, following, preceding, isBoundary | iteration |
String.codePointCount, codePoints(), regex \X and \b{g} | code points and grapheme clusters |
String.lines(), regex \R, System.lineSeparator(), %n | line endings |
Charset.forName, StandardCharsets, Charset.defaultCharset() | charsets |
CharsetDecoder/CharsetEncoder.onMalformedInput/onUnmappableCharacter(CodingErrorAction), canEncode | strict conversion |
System.console(), Console.charset() (17), isTerminal() (22), reader(), readLine, readPassword | console I/O |
IO.println, IO.readln (25) | simple console I/O |
system properties native.encoding, stdout.encoding, stderr.encoding, stdin.encoding | encoding information |
Summary
length()counts UTF-16 units, not characters. Use code points for Unicode processing and grapheme clusters (\X,BreakIterator) for anything a user sees.BreakIteratorfinds character, word, sentence and line boundaries; filter word segments yourself and treat sentence boundaries as heuristics.- Read lines with
lines()/readLine/\R; write\nor\r\ndeliberately when a format requires it. - UTF-8 has been the default charset since Java 18, but always pass a charset explicitly; use
native.encodingfor local legacy files. - Decoding with the wrong charset produces mojibake; use
REPORTdecoders or the NIOFilesmethods to fail loudly. - Consoles may use another encoding; use
Console,stdin.encoding/IO.readln(Java 25), or switch the terminal to UTF-8. - Java does not strip a UTF-8 BOM, neither when reading files nor in
javac; handle U+FEFF yourself.
Practice Questions
1. A tweet limit check uses text.length() <= 280. Why does it reject some messages that look shorter, and what should it use?
length() counts UTF-16 code units. Every emoji outside the BMP counts as 2, and composed emoji (families, flags, skin tones) count as many units, so a message with emoji is overcounted. Count grapheme clusters instead, for example (int) Pattern.compile("\\X").matcher(text).results().count(), or use whatever counting rules the target platform specifies.
2. A CSV import reads the header with Files.readAllLines(path).get(0).split(","), but the column "id" is never found in files exported from Excel. Why?
Excel's "CSV UTF-8" export starts with a UTF-8 byte order mark. Java decodes it as the character U+FEFF and keeps it, so the first column name is "\uFEFFid", not "id". Strip a leading U+FEFF from the first line (or skip the three BOM bytes before decoding).
3. What changed in Java 18 for new FileReader("data.txt"), and what should code written today do?
Before Java 18 it used the platform's default encoding, which varied by operating system and locale. Since Java 18 (JEP 400), the default charset is UTF-8 everywhere, so it reads UTF-8. Code should not depend on either default: use new FileReader(file, StandardCharsets.UTF_8) or Files.newBufferedReader(path, charset) and name the charset the file really uses.
4. A program prints "100 €" and Windows cmd shows "100 ?". What is going on and how can it be fixed?
The console uses an OEM code page such as 437 or 850, which has no euro sign. Java encodes the output for the console code page (stdout.encoding), and characters it cannot map become ?. Switch the console to UTF-8 with chcp 65001 (or use a terminal with UTF-8), after which Java detects the new encoding. Before Java 19 you also had to align the encoding manually.
5. Why is text.split("\n") a poor way to split file content into lines, and what are the alternatives?
Files with Windows line endings contain \r\n, so each line would keep a trailing \r, which breaks comparisons and parsing, and files with old Mac \r endings would not be split at all. Use text.lines(), text.split("\\R"), BufferedReader.readLine() or Files.readAllLines, all of which recognize \n, \r\n and \r.
Previous: MessageFormat and ChoiceFormat in Java: Placeholders, Plurals and Choices
Next: Resource Bundles in Java: Locating Bundles, Property Files and Bundle Classes
Related reading
- MessageFormat and ChoiceFormat in Java: Placeholders, Plurals and Choices
- Localized Dates, Collation and Unicode Normalization in Java
- Number Formats in Java: NumberFormat, Compact Numbers, DecimalFormat and Currencies
- Locales in Java: Language Tags, Default Locales and Display Names
- Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar

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.