We sometimes are forced by the Java language to declare variables that we never use, attracting the ire of the javac compiler. Since Java 22 we have a way to declare these as "unnamed" by using an underscore. Full Article
Java 22 preview allows us to write code before the call to super(). There are restrictions. We are not allowed to refer to "this" in any way. We thus cannot set fields before calling the superclass constructor. But what if the superclass constructor calls our methods? In this newsletter we explor... Full Article
The enhanced switch is cool. Pattern Matching for switch is super cool (they even timed the JEP number to be exactly 420 - or was that fate?). But what happens when we use "break" inside the case statement? Let's find out. Full Article
Sealed classes show us which subclasses they permitted. Unfortunately there is no way to do this recursively. In this newsletter we show how to navigate the sealed class hierarchy and write a ClassSpliterator that can then create a Stream of classes. Full Article
Should we write "public abstract static class" or "public static abstract class"? And should fields be "final static private" or "private static final"? In this newsletter we explore the canonical order of modifiers in Java. Full Article
How consistent is weakly-consistent iteration? And which collections return weakly-consistent iterators? How do we know? Join us as we explore what weakly-consistent means with concrete examples. Full Article
Is the Java Ecosystem still safe and robust or should we move to a different language? Maybe Go or Python? In this newsletter we look at whether Java is still a solid choice. Full Article
How would the plain Java code look for our try-with-resource constructs? Watch how 4 lines of code are expanded into 39 LOC and 170 bytecodes. We also look at how Java 9 has reduced this slightly. Full Article
Local variable type inference is finally here, but dangers lurk. We might encourage overly long methods and lose the benefits of interface abstraction. Full Article
Since Java 5, we have been able to create collections that would check at runtime that the objects added were of the correct type. But very few Java programmers know about it. The benefit we get in debugging ease is huge, as exceptions are thrown earlier. Full Article
Java 9 has changed the way that new programmers can be introduced to Java. No more "public static void main(String[] args)", but instead a beautiful jshell REPL that lets us experiment with Java features without understanding the subtleties of "static". Full Article
Surprisingly, the compound arithmetic expression contains a cast that can produce some interesting side effects. In this newsletter we explore this and other edge cases in the Java Language Specification. Full Article
Java 8 introduced the java.util.Optional class, based on the famous Guava class by the same name. It was said that we should hardly ever call get(). In this newsletter we offer a short tutorial that demonstrates coding examples of alternatives to get(). Full Article
Whenever a class implements an interface, all the implemented methods have to be public. In this newsletter we look at a trick that we can use to make them private. Full Article
Blocking methods should not be called from within parallel streams in Java 8, otherwise the shared threads in the common ForkJoinPool will become inactive. In this newsletter we look at a technique to maintain a certain liveliness in the pool, even when some threads are blocked. Full Article
The JavaDocs for method Object.hashCode() seems to suggest that the value is somehow related to memory location. However, in this newsletter we discover that there are several different algorithms and that Java 8 has new defaults to give better threading result if we call hashCode a lot. Full Article
When a thread is interrupted, we need to be careful to not create a livelock in our code by re-interrupting without returning from the method. Full Article
Maps and Sets in Java have some similarities. In this newsletter we show a nice little trick for converting a map class into a set. Full Article
In this newsletter we investigate what can go wrong when we call methods from constructors, showing examples from the JDK, Glassfish, Spring Framework and some other well known frameworks.. Full Article
How can you set a field at point of declaration if its constructor throws a checked exception? Full Article
The trend of marking parameters and local variables as "final" does not really enhance your code, nor does it make it more secure. Full Article
It is possible to use the break statement to jump out to the end of a labelled scope, resulting in some strange looking code, almost like the GOTO statement in C. Full Article
Surreptitious: stealthy, furtive, well hidden, covert. In this newsletter we will show two Java puzzles written by Wouter Coekaerts that require a surreptitious solution. You cannot do anything to upset the security manager. Full Article
What is the largest double that could in theory be produced by Math.random()? In this newsletter, we look at ways to calculate this based on the 48-bit random generator available in standard Java. We also prove why in a single-threaded program, (int)(Random.nextDouble() + 1) can never be rounde... Full Article
In this newsletter we try to calculate the meaning of life, with surprising results. Full Article
In this newsletter we discuss why we unfortunately will not be able to use the try-with-resource mechanism to automatically unlock in Java 7. Full Article
In this newsletter we explore my favourite new Java 7 feature "try-with-resource" and see how we can use this mechanism to automatically unlock Java 5 locks. Full Article
Most of the northern hemisphere is on holiday, so here is a quick quiz for those poor souls left behind manning the email desk. How can we prevent a ConcurrentModificationException in the iterator? Full Article
Generics can be used to further improve the WalkingCollection, shown in our previous newsletter. Full Article
After almost nine years of silence, we come back to bring the logging series to an end, looking at best practices and what performance measurements to log. Full Article
In this newsletter we show the reflection plumbing needed for writing a socket monitor that sniffs all the bytes being sent or received over all the Java sockets. The Delegator is used to invoke corresponding methods through some elegant guesswork. Full Article
In this newsletter we answer the question: "How do we force all subclasses to contain a public no-args constructor?" The Annotation Processing Tool allows us to check conditions like this at compile time, rather than only at runtime. Full Article
The developers of the Java language tried their best to stop us from constructing our own enum instances. However, for testing purposes, it can be useful to temporarily add new enum instances to the system. In this newsletter we show how we can do this using the classes in sun.reflect. In addi... Full Article
Enums are implemented as constant flyweights. You cannot construct them. You cannot clone them. You cannot make copies with serialization. But here is a way we can make new ones in Java 5. Full Article
Java 5 adds a new way of casting that does not show compiler warnings or errors. Yet another way to shoot yourself in the foot? Full Article
When we make proxies that wrap objects, we have to remember to write an appropriate equals() method. Instead of comparing on object level, we need to either compare on interface level or use a workaround to achieve the comparisons on the object level, described in this newsletter. Full Article
The Strategy Pattern is elegant in its simplicity. With this pattern, we should try to convert intrinsic state to extrinsic, to allow sharing of strategy objects. It gets tricky when each strategy object needs a different set of information in order to do its work. In this newsletter, we look ... Full Article
Someone asked me yesterday what the maximum inheritance depth is in Java. I guessed a value of 65535, but for practical purposes, not more than 5. When I asked performance guru Kirk Pepperdine to estimate, he shot back with 63. In this newsletter, we look at the limitations in the JVM and exam... Full Article
What do you do when an object cannot be properly constructed? In this newsletter, we look at a few options that are used and discuss what would be best. Based on the experiences of writing the Sun Certified Programmer for Java 5 exam. Full Article
Sometimes frameworks use reflection to call methods. Depending how they find the correct method to call, we may end up with IllegalAccessExceptions. The naive approach of clazz.getMethod(name) is not correct when we send instances of non-public classes. Full Article
When we change libraries, we need to do a full recompile of our code, in case any constants were inlined by the compiler. Find out which constants are inlined in this latest newsletter. Full Article
A problem that I encountered when I first started using enums was how to serialize them to some persistent store. My initial approach was to write the ordinal to the database. In this newsletter, I explore some ideas of a more robust approach. It will also show you some applications of Java ge... Full Article
Java does not use the "goto" statement, although it is a reserved word. We do have something similar though: labeled breaks. Full Article
Instead of auto-generating our hashCode() and equals() methods, why not use the strategy pattern to do this for us? In this newsletter, we examine different approaches and their benefits. Full Article
The object adapter pattern is similar in structure to the proxy pattern. This means that we can use the dynamic proxy mechanism in Java to also implement a dynamic object adaptor. Full Article
Enumeration was the interface in Java 1.0 that has now been superceded by Iterator. It is still in widespread use. In this newsletter we look at how we can use Enumeration with the new for-in statement. Full Article
Java 5 introduced the Iterable interface, used by the enhanced "for" statement to iterate. Collection extends Iterable, but we can also write our own classes that implement it. This way we can use the enhanced "for" statement to iterate over them. Examples would be ResultSet and InputStream. Full Article
To optimize autoboxing, Java caches boxed integers in the range -128 to 127. We examine what happens if this cache were to get corrupted. Full Article
In this newsletter, we have Amotz Anner show us how we can map objects to XML files using the new Java 5 annotations. Full Article
Final fields could not be set with reflection in Java 1.1. In Java 1.2 they changed it so that we could set final fields. We again couldn't in Java 1.3 and 1.4. Since Java 5, we can again set final fields. Full Article
Do generics make the code easier or harder to read? Anything new can be challenging on the eyes, but time will tell whether generics will be as popular as we expect. Full Article
The java.util.Properties class can load and store the properties in an XML file. We furthermore periodically check whether the file has changed and if so, reload the properties. Full Article
Fields can either be initialized where they are declared or in the constructor. Some programmers set them twice. We have a look at how final fields avoid this. Full Article
A handy class shipped in the JDK is sun.reflect.Reflection. It allows us to find out which class called our method. Note that this class might become unavailable in future versions of Java. Full Article
We have a look at how to build a simple webservice with Java. Full Article
Two easy Java puzzles to test your understanding of try-finally. Full Article
Another small puzzle to test your knowledge of Java. Full Article
We have heard that we can only have one public class per .java file. But that is not entirely true. We could, in theory, have many public static inner classes inside one public class. Full Article
Instead of coding the toString() method repeatedly by hand, we present several approaches to generate the String automatically. Full Article
A common pattern is the Java Monitor Pattern. All public methods are synchronized. Private methods would assume that the lock is already held. How can we verify this? In this newsletter we show how we can assert that we hold the lock inside the private methods. Full Article
LinkedHashMap gives us a map that retains the order in which elements were inserted. This can help us maintain a dictionary of key-value pairs in the same order as they were read in. Full Article
We learn how we can download images from within Java and then display them in a JFrame. Full Article
Overloading of methods refers to multiple methods with the same name, but different parameter types. As convenient as this feature is, we should use it sparingly. This newsletter explains why. Full Article
A typical first computer language used to be BASIC. It had a bad reputation for producing spaghetti code, due to the GOTO statement. We show how switch-case and exceptions in Java can look like BASIC. Full Article
Stack traces give us a clue of which method called us, giving us a form of caller ID. Full Article
Java 1.4 changed inner classes slighty to set the link to the outer object prior to calling super(). This avoids some hard to explain NullPointerExceptions. Full Article
Inner classes have magic handles to the outer object and provide synthetic methods to acces private data. This can result in some hard-to-understand bugs. Full Article
Starting threads is easy. Shutting them down again in an orderly fashion is not. In this newsletter we explore how to use interrupts to indicate to a thread that it should cooperatively shut down. Full Article
A long time ago, James Gosling wrote Oak, which was later renamed to Java. Some of the quirky Java restrictions, for example only one public class per file, can be traced back to Oak. This newsletter looks at the Oak 0.2 specification. Full Article
Source control systems give us insight into how a method has changed over time. It is usually a bad idea to comment out code, especially without adequate comments why. It confuses the person maintaining the code. Full Article
Instead of writing and reading blobs as large byte[], we should rather stream the data using ResultSet.getBytes(). Full Article
In Java we can use OS signals directly for detecting when a program is being closed. This can be used to write our own shutdown hook or put in whatever feature we need. Full Article
When iterating over a heterogeneous collection, one way to differentiate between object types is with instanceof. Another way is to create a special visitor object that can be applied to the objects in the collection. Full Article
Java supports unicode in variable and method names, although we generally recommend using ASCII characters. Here we have a look at how to do it. Full Article
Prior to Java 5, we had to jump through all sorts of hoops to get something like generics. In this newsletter we use "dynamic decorators" to produce type-safe iterators dynamically. Full Article
One way to protect ourselves from badly constructed objects is to throw an exception from the constructor. However, the object can be resurrected if the class is non-final by using the finalize() method. Full Article
When I first started using Java in 1997, I needed very large hash tables for matching records as quickly as possible. We ran into trouble when some of the keys were mutable and ended up disappearing from the table, and then reappearing again later. Full Article
In this newsletter, we learn how to do network multicasting in Java using the Datagram class. Full Article
Packages should have versions numbers embedded in the Jar file's manifest. Our guest author Herman Lintvelt shows us how. Full Article
No, this is not our "final" newsletter, but rather a newsletter about the "final" keyword. Full Article
In this newsletter, Dr Christoph Jung amazes us by showing how we can build a minimalist application server by playing around with class loaders. Full Article
In Java all methods are virtual, meaning that the most derived method is always called. In earlier versions of Java, it was possible to trick the JVM by replacing the superclass with another wheere the method is defined as "private". Full Article
In this newsletter, we serialize Java objects into a byte[] and then write that into a PreparedStatement with setBytes(). Full Article
Classes loaded by different ClassLoaders are considered distinct, even when they have the exact same name and bytecode. Full Article
A quick follow-up to our newsletter on abusing exceptions to simulate the switch construct, looking at the performance in comparison to other approaches. Full Article
The try-catch construct can be used for program flow control. In this newsletter we abuse it to simulate the switch statement. Full Article
Some crazy antics as we modify the contents of the char[] embedded within Strings. Of little practical value, except to gain some understanding of how things work under the covers. Full Article
System.exit() does not immediately shut down the Java Virtual Machine. Instead, it first runs our shutdown hooks, albeit in an undefined order. Once they are done, the JVM stops for real. Full Article
Usually in Java, polymorphism is done depth-first. This is the reason why in Java 5, classes implementing Comparable cannot be further specialized to another Comparable type (compareTo takes an Object). In this newsletter we look at how we can change this to breadth-first polymorphism. Full Article
Java was based on ideas taken from C/C++, but the designers of the language tightened up the language significantly. In C/C++, a zero (0) means false and non-zero (e.g. 1) means true. In this newsletter, we examine how we should be comparing booleans. Full Article
Did you know that it is possible to define inner classes inside interfaces? This little trick allows us to create method objects inside an interface. Full Article
Dynamic proxies can help us reduce the amount of code we have to write. In this newsletter, our guest author, Dr Christoph Jung, gives us a short tutorial on how the dynamic proxies work. Full Article
We look at some tricks on how we can track where things are happening in our code, which can then be used for producing more detailed logging. Full Article
In this newsletter we look at how we can write a TeeOutputStream that works similarly to the unix "tee" utility and pipes the output to two different OutputStreams. We can then reassign System.out to be written to a file and to the old System.out. Full Article
Anonymous inner classes allow us to call super class methods inside its initializer block. We can use this to add values to a collection at point of creation, for example: new Vector(3) {{ add("Heinz"); add("John"); add("Anton"); }}); Full Article
Get: every new article, exclusive invites to live webinars, our top-10 articles ever, access to expert tutorials & more!
Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations. Find Out More