News for hackers. Stuff that matters.
Re:It’s Not Wrong that “ ”.length == 7 by rzwitserloot on Friday June 02, 2023 @10:56AM (#36165988)
Java loaded full unicode code point semantics into its standard `java.lang.String` class. These _are not guaranteed_ to have `O(1)` performance characteristics, because the underlying storage format is dynamically either a UTF-16-esque variant (with surrogate pairs for characters that don't fit in 16 bit), or a single-byte-per-char format if the string does not contain any non-ASCII. This has the advantage of being very very slightly more obvious, given that both methods exist and are documented:

  void main() {
    String x = "(that emoji here)";
    System.out.println("Chars: " + x.length());
    System.out.println("Codepoints: " + x.codePointCount(0, x.length()));
    System.out.println("As stream of chars (= UTF16-esque with surrogate pairs):");
    x.chars().forEach(System.out::println);
    System.out.println("As a stream of codepoints:");
    x.codePoints().forEach(System.out::println);
  }
This ends up printing:

  Chars: 7
  Codepoints: 5
  As stream of chars (= UTF16-esque with surrogate pairs):
  55358
  56614
  55356
  57340
  8205
  9794
  65039
  As a stream of codepoints:
  129318
  127996
  8205
  9794
  65039
NB: Apparently many hackernews readers know java but don't use it all that often day-to-day. The provided java snippet is vanilla valid and can be executed with `java ThatFile.java` (no need to compile it first), though it does use preview features.

The fact that the codepoint counter is a very awkward `codePointCount` call has the dubious benefit of highlighting this method loops through and therefore would be quite slow on very large strings.

Re:It’s Not Wrong that “ ”.length == 7 by ElectricalUnion on Friday June 02, 2023 @11:17AM (#36166305)
> The provided java snippet is vanilla valid

Did not you still need the `java --source 11 ${filename_without_java_extension_because_JEP_330}` to use it? And you still need a wrapper class with a static method main in it.

Re:It’s Not Wrong that “ ”.length == 7 by JZerf on Friday June 02, 2023 @11:43AM (#36166669)
I was a little puzzled by this compared to what I was used to with Java in the past. It looks like the grandparent's code relies on JEP 445 ( https://openjdk.org/jeps/445 ) which is a preview feature as was mentioned but it also apparently requires the very latest Java 21 which hasn't even been officially released yet.
Re:It’s Not Wrong that “ ”.length == 7 by Bjartr on Friday June 02, 2023 @11:44AM (#36166701)
> And you still need a wrapper class with a static method main in it

One of the preview features he's using is JEP 445[1] that allows you to omit the wrapper class, as well as the arguments to main and the public and static modifiers.

[1]https://openjdk.org/jeps/445