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!

What ChatGPT thinks about Java?

First I asked the Assistant (that’s how ChatGPT refers to itself) if he knows to write Java programs: What ChatGPT thinks about Java

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.

ints and Integers

A method to calculate sum of an array of ints

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.

A method to calculate sum of an array of Integers

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.

A method to calculate sum of an array of positive Integers skipping nulls

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?

Refined previous method with null check

Yes it can and the explanation even says which runtime exception can be thrown. Good job ChatGPT!

A method to calculate average of ints

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.

Strings

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.

A method to sort strings by length

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 List subclass.

A method to remove whitespaces from a string

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?

A method to remove whitespaces from a string - second attempt

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.

Reversing a string 1 Reversing a string 2

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.

A method that does nothing

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.

Random numbers

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?

A method to flip a coin

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 java.util.random.RandomGenerator.

A method to flip a coin - second attempt

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…

A method to flip a coin - third attempt

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.

A method to roll a die

Finally back on track. It used ThreadLocalRandom correctly and the method really simulates 6-sided die.

A class that flips a coin and rolls a 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.

A class that flips a coin and rolls a die - second attempt

It changed the name to a more generic one and made the class final which in this case was enough to make it immutable.

Overall impression

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!

All the prompts in order

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!