Most programming language have their oddities or lesser known features. Java is no exception. In this article, I will present a short selection of such oddities.
Java Reflection is a powerful API that can dynamically access classes, methods, fields, etc. It is used internally by many frameworks and libraries.
We usually expect System.out.println("foo")
to print foo
. But this can be changed using Java Reflection,
for example by dynamically replacing the content of "foo"
with the content of another string.
First we define a method that replaces the content of a given string:
public static void replaceContent(String string, String newContent) throws Exception {
// Handling strings of different lengths is more complex
if (string.length() != newContent.length()) {
return;
}
// Get the field that contains the string content
Field field = String.class.getDeclaredField("value");
// Make it readable
field.setAccessible(true);
// Replace the content
byte[] currentContent = (byte[]) field.get(string);
System.arraycopy(newContent.getBytes(), 0, currentContent, 0, newContent.length());
}
It used to be enough, but more recent versions of Java also require extra configuration such as the
--add-opens=java.base/java.lang=ALL-UNNAMED
JVM parameter.
Then we can simply execute the following code:
// First call this somewhere, for example in the "main" method
replaceContent("foo", "bar");
// Then this prints "bar" !
System.out.println("foo");
// But also this is true !
boolean b = "foo".equals("bar");
This hack works in Java because strings of the same content are stored in the same memory location.
This particular usage of Java Reflection breaks the encapsulation principle of object-oriented programming, so should be used with care. This is for educational purposes, and not at all to prank your coworkers by replacing the content of some of their strings...
Simply said, can you guess what a URL does in some Java code?
Consider this code sample:
public sum(int a, int b) {
int s = a + b;
https://www.example.com
return s;
}
Does it compile? Does it run correctly?
The previous code compiles and runs fine. A URL is valid Java code, that does nothing by itself.
It is actually a comment (the //www.example.com
part) preceded by a label (the https:
part).
Comments are well known, but labels not so much. They can be used to jump to a given statement using the break
or continue
keyword, for example in a for
or while
statement:
outer: for (...) {
for (...) {
...
if (...) {
break outer; // Using just "break;" would only break the inner loop
}
}
}
Mockito is a popular mocking framework, used to create mock objects for testing purposes. Years ago, when I first used it, I was surprised how stubbing is declared:
TimeService mockedService = mock(TimeService.class);
when(mockedService.getDuration()) // Why passing the current value?
.thenReturn(1000);
The when
method receives the result of the current execution of the business method.
But Mockito has no use of that value, so why is it passed?
The actual implementation of when
in Mockito 5.3.1 is:
public <T> OngoingStubbing<T> when(T methodCall) {
MockingProgress mockingProgress = mockingProgress();
mockingProgress.stubbingStarted();
@SuppressWarnings("unchecked")
OngoingStubbing<T> stubbing = (OngoingStubbing<T>) mockingProgress.pullOngoingStubbing();
if (stubbing == null) {
mockingProgress.reset();
throw missingMethodInvocation();
}
return stubbing;
}
The implementation details are not important here, but we can see that the methodCall
parameter value is not used
at all. It is nevertheless useful. This parameter has two main purposes: convenience and reliability.
First, about convenience. To be able to execute thenReturn
, Mockito needs to know the business method
being stubbed. This is achieved by executing the business method somewhere before thenReturn
.
When the business method of the mock is executed, Mockito can flag (as far as I know this is stored in a ThreadLocal
instance) that method for later use in thenReturn
. Calling the business method in when
right before thenReturn
is
an easy and convenient way to stub the right method.
Then, about reliability. From the when
source, we can see that the method is generic.
It can forward the parameter type to the thenReturn
method thanks to OngoingStubbing<T>
.
This makes sure that the value passed to thenReturn
is compatible with the business method call,
or else the compiler with raise an error.
Some templating engine use the double mustache syntax for string interpolation, for example
{{ name }}
to display the user name.
This syntax exists in Java but has a very different meaning, here is sample usage:
List<Integer> list = new ArrayList<>() {{
add(1);
}}
The previous code creates an instance of an anonymous subclass of ArrayList
then executes the
add(1)
method on that instance. Of course, we can simply use List.of(1)
if an immutable list is ok.
The double mustache syntax is actually the composition of two different features.
Each pair of curly braces has a different meaning.
The outer pair, along with new
, is used to declare and instantiate an anonymous class,
and the inner pair is used to declare an instance initializer block.
Here is an example of an anonymous class instantiation, to create a custom Runnable
object:
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Running");
}
}
Then, an example of an instance initializer block, to execute some code before the constructor:
public class Foo {
{
System.out.println("Before the constructor");
}
Foo() {
System.out.println("During the constructor");
}
}
As a side note, the Java double mustache syntax is similar to the Kotlin apply
scope function:
val list = ArrayList<Int>().apply {
add(1)
}
Do you know what a file magic number is? Simply said, it's a sequence of bytes at the beginning of files
used to identify the type of the file. For example PDF files start with %PDF-
which is 25 50 44 46 2D
in hexadecimal. See Wikipedia - List of file signatures
for a list of file magic numbers.
Java class files have their own magic number. You can see it by opening a .class
file with a text editor.
It is CA FE BA BE
in hexadecimal, also known as cafe babe. This is a reference to the restaurant where
James Gosling, the founder of Java, and friends used to go to lunch,
see Wikipedia - Java class files - Magic number.
I hope you enjoyed this selection of Java oddities, and possibly learnt something useful (no, not you cafe babe).
© 2007-2025 Florian Beaufumé