r/javahelp

How do I design a class that can switch between different implementations at runtime

 I have a game where a Character class needs to change behavior from Villager to Enemy after certain conditions are met. I know I can't change an object's class at runtime in Java. What's the best pattern to achieve this instead. I've looked at Strategy pattern but that seems to change only algorithms not the whole behavior set. Should I use composition where the Character holds a reference to an interface like CharacterType and swap that reference when needed. Or is there a cleaner way using delegation. I want to avoid huge ifelse chains checking a state variable. Any code examples or pattern names would be really helpful. Thanks.

reddit.com
u/prattman333 — 9 hours ago

What are the most important concepts to master in Java before moving to frameworks like Spring?

kindly give me some suggestion

reddit.com
u/Wise_Safe2681 — 8 hours ago

Are the javadocs for java.net.http.HttpResponse.body() misleading or am I wrong?

This has caused some internal discussion, so I wanted to look for external input.

If you have ever used the newer java.net.http implementation, you probably have used the HttpResponse.body() method to retrieve the response body. It usually looks something like this:

HttpClient client = HttpHelper.client();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("<uri>"))
        .POST(HttpRequest.BodyPublishers.ofString(content))
        .build();
HttpResponse<String> res = client.send(request, HttpResponse.BodyHandlers.ofString());

// Can this be null?
String bodyString = res.body();

Then, looking at the javadocs for the body() method, it says:

* Returns the body. Depending on the type of {@code T}, the returned body
* may represent the body after it was read (such as {@code byte[]}, or
* {@code String}, or {@code Path}) or it may represent an object with
* which the body is read, such as an {@link java.io.InputStream}.
*
* <p> If this {@code HttpResponse} was returned from an invocation of
* {@link #previousResponse()} then this method returns {@code null}
*
* @return the body

Here is how I interpreted this: Assuming that there is no IOException thrown, the request must have gone through (even if it returned something like a HTTP 500) and we should have response body. Since we don't use the previousResponse() method, the note about null values does not apply here. The rest of the javadocs don't mention anything about null, so I implicitly assumed that it does not return null. If there is an empty body, then it returns an empty String/byte[]/whatever. The BodyHandlers javadocs don't mention anything about null return values.

But the method returns null for something like HTTP 407 Proxy Authentication Required.

So my question is: If you read the javadocs of a JDK method and it does not mention null return values, do you interpret this as that the method does not return null? Or do you still perform null checks as the javadocs also didn't mention about not returning null?

reddit.com
u/milchshakee — 1 hour ago
▲ 3 r/javahelp+1 crossposts

Java "for loop" vs "enhanced for loop"

Both are used for iteration, but they solve slightly different problems. I show the practical differences, the tradeoffs, and the situations where one loop gives you more control while the other gives you cleaner and more readable code. https://youtu.be/Pgt1eN3e-pc

u/Efficient-Public-551 — 6 hours ago

Java import is not working in VSCode

I have this problem for so long time now. I am studying computer Sience and we got a .jar file from our lecturer and we have to work with it. Usually we are using Eclipse in class, but I love using VSCode and it won't work there. A fellow student is also using VSCode and it works. I tried everything, but nothing works. Not even my lecturer knows how to fix this issue.

We have to use Java for this task and need to import some Classes from the .jar file the lecturer gave us. So I added it into the Referenced Libraries. It still can't find the File apparently.

The Issue says "The import de.vitbund.netmaze.connector.Ibot cannot be resolved Source: VitNetMaze.jar"

The Github Copilot Chat also does not know the answer. Every time he says I fix it, but he changed nothing.

This is very odd, because the autocomplete feature is finding all the methods from the .jar. So it is finding it kind of?

The same project is working fine in Eclipse, so I thougt this must be a VSCode problem right?

If there are some Java programmes using VSCode please help me!!!

I' m not sure if this subreddit is the right place to ask this question. If someone knows a better subreddit to post this one would help me too.

package bot;


import de.vitbund.netmaze.connector.Action;
import de.vitbund.netmaze.info.GameEndInfo;
import de.vitbund.netmaze.info.GameInfo;
import de.vitbund.netmaze.info.RoundInfo;
import de.vitbund.netmaze.connector.IBot;


public class MinimalBot implements IBot {


    u/Override
    public String getName() {
        // TODO Auto-generated method stub
        return null;
    }


    u/Override
    public void onError(Exception arg0) {
        // TODO Auto-generated method stub
        
    }


    u/Override
    public void onGameEnd(GameEndInfo arg0) {
        // TODO Auto-generated method stub
        
    }


    u/Override
    public void onGameStart(GameInfo arg0) {
        // TODO Auto-generated method stub
        
    }


     bot;


import de.vitbund.netmaze.connector.Action;
import de.vitbund.netmaze.info.GameEndInfo;
import de.vitbund.netmaze.info.GameInfo;
import de.vitbund.netmaze.info.RoundInfo;
import de.vitbund.netmaze.connector.IBot;


public class MinimalBot implements IBot {


    u/Override
    public String getName() {
        // TODO Auto-generated method stub
        return null;
    }


    u/Override
    public void onError(Exception arg0) {
        // TODO Auto-generated method stub
        
    }


    u/Override
    public void onGameEnd(GameEndInfo arg0) {
        // TODO Auto-generated method stub
        
    }


    u/Override
    public void onGameStart(GameInfo arg0) {
        // TODO Auto-generated method stub
        
    }


    u/Override
    public Action onNewRound(RoundInfo arg0) {
        // TODO Auto-generated method stub
        return null;
    }


}
    public Action onNewRound(RoundInfo arg0) {
        // TODO Auto-generated method stub
        return null;
    }


}
reddit.com
u/Meun3D — 4 hours ago

Should I use Lanterna to create a TUI application or is Java not suitable for this?

I recently started using the terminal version of Joplin, the note taking app, while setting up linux servers as it's my first time setting those up and I want to be able to go back and remember how to do everything. I really like it and I've been looking for another project idea to get me to program more. So I want to basically build the same app but in a language that I know which is Java.

So far all I've found is the lanterna library to start doing this but the more I look, the more I think it would just make more sense to go to C or Rust for this.

Does anyone have any experience with Lanterna? Is it a robust library that gives you lots of options when it comes to design? I want it to have the sort of ascii art looking feel to it so the GUI element of lanterna I am not that interested in.

reddit.com
u/RustieJames — 3 days ago

Am I not self-sufficient enough when it comes to solving problems that I see for the first time?

Hi all, I have this habit where whenever I see a new problem, instead of trying out the most naive approach to the problem that I can think of (due to a mental blockade in my head thinking that I won't be able to solve the problem in the most "efficient" way, even though I don't exactly have the criteria of what efficient look like, maybe the time doing Leetcode has messed up my brain with all of the arbitrary acceptance requirements, I'm also afraid of the fact that the approach that I come up with have bugs due to edge cases that I haven't think of), I instead choose to go online and search to see how other people have solved this problem (since I assume that I am not the first one that encountered such problem). However I feel like doing this overtime will lower my ability to think and reason with different approaches to the same problem, which will ultimately cause me to not being able to solve a genuinely new problem that I (and probably the internet) have never seen before.

Is anyone else experiencing this issue, and for the people who have overcame this, how did you guys do it? Thanks in advance, y'all!

reddit.com
u/Expensive-Tooth346 — 2 days ago

Some help with code

Hello! I finally decided to do the push into trying to make a simple game on Java, starting with a simple text game. I do have some programming knowledge, and I'm using this game making to help me learn more about the language. I've been following a tutorial on how to make a game, and it has been going good so far execept for one thing. When making the main menu, everything went well on adding the main text and button, but, for some reason, while changing the size of the text of the button something broke on the code, and text has disappeared from the title panel. The button that was there previously is now also gone. Anyone can elighten me on what's wrong?

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Game {
    JFrame window;
    Container con;
    JPanel titleNamePanel, startButtonPanel;
    JLabel titleNameLabel;
    Font titleFont = new Font("Times New Roman", Font.PLAIN, 80);
    Font normalFont = new Font("Times New Roman", Font.PLAIN, 28);
    JButton startButton;  
    public static void main(String[] args) {
         new Game();
    }
    public Game() {
        window = new JFrame();
        window.setSize(800, 600);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.getContentPane().setBackground(Color.darkGray);
        window.setLayout(null);
        window.setVisible(true);
        con = window.getContentPane();


        titleNamePanel = new JPanel();
        titleNamePanel.setBounds(85, 100, 600, 100);
        titleNamePanel.setBackground(Color.black);
        titleNameLabel = new JLabel("WIZARD GAME");
        titleNameLabel.setForeground(Color.white);
        titleNameLabel.setFont(titleFont);


        startButtonPanel = new JPanel();
        startButtonPanel.setBounds(300, 400, 200, 100);
        startButtonPanel.setBackground(Color.black);


        startButton = new JButton("START");
        startButton.setBackground(Color.black);
        startButton.setForeground(Color.white);
        startButton.setFont(normalFont);


        
        titleNamePanel.add(titleNameLabel);
        startButtonPanel.add(startButton);
        con.add(titleNamePanel);
        con.add(startButtonPanel);
    }


}
reddit.com
u/ResearcherThese8675 — 2 days ago

Exclude directory in gradle task without editing build.gradle?

So I'm trying to modify a gradle task (exclude a particular directory) in a project without editing the build.gradle file. How can I do so?

Some more context:

I am trying to use IntelliJ to work on an existing Java code base. I am unable to edit build.gradle due to restrictions imposed by the maintainers of the code base. The problem is that IntelliJ creates a .idea directory to store project config data, but this is not properly excluded in build.gradle. As such, the build will include the .idea directory, which is something I do not want.

I am aware of the possibility of adding init.d/init.gradle to my gradle home directory, but it's not a good option for me as I want the solution to be within my project root.

Appreciate any advice, thanks!

reddit.com
u/5haco — 3 days ago

Any fellow Java devs building SaaS ? Looking for a quick code review on my Paddle integration!

Hey everyone!

I’m a Java developer making the jump into the SaaS world. It’s been a really fun journey so far, but navigating the billing side definitely has its learning curve.

I just finished writing the backend integration for Paddle to handle my subscriptions, but since I'm fairly new to SaaS billing architecture, I want to make sure I'm on the right track before launching.

I'm hoping to get some feedback.

It’s not a massive chunk of code—just the core billing services. I’d massively appreciate a second set of eyes from someone who has walked this path before!

Thanks so much in advance! 🚀

This is the GitHub repository

u/the_fresh_G — 3 days ago

What's a good template / project structure i can find online and base my spring-boot project on?

Basically what the title says , i tried looking up resources myself but couldnt find any, and if the question is stupid , forgive me i come from a nodejs background and i am not that familiar with the spring , but looking to start learning it!

Thank you

reddit.com
u/No-Sprinkles-1754 — 3 days ago

Java equivalent of .NET Solution?

Hi! coming from C#.NET and I’m confused about Java project structure, a little bit.

In Visual Studio and Rider, you have a Solution with multiple Projects inside.
In IntelliJ IDEA, it feels like you just create a project directly? Kind of.

What’s the Java equivalent of a Solution? How do you group multiple related projects?

Is that handled by IntelliJ or Maven? Thx!

reddit.com
u/gameramante — 5 days ago

Dependency Injection in Spring Boot (under 2 minutes)

I made this quick tutorial covering what Dependency Injection is, the purpose of it, and how to use it in Spring Boot: https://youtu.be/S23r5oaEA-8

Hope you enjoy!

u/BuckFrog2 — 5 days ago

Short study on understanding security analysis output (Java developers)

We are conducting a short (15-20 minute), anonymous academic study on how developers understand the output of a security analysis tool for Java programs.

We are looking for Java developers or advanced CS students and would much appreciate your feedback on how to improve the usability of this tool. No prior security background is required. Participation is voluntary and non-commercial.

Link to the form:

Usability Study of a Tool for Security Analysis of Java Programs – Fill in form

reddit.com
u/secsumtool — 2 days ago

downloading file in parallel?

I am trying to download one big file parallel in multiple chunks with threadAPI and runnables, but my friend said executor with virtualthreads (callables) has better performance...

What is the normal way to do this?

reddit.com
u/Electronic_Site2976 — 5 days ago

String object vs String variable

Hi i am learning java in highschool, I was just wondering when and why would I instantialise a string as an object when declaring a String is much easier and quicker?

reddit.com
u/Nottheugis — 6 days ago

Is there a way to mimic the behaviour of -client to spawn a lightweight process in JDK 11 and higher versions?

In JDK 8, we had the -client flag that would spawn a lightweight process with less memory footprint and a faster startup. I understand that the Client Hotspot VM is no longer available JDK 9 onwards, and I was looking for a way to reduce the startup time while launching a new java process. Any inputs?

reddit.com
u/ABaradwaj — 5 days ago

Is TestNG still being used in 2026?

Even when it was relatively popular (10-15 years ago) I've rarely seen a project which used TestNG. Do ppl still use it for new projects? Are there any advantages over JUnit 5? Just curious.

reddit.com
u/oweiler — 5 days ago

Why should I use the new switch expressions instead of classic switch statements?

I keep seeing modern Java code using the new switch expressions with arrows and no fallthrough. My team still uses the old style with colons and break statements. We are on Java 17 but nobody seems to care about the newer syntax. What actual advantages does the new switch have besides looking cleaner? Does it help prevent bugs or make the code more readable in real projects? I want to convince my team to adopt newer patterns but I need solid reasons beyond it looks new. Can anyone give me concrete examples where the new switch expression saved them from a stupid mistake?

reddit.com
u/Unlucky-Moment-3366 — 7 days ago

java underhyped in 2026 ?

my question is for senior devs in enterprise level companies, fortund 100, banking, insurance sector. python and javascript I feel are overhyped, used by startups cause they want ai and speed but are big mnc's also switching to these ? what langs do you ppl use ? also i have heard as of now it is difficult to a job as a java dev for a fresher so would learning python or javascript be more benificial from a jobs perspective ?

reddit.com
u/dante_alighieri007 — 8 days ago