Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ChatGPT and Java

 
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ChatGPT is a free text AI program. I asked it:
Me: "write a java program that will write 220000000000 random bytes to a file"
Bot:
Output:
My comment: Not the most efficient and doesn't use try-with-resources but usable. It also didn't detect that the long number was out of range for an int.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: 220000000000 won't fit in an int

Bot: You're correct. The value 220000000000 is too large to fit into an int data type in Java. To handle such a large number of bytes, we need to use a type that can handle larger values, such as long.

Here's an updated version of the program that uses long instead of int:
((revised code))
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: can you re-write to use try-with-resources

Bot: Sure, here's the updated code that uses the try-with-resources statement:
Output:
The try-with-resources statement ensures that the FileOutputStream is automatically closed at the end of the try block, even if an exception is thrown. This helps avoid resource leaks.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: add a BufferedOutputStream to make it more efficient

Bot: Here's the updated code that uses a BufferedOutputStream to improve performance:
Output:
The BufferedOutputStream class provides a buffer, which helps reduce the number of low-level write operations performed on the underlying FileOutputStream. This can result in improved performance by reducing the number of disk I/O operations.

With the BufferedOutputStream, data is stored in memory until the buffer is full, at which point it is flushed to the underlying stream. The BufferedOutputStream also automatically flushes the buffer when the stream is closed, ensuring that all data is written to the file.
 
Saloon Keeper
Posts: 15437
361
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is pretty damn cool. I haven't tried ChatGPT yet, but I was already quite impressed with what I've seen from social media posts. However, so far I haven't seen any examples of somebody having a conversation with it so that it can revise its answers. That is really neat and impressive.
 
Marshal
Posts: 79023
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What happens if you tell it to use Allman indentation?
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bot:
Output:

 
Campbell Ritchie
Marshal
Posts: 79023
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not bad!
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: make "random" a static final class member

Bot:
To make the Random instance a static final class member, you can declare it as a private static final field in the WriteRandomBytes class. Here's the modified code:
This modification ensures that the Random instance is created only once for the lifetime of the WriteRandomBytes class, and can be used by all instances of the class, if any. The static keyword makes the field belong to the class rather than to any specific instance, and the final keyword makes the field immutable once it is initialized. By convention, the field name is in uppercase to indicate that it is a constant.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: use a constant to hold the file name

Bot:
To use a constant to hold the file name, you can declare a private static final string field in the WriteRandomBytes class, and initialize it with the file name. Here's the modified code:
This modification ensures that the file name is defined as a constant and can be easily changed if needed. The static keyword makes the field belong to the class rather than to any specific instance, and the final keyword makes the field immutable once it is initialized. By convention, the constant name is in uppercase with underscores to separate words.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: make "numBytes" a constant
Me: use Allman indentation style
...

 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: insert underscores in numeric constant as delimiter

Bot:
To make a long numeric constant easier to read, you can use underscores as delimiters to separate groups of digits. Here's the modified code for the WriteRandomBytes class with underscores in the NUM_BYTES constant:
In this modified code, the NUM_BYTES constant is written with underscores to make the number easier to read. The underscores don't affect the value of the constant, they just make it easier to read. By convention, the underscores are placed between groups of three digits in a long number.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me: modify file name to include a current date-time stamp

Bot:
To modify the FILE_NAME constant to include a current date-time stamp, you can use the java.time package to get the current date and time, format it into a string, and concatenate it with the file name. Here's the modified code for the WriteRandomBytes class with the date-time stamp in the file name:
In this modified code, the FILE_NAME constant is set to "random_bytes_" + getDateTimeStamp() + ".bin". The getDateTimeStamp() method uses the LocalDateTime class to get the current date and time, formats it into a string using the DateTimeFormatter class, and returns the formatted string. The DateTimeFormatter pattern "yyyyMMdd_HHmmss" formats the date and time into a string with the year, month, and day followed by the hour, minute, and second, separated by underscores. The formatted date-time string is then concatenated with the file name and the file extension to create the complete file name.
 
Marshal
Posts: 8837
631
Mac OS X VI Editor BSD Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried to use it in the past, but it always was at capacity, so couldn't log in.
Now seeing this topic gave a try once again - it worked!

To be honest, a word impressive is the least we can say here.

Sorry Carey for stepping in with my query here, but just one:


Query: Write a Java controller example using spring framework

Answer:

Accompanying information provided in addition to code:

In this example, we're defining a controller class called GreetingController with a single method called greeting. The @Controller annotation indicates that this class is a Spring MVC controller, and the @GetMapping annotation specifies that the greeting method should handle GET requests for the /greeting endpoint.

The greeting method takes two parameters: a name parameter, which is an optional query parameter, and a Model parameter, which is used to pass data to the view. The @RequestParam annotation specifies that the name parameter should be bound to the name query parameter in the request, with a default value of "World" if the query parameter is not present.

Inside the method, we add the name parameter to the model, using the model.addAttribute method. This makes the name value available to the view for rendering.

Finally, the greeting method returns a String representing the name of the view that should be rendered. In this case, it returns the string "greeting", which will cause Spring to look for a view template called "greeting.html" (or a similar file with a different extension) in the appropriate location.



Query: Could you implement an OpenAPI spec with this controller instead of adding annotations to controller

Answer:

Yes, you can use OpenAPI to document your API and generate the controller code, instead of adding annotations to the controller. Here's an example of an OpenAPI specification that describes the same API that we defined earlier:



Also a lot of accompanying explanation added to explain pretty much every block what it means.

Query: Generate java server using defined OpenAPI spec

Answer:

To generate a Java server from an OpenAPI specification, you can use a code generator like Swagger Codegen. Here's how you can generate a Java server from an OpenAPI spec:

Install Swagger Codegen. You can download it from the Swagger Codegen GitHub repository or use a package manager like Homebrew or apt-get to install it.
Download or create an OpenAPI spec. The spec should describe the API that you want to generate a server for.
Use Swagger Codegen to generate the Java server. The command to generate the Java server might look something like this:



And again bunch of further explanation.


Man, I don't know the limits of this, but from what it looks, it is just a matter of yourself being able to explain stuff clearly, the rest is handled.

I don't know how to react even to this, whether to be happy or rather worried, but very very shocking.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:just a matter of yourself being able to explain stuff clearly

That's the tricky part but even when I wasn't sure of the correct words (e.g. a lambda query I had) it pulled up something close enough that allowed me to rephrase my query and get my answer.

There are some things I wish GPT would remember like wanting output in Allman indentation style or using underscores in numeric constants as an example. (Hmmmm maybe I'll ASK GPT to remember and see what it says)

My daughter programs in IDL (astro-physics) which is a niche language I don't  know anything about so I started asking noob questions and there was a flood of information and examples.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
... said it would remember and it appears to have worked
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
are the things I ask you to remember available across multiple chats

As an AI language model, I can't remember previous conversations or settings across multiple chats. Each chat session is independent of the others, and any modifications or preferences discussed during a particular chat session will only apply to that session. However, I can certainly try to remember any specific preferences or modifications that you request within a single chat session, and apply them consistently throughout that session.


Note:
Using ChatGPT via OpenAI gives you a list of your chat sessions in a column down the left side so that you can return to and continue a previous chat session.
 
Saloon Keeper
Posts: 27697
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A thought.

Much is made about AI replacing programmers, but new software development is typically not the bulk of what programmers do, at least in places I've worked.

Where help is actually needed is in analyzing, documenting and maintaining existing systems.

Case in point. We've got a thread going currently where the OP is hoping to use some sort of tool to plot out classes and functions for an inherited Java app, probably as a UML diagram.  As I noted there, and have noted before, one problem with the UML toolkit is that the resulting diagrams have no sense of importance and are thus more useful as wallpaper than as references. A properly developed AI would hopefully sort things out and arrange/hightlight into something actually useful.

Another thing I've often noted is that lot of the mission-critical systems I've seen were basically hacked out by one or 2 people of questionably sobriety over a weekend. They've often got serious integral warts, but no one dares to address them until they're close to the breaking point, at which attempts to overhaul/rewrite often fall victim to Fred Brooks' Second System Effect.

Documentation for such systems (and quite a few open-source projects) tends to be minimal, out of date, and frequently assumes the reader knows things that only the developers knew. Here again, AI could be a major help.

So before we spend too much time automating programming, perhaps we should invest some time in making existing programming a better place.
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This would be an interesting experiment to try with ChatGPT on a small scale. Give it the source code for a small project and see how much help it  needs to "understand" what's happening in the code. Then can it write documentation for it? Can it answer questions about it?
 
Carey Brown
Saloon Keeper
Posts: 10641
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
REVERSE ENGINEERING:
Note: Started a new CHAT thread for this topic.

BOT:
Output:
This Java program generates a file containing random bytes of a specified size. Here is an explanation of the code:

  •    The program imports several Java classes for file and date/time operations.
  •    The class WriteRandomBytes contains a private Random object and two constants: FILE_NAME and NUM_BYTES.
  •    The main method opens a BufferedOutputStream object to write bytes to the file specified in FILE_NAME.
  •    A loop is executed NUM_BYTES times, where each iteration writes a random byte to the output stream using bos.write(RANDOM.nextInt(256));.
  •    If an exception is caught, an error message is printed to the console.

  • Note that the program generates a file with a very large size (NUM_BYTES = 220_000_000_000L). This could potentially cause performance or storage issues on the computer running the program.
     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    REVERSE ENGINEERING:
    Input:

    BOT:
    This Java program searches for a regular expression pattern in the contents of jar files. Here is an explanation of the code:
  •    The program imports several Java classes for file and zip operations.
  •    The FileJarSearch class contains static variables for the search options (recursive, ignoreCase, and pattern) and a usage method to print command-line usage instructions.
  •    The main method processes command-line arguments to set the search options and pattern, then calls the process method to search for the pattern in each file or directory specified.
  •    The process method checks if the specified file exists, and if so, determines if it is a jar file or a directory. If it is a directory, the method recursively calls itself on each file in the directory. If it is a jar file, the method calls searchJar to search for the pattern in the jar file.
  •    The searchJar method opens a ZipInputStream to read the contents of the jar file, then searches for the pattern in each entry name in the jar file. If the pattern is found, the method prints the file path and entry name to the console.

  • Note that the program assumes that jar files have the .jar file extension. If jar files have a different file extension, the program will not find them.
     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Me:  can you suggest improvements to the code

    BOT:
    Sure! Here are a few suggestions for improving the code:

       Add error handling: Currently, the program does not handle any exceptions that may occur during file and zip operations. It would be a good idea to add error handling to gracefully handle any exceptions and prevent the program from crashing.

       Use try-with-resources: The program currently opens file streams and a zip stream using the traditional try-catch-finally block. It is recommended to use the try-with-resources statement to automatically close the streams when they are no longer needed.

       Use Path instead of File: The File class is an older API for file operations in Java. The newer Path API is more flexible and provides additional functionality. You could update the code to use Path instead of File.

       Improve performance: The program reads the entire contents of a jar file each time it searches for a pattern. This can be inefficient if the jar file is large. To improve performance, you could consider reading the contents of the jar file only once and storing them in memory, then searching the in-memory contents for each pattern.

       Add unit tests: The program does not have any unit tests to ensure that it functions correctly. It would be a good idea to write some unit tests to verify that the program correctly searches for the pattern in jar files and handles different file types and search options.

       Refactor the code: The process method is quite long and contains multiple levels of indentation. You could consider refactoring the code to break the method into smaller, more focused methods with descriptive names. This would make the code easier to understand and maintain.
     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I corrected an assumption it made:

    Only one pattern is used per execution

    Then it implemented the suggestions which broke the recursive test for levels.

    ??!!!

    I explained the need for levels and it put it back in.
     
    Tim Holloway
    Saloon Keeper
    Posts: 27697
    196
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Now* do it on my 15,000-line mainframe assembly language system that takes output files from a batch transaction processing system and splatters them to all sorts of output media.

    Scratch that. Here's something practical. Take the source for FreeCAD and generate functional docs for its internal operations. In particular, I'd like to know how to make it automatically switch metrics between multiple open documents so that both Metric and US units are handled properly according to the system in use on the active document. The people in charge of it don't know enough about the system to suggest how to broadcast the change to the UI.

    Putting information about what metric system a given document in to the document meta-data was easy. Making it display properly in the properties editor is a mystery.

    ===
    * Edited correction. Lost the "t" on "not"!
     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Tried using Bard to create the same "write random bytes to a file" problem and it struggled and failed. At first it was using  a small  enough number of bytes that it would  fit in an int. When I requested that it change the value to 220 Gigs it was all down hill from there even with gentile hints. At this point it has even lost the constant that had the 220Gig value.

     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Additionally, I requested that it display the code in Allman style. It gave a short description of what Allman style entails, then said "here it is", and re-displayed the code in K&R again.

    Not going to be taking anybody's job anytime soon.
     
    Campbell Ritchie
    Marshal
    Posts: 79023
    375
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    How did you tell it to use 220Gig? That is beyond the limits of an int.
    I would like to know who taught it to write
     
    Tim Holloway
    Saloon Keeper
    Posts: 27697
    196
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:
    I would like to know who taught it to write

    It probably scraped it from innumerable example questions posted by newbies on the Ranch. And didn't "see" where we told them not to.
     
    Liutauras Vilda
    Marshal
    Posts: 8837
    631
    Mac OS X VI Editor BSD Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tim Holloway wrote:It probably scraped it from innumerable example questions posted by newbies on the Ranch. And didn't "see" where we told them not to.


    Like the other day I was reading, that ChatGPT does not have creativity, it just takes what has been written by us engineers. So now one needs to be careful when writing code.
     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:How did you tell it to use 220Gig? That is beyond the limits of an int.


    220_000_000_000
    First is assigned it to an int constant and used the constant to allocate a byte array. Then I pointed out it wouldn't fit in an int so it turned it into a long but in the array allocation it just cast it back to an int. Then I pointed out the array would be too large and that another approach would be needed it totally scrambled.
     
    Campbell Ritchie
    Marshal
    Posts: 79023
    375
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:. . . 220_000_000_000 . . .

    There's no answer to that one!
     
    Carey Brown
    Saloon Keeper
    Posts: 10641
    83
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    My third post in this thread was a suitable answer created by ChatGPT. Bard just went off the deep end and created some unfathomable code that both wrote and read from the file.
     
    Any sufficiently advanced technology will be used as a cat toy. And this tiny ad contains a very small cat:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic