Are you ready to level up your productivity? In this blog post, we’ll explore ChatGPT , a powerful and user-friendly language model that can generate Java functions and classes from textual descriptions thus helping you take your Java development to the next level. Read on to learn more!
First I asked the Assistant (that’s how ChatGPT refers to itself) if he knows to write Java programs:
Great! Now let’s start with some basics like does it distinguish between primitives and objects and can it do simple iterations and computation on iterated elements. I decided to be very specific in my prompts at the beginning.
This is beginner-level stuff but it’s a nice start! Correct algorithm and naming of a parameter and the method. There is space for improvement though - an array can be null and the result can overflow so the return type could be
long. Let’s see if it knows the difference between primitives and objects in Java.
Yes it does, and gives a good explanation thereof. The problems from the previous method are still present though. Let’s correct some of them.
It correctly did what I asked for. It even noticed that this method is similar to the previous example without me explicitly mentioning that. Can it do the
null check of a parameter but using a popular library?
Yes it can and the explanation even says which runtime exception can be thrown. Good job ChatGPT!
Here I was a bit less explicit and didn’t tell it to use an array and it correctly deducted that I want primitive
int and that an array is the only possible choice. Return type is
double which is good. Still,
sum can overflow.
Overall I am satisfied with the results in this area. Generated methods might not be of industrial quality but they are a solid starting point and, depending on your use-case, might even be enough to use as-is.
Manipulating strings is something we do daily and every bit of help here is precious. Let’s see what ChatGPT can generate here regarding sorting, removing whitespaces, reversing a string etc.
Correct implementation, it sorts strings in-place by length in ascending order. It uses method references and
Comparator.comparingInt, both of which are available since Java 8. Now it’s more than obvious that if we want to guard against
null parameter we must explicitly say so. Also, if any of the elements of a list of strings is
null, the method can throw an exception, depending on the implementation of
sort method in a concrete
This was my first “ooooops!” moment. Implementation is seemingly correct although I didn’t test it extensively, but way more convoluted than it should be. To ChatGPT’s defense, explanation of a code was quite solid (not shown here but it explained what is the underlying principle and the mechanics of
while loops). However, I explicitly said that it should use Java 17, counting that I would see
strip() method from the
String class used. What if I politely say I want that method?
Now we’re talking! Simple and effective, and explanation even includes differences from the previous method. This time it checked for
null without explicit request. I presume it’s because of the call to
strip which would throw
NullPointerException had the check been absent.
OK, I just couldn’t resist to ask it textbook junior developer interview question. It offered two snippets which is reasonable because I didn’t ask it to generate a method. One of them uses
StringBuilder, the other one plain
String. Explanations are traditionally solid. Before moving to the next topic I wanted to see whether the AI wants to do some useless work.
It doesn’t object even if the effect of the result is just… well, nothing. With this philosophically-existential task behind us, I conclude that it can generate helpful methods or snippets for
String manipulation but it’s noticeable that it needed more nudging than with arrays of integers. It already seems like the person driving the dialog should be a subject matter expert and not just a blind follower of ChatGPT’s results.
This is one of my favourite topics. Many years ago I dealt a lot with pseudo-random numbers and simulations and was really excited to see significant improvements in that area in Java 17. Does our assistant know about them?
Ouch, not even close! While the implementation works, it uses
java.util.Random which exists since Java 1.0. In the explanation, it confidently yet wrongly claims that this class was introduced in Java 17, and just a few lines down it says that the same class is “from Java 1.0”. The only thing that is connected to Java 17 is that
java.util.Random was retrofitted to implement
Ouch again! It has found classes with the same name but from the Caffeine library . The good thing (for me at least) is that I didn’t know about that library and now I do. But back to the RNG topic…
It tries really hard but this doesn’t even compile! Package
jdk.random is declared in module
jdk.random, which does not export it to the unnamed module. It seems like the training corpus of Java code is predominantly written in versions < 17. Too bad. Perhaps in the next version it will learn more and more from modern Java code.
Finally back on track. It used
ThreadLocalRandom correctly and the method really simulates 6-sided die.
It generated a class, used
ThreadLocalRandom as I asked before and even made the field
final. First objection I have is the class name. Flipping a coin can’t be a part of
Dice. Yes, this class has low cohesion but that’s what I requested. The name should be more generic. Second objection is that a class should be immutable whenever possible.
It changed the name to a more generic one and made the class
final which in this case was enough to make it immutable.
Opening of ChatGPT to the general public made a lot of publicity and I think it is well deserved. People’s reactions go from “It’s useless and gives a lot of false answers” to “All developers will lose jobs in a few years, I’m moving to farming while I still can”. My opinion is somewhere in the middle - I see it as a useful tool that takes getting used to and surely demands some time from us to learn it, then become comfortable and finally master it. There is a potential that in the hands of a skilled developer it could be valuable and speed up writing some boring but needed code. On the other hand, it definitely won’t leave us jobless (at least for now). Almost every time it stumbled I managed to push it to give me more useful or accurate answer but that’s only because I knew what to ask it! Had I not known, for example, about
strip() method in
String class I could’ve just accepted objectively inferior answer and made it a part of a codebase which someone would have to test, maintain, fix bugs… And this little experiment touched only the tip of the iceberg. ChatGPT and myself will definitely meet again and talk about JSON, HTTP(S), constructors, immutability, defensive programming techniques and a lot more!
As a bonus, here are all the prompts I issued:
1Hello Assistant, do you know how to write Java programs? 2 3Can you please write me a Java function that calculates and returns sum of an array of ints? 4 5Can you please write me a Java function that calculates and returns sum of an array of Integers? 6 7Can you please write me a Java function that calculates and returns sum of an array of positive Integers, but if any Integer is null it simply skips it? 8 9Can you refine previous function so that it throws an exception if a parameter is null? And oh, please use Guava library for that. 10 11Can you please write a Java function to find average of ints? 12 13Can you please write a Java function to sort strings by length? 14 15I need a function that removes leading and trailing whitespaces from a String. Please first check if a String is null. Then remove as many leading and trailing whitespaces from it. Please use Java 17. 16 17Can you please rewrite previous example but use method strip() from String class? 18 19How can I reverse a string in Java? 20 21I need a Java function that does nothing. 22 23I need a Java function that simulates a coin flip. Please use random-number generators introduced in Java 17. 24 25But `java.util.Random` is introduced in Java 1.0! I want the previous example to use classes like `RandomGeneratorFactory` and `Xoshiro256PlusPlus`. 26 27Please rewrite the previous example but use only classes available in Java 17. Class Xoshiro256PlusPlus is available in Java 17 in the package jdk.random. 28 29OK, let's stick to the ThreadLocalRandom from now on. Can you write a similar function, just instead of coin flip I need to roll a standard 6-sided die? 30 31Can you write a class that has methods for simulating a coin flip and rolling a die? 32 33Can you make the previous class immutable? Also, Dice is not a very good name because dice can't flip a coin.
Dear fellow developer, thank you for reading this article about ChatGPT and how it can help us in day to day work. Until next time, TheJavaGuy saluts you!