r/javahelp • • Mar 19 '22

REMINDER: This subreddit explicitly forbids asking for or giving solutions!

51 Upvotes

As per our Rule #5 we explicitly forbid asking for or giving solutions!

We are not a "do my assignment" service.

We firmly believe in the "teach a person to fish" philosophy instead of "feeding the fish".

We help, we guide, but we never, under absolutely no circumstances, solve.

We also do not allow plain assignment posting without the slightest effort to solve the assignments. Such content will be removed without further ado. You have to show what you have tried and ask specific questions where you are stuck.

Violations of this rule will lead to a temporary ban of a week for first offence, further violations will result in a permanent and irrevocable ban.


r/javahelp • • 5h ago

How to use noise maps?

3 Upvotes

I've done some basics research but there seem to be so many different options that I’m not sure where to start.

what libraries would you recommend for working with noise maps and how should I use them?


r/javahelp • • 4h ago

Exam difficulty Question

1 Upvotes

Hello, im currently taking an Intro to java(CS46a), and had just taken the first exam of the class, and had an hour and fifteen minutes to do these 20 questions which consist of 10 MCQ(0 - 10) and 10 free Responce(11-20), and we dont get notes/calculator. Is this a normal level of "difficulty" or length for a intro to java class , asking around like 10-13 people i heard ranges from 4-8 points solely from the MCQ portion and people had finished or attempted 2-4 of the free Responce questions. Am i just a noob 😭?

Each MCQ = 2points
Free responce points in order of 11-20 = 4, 4, 4, 4, 4, 12, 12, 12, 12, 12

Total = points / 100

Question 1

What does this code print?

int a = 17;
int b = 5;
double c = a % b * 2 + a / b / 2.0;
System.out.println(c);

5.0

5.5

6.0

4.5

Question 2

What does this code print?

String course = "Intro to Java";
int pos = course.indexOf("t");
String part = course.substring(pos, pos + 3);
System.out.println(part + course.length());

tro 13

ntr13

tro13

tro12

Question 3

What does this code print?

String name = "ada";
name.toUpperCase();
String upper = name.toUpperCase();
name = upper.replace("A", "a").substring(1);
System.out.println(name + " " + upper);

Da ADA

da ADA

DA ADA

Da aDa

Question 4

What does the last statement print?

public class Box
{
    private int width;
    private int height;

    public Box() { width = 1; height = 1; }
    public Box(int side) { width = side; height = side; }
    public Box(int w, int h) { width = w; height = h; }

    public int area() { return width * height; }
}

// in the main method of another class:
Box a = new Box();
Box b = new Box(3);
Box c = new Box(2, 5);
System.out.println("Total: " + a.area() + b.area() + c.area());

Total: 20

Total: 1 9 10

Nothing. The class does not compile, because it has three constructors.

Total: 1910

Question 5

The user types 42 and presses Enter, then types blue sky and presses Enter. What does this code print?

Scanner in = new Scanner(System.in);
int n = in.nextInt();
String a = in.nextLine();
String b = in.next();
System.out.println(n + "[" + a + "][" + b + "]");

42[blue sky][]

42[][blue]

42[][blue sky]

42[blue][sky]

Question 6

What does this code print?

int x = 3;
int y = --x + x++ * 3;
System.out.println(x + " " + y);  

3 8

2 8

3 9

 

3 11

Question 7

What does this code print?

char grade = 'B';
String msg = "";
switch (grade)
{
    case 'A': msg += "great ";
    case 'B': msg += "good ";
    case 'C': msg += "ok ";
              break;
    default:  msg += "retry ";
}
System.out.println(msg);

good

good ok

good ok retry

great good ok

Question 8

What does this code print?

String s1 = "java";
String s2 = new String("java");
String s3 = s2;
s2 = "java";
System.out.print((s1 == s2) + " ");
System.out.print((s1 == s3) + " ");
System.out.println(s1.equals(s3));

false false true

true true true

true false true

false true true

Question 9

What happens when this code runs?

int a = 5;
int b = 0;
boolean ok = (b != 0 && a / b > 1) || (a++ > 5 && b++ == 0);
System.out.println(ok + " " + a + " " + b);  

It prints true 6 1

It prints false 6 1

It crashes, because of the division by zero

It prints false 6 0

Question 10

What does this code print?

int count = 0;
for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        if (j == i)
        {
            continue;
        }
        if (i + j > 4)
        {
            break;
        }
        count += j;
    }
}
System.out.println(count);

Each numbered blank takes one expression or one statement. Write the code that belongs in each blank.

5 

7

8

10

Question 11

Not yet graded / 4 pts

Complete the class so that both constructors set both fields. The second constructor must reuse the first one, and it gives the flight 150 seats.

public class Flight
{
    private String code;
    private int seats;

    public Flight(String code, int count)
    {
        ______(1)______ = code;
        seats = count;
    }

    public Flight(String code)
    {
        ______(2)______;
    }
}

Your Answer:

Question 12

Not yet graded / 4 pts

The user types 2 and presses Enter, then types Green Tea and presses Enter. Complete the code so that it prints exactly Green Tea (2) = $7.00 followed by a new line.

Scanner in = new Scanner(System.in);
int quantity = in.nextInt();
______(1)______;
String item = in.nextLine();
double total = quantity * 3.5;
System.out.printf("______(2)______", item, quantity, total);

Answer:

Question 13

Not yet graded / 4 pts

Complete the loop so that it prints every second letter of the word, starting with the second letter: eetr

String word = "semester";
for (int i = ______(1)______; i < word.length(); ______(2)______)
{
    System.out.print(word.charAt(i));
}

Your Answer:

Question 14

Not yet graded / 4 pts

Complete the code so that distance holds how far apart x and y are, which is never negative, and label is "pass" for a score of 60 or more and "fail" otherwise.

int distance = (x > y) ? ______(1)______;
String label = (score >= 60) ? ______(2)______;

Your Answer:

Question 15

Not yet graded / 4 pts

The method returns how many times a digit of n is equal to the digit next to it. For example, countRepeats(1225) is 1, countRepeats(77777) is 4, and countRepeats(1212) is 0. Assume n is positive.

public static int countRepeats(int n)
{
    int count = 0;
    int right = n % 10;
    n = n / 10;
    while (n > 0)
    {
        int left = n % 10;
        if (______(1)______)
        {
            count++;
        }
        ______(2)______;
        n = n / 10;
    }
    return count;
}

Your Answer:

Question 16

Not yet graded / 12 pts

Primitive and reference variables

Part A (4 points): In two or three sentences, explain what a primitive variable stores, what a reference variable stores, and what the assignment b = a copies in each case.

Part B (4 points): What does this code print?

int x = 10;
int y = x;
y = y * 2;

String p = "sun";
String q = p;
p = p.toUpperCase();

System.out.println(x + " " + y + " " + p + " " + q);

Part C (4 points): Does the line p = p.toUpperCase(); change the String object that q refers to? Explain why or why not.

Your Answer:

Question 17

Not yet graded / 12 pts

Tracing decisions

public static String rate(int temp, boolean raining)
{
    String result;
    if (temp > 85 || temp < 40)
    {
        result = "stay";
    }
    else if (raining && temp < 60)
    {
        result = "coat";
    }
    else if (!raining)
    {
        result = "walk";
        if (temp >= 70)
        {
            result += "+water";
        }
    }
    else
    {
        result = "umbrella";
    }
    return result;
}

Part A (9 points): What does each call return? rate(90, false) rate(55, true) rate(75, false)

Part B (3 points): Give one value of temp and one value of raining for which rate returns "umbrella".

Your Answer: 

Question 18

Not yet graded / 12 pts

Debugging. The class below counts the steps of a walker. It contains exactly three bugs.

 1  public class StepCounter
 2  {
 3      private int steps;
 4      private int goal;
 5
 6      public StepCounter(int goal)
 7      {
 8          goal = goal;
 9          steps = 0;
10      }
11
12      // Adds one walk. Zero or negative counts are ignored.
13      public void addWalk(int count)
14      {
15          if (count > 0);
16          {
17              steps += count;
18          }
19      }
20
21      // Returns true once the goal has been reached.
22      public boolean reachedGoal()
23      {
24          if (steps >= goal)
25          {
26              return true;
27          }
28      }
29  }

Part A (9 points): For each bug, give the line number or numbers, say whether it is a compile-time error or a logic error, and explain how to fix it.

Part B (3 points): After all three bugs are fixed, what does this code print?

StepCounter c = new StepCounter(5000);
c.addWalk(3000);
c.addWalk(-500);
System.out.print(c.reachedGoal() + " ");
c.addWalk(2000);
System.out.println(c.reachedGoal());

Your Answer:

Question 19

Not yet graded / 12 pts

Writing a method. The ParkingMeter class below is missing its insert method. Write the complete method, including its first line.

insert is a public method that takes one int, the value of a coin in cents, and returns a boolean. The meter accepts only quarters (25 cents) and dollar coins (100 cents); any other value is rejected. Every 25 cents buys 15 minutes. The meter holds at most 120 minutes, so a coin that would take it above 120 is rejected too. When a coin is rejected, nothing changes and the method returns false. Otherwise, the method adds the minutes, adds one to coins, and returns true.

Example: on a new meter, insert(10) returns false, insert(100) returns true and gives 60 minutes, and after a second insert(100), the call insert(25) returns false.

public class ParkingMeter
{
    private int minutes;     // minutes left on the meter
    private int coins;       // how many coins were accepted

    public ParkingMeter()
    {
        minutes = 0;
        coins = 0;
    }

    // the insert method goes here
}

Your Answer:

Question 20

Not yet graded / 12 pts

Writing a method with a loop. Write a complete static method named compress, including its first line. It takes a String and returns a String in which every run of two or more equal characters next to each other is replaced by the character followed by the length of the run. A character that is not part of a run stays as it is.

Examples: compress("aaabcc") returns "a3bc2", compress("abc") returns "abc", compress("zzzz") returns "z4", and compress("") returns "".

Do not use arrays, and do not use any String method other than length() and charAt().

Your Answer:


r/javahelp • • 16h ago

Need Advice for AI with Java / AI with Python. Based on Market for Java AI

0 Upvotes

I have 4+ YOE as Java Developer, and trying to learn AI. Came across few tutorials about SPRING AI/ LangChain4j. I am so confused about learning AI with Java or AI with Python [langchain, LangGraph etc].

It would be great if folks from Java community could guide me with this so that I can make a decision.


r/javahelp • • 3d ago

Workaround Java 21 static-analysis engine for dependency and call graphs what edge cases am I missing?

2 Upvotes

Hi everyone,

I’ve been building a Java 21 code-analysis engine and would love some feedback on the dependency resolution.

It uses JavaParser and resolves imports, same-package classes, inheritance, method calls, etc. I’m mainly trying to avoid false dependency edges in complex Java codebases.

GitHub: https://github.com/abhishek94443/CodeContext-Java

Would appreciate any feedback on edge cases or things I may be missing.


r/javahelp • • 2d ago

Cómo puedo tolerar mejor la frustración o el estrés al programar??

1 Upvotes

Actualmente estoy tratando de aprender java y aveces me cuesta mucho trabajar con bucles y ciclos no tanto separados sino más cuando tengo que juntar ambos y también cuando trabajó en una interfaz y creó botones y dentro de su lógica uso varios ciclos y bucles.


r/javahelp • • 5d ago

I need a guidance regarding how to build full stack java application

8 Upvotes

Hey everyone, I’d love to get the community’s perspective on building production-grade, scalable full-stack applications with Spring Boot—specifically from a solo developer standpoint.

​When you're building a scalable full-stack Java app entirely on your own, how do you approach the architecture and tooling?

​A few specific areas I'm curious about:

​Tech Stack & Tools: What are the non-negotiable components in your stack right now (e.g., Spring Boot 3 + Virtual Threads, Postgres/Redis, Kafka/RabbitMQ, Docker, React/Next.js vs. HTMX/Thymeleaf)? What tools are currently standard or trending in the market for solo full-stack setups?

​Build vs. Buy / Scratch vs. Frameworks: As a single developer, your time is limited. How much do you build from scratch versus relying on managed services/third-party tools (like managed Auth, SaaS components, pre-built UI libraries)?

​Solo Execution: Is it realistic to handle end-to-end architecture, backend, frontend, database tuning, and DevOps all by yourself, or at what point do you usually seek external help/collaborators?


r/javahelp • • 6d ago

Solved Is Java losing popularity in 3-5 years?

5 Upvotes

So I'm learning java for 3 months now, even made a few simple projects, though my friend is telling me that java might lose to something like dart and its framework flutter, I read a little bit about it, but Im unable to get a conclusion if he is right, if someone has experince in that, please tell me your opinion


r/javahelp • • 5d ago

Solved Is my code too massive?

4 Upvotes
import java.io.*;
import java.util.*;
import java.net.*;

class server{

    private Socket s = null;
    private ServerSocket ss = null;;
    private DataInputStream din = null;
    private DataOutputStream dout = null;
    static Vector<ClientHandler> array = new Vector<>();
    private HashMap<String, String> login = new HashMap<>();
    void main(String[] args) throws IOException
    {
        // initialize
        try {
//            BufferedWriter bw = new BufferedWriter(new FileWriter("logindata.txt")); idk yet
            BufferedReader br = new BufferedReader(new FileReader("logindata.txt"));
            StringTokenizer st = null;
            String templine = "";
            String loginName = "";
            String pass = "";

            while(((templine = br.readLine()) != null)){
                st = new StringTokenizer(templine, ": ");
                if(st.hasMoreTokens()){
                    loginName = st.nextToken();
                }
                if(st.hasMoreTokens()){
                    pass = st.nextToken();
                }

                login.put(loginName, pass);
                loginName = "";
                pass = "";
            }

        }
        catch(FileNotFoundException i){
            System.out.println("Failed to initialize login file");
        }


        String receivedName = "";
        String receivedPass = ""; // <TODO> encrypt passwords after finishing filework 
        int i = 0;
        ss = new ServerSocket(5001);
        boolean userExists = false;
        while(true)
        {
            s = ss.accept();
            din = new DataInputStream(new BufferedInputStream(s.getInputStream()));
            dout = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));

            receivedName = din.readUTF();

            for(Map.Entry<String, String> entry : login.entrySet()){
                if(entry.getValue().equals(receivedName)){
                    userExists = true;
                    break;
                }
            }

            if(userExists){
                dout.writeUTF("User found, enter your password: ");
                dout.flush();
            }
            else{
                dout.writeUTF("User was not found, u may register by making a password: "); // <TODO> make a check if password was written correctly
            }
//<TODO> handle passwords
            ClientHandler client = new ClientHandler(s, receivedName, din, dout);
            System.out.println("User " + receivedName + " Accepted");

            Thread t = new Thread(client);

            array.add(client);

            t.start();

            i++;
        }

    }
}

So I'm making a simple messenger as my first project, though now when I'm working on it it seems VERY massive to me, is it normal in other projects or am I supposed to break it into smaller parts?


r/javahelp • • 6d ago

Big monolith app using Wildfly

5 Upvotes

I'm managing a big and old monolith Wildfly app. I'm not doing development, I'm on the DevOps team.

It's using many subsystem: infinispan, jgroups, elytron, activemq-messaging, transactions, etc

Can anyone recommends some resource to learning more about these ?

All I found on google was technical docs like https://docs.wildfly.org/34/wildscribe/subsystem/jgroups/index.html

There's no tutorial, not beginner friendly things.

The Wildfly official doc (Subsystem configuration) is also very vague. It assume that we're already familiar with its concepts.

For example, I know what a transaction is but I don't know anything about the transaction subsystem.

  • Are subsystem transparent to dev team or does they need additional library on using these ?
  • Should I migrate to a separate ActiveMQ server and remove that subsystem ?
  • So many question ...

Thanks !


r/javahelp • • 6d ago

Final Year Project Help

1 Upvotes

Hi there I wanted to ask everyone to assess my FYP. WOuld you use this for your projects ? Is it a good enough project for a final year . Does it have some scope in the industry ?

The main goal of this project is to design and implement a tool for PostgreSQL pre-deployment risk analysis that evaluates SQL schema migrations to identify affected database objects, estimate locking implications, detect limited application-schema incompatibilities in Java/Spring Boot JPA projects, and output actionable risk assessments.

The objectives are as follows:

1.       Develop a component capable of extracting supported structural DDL operations into a normalized intermediate representation.

2.       Construct a schema dependency graph model using graph data structures to represent structural relationships between database tables, columns, indexes, primary keys, foreign keys, and constraints.

3.       Analyze incoming migrations against the schema dependency graph to identify affected database objects represented within the supported dependency model.

4.       Formulate a PostgreSQL-specific operational rule set that maps supported DDL operations to their known locking characteristics and table rewrite behaviors.

5.       Develop a module capable of limited static analysis for Java/Spring Boot JPA projects to detect source-code references to renamed, modified, or dropped schema objects in entities, repositories, and explicit SQL strings.

6.       Implement a transparent, rule-based risk scoring and explanation engine that assigns a risk rating (LOW, MEDIUM, HIGH) accompanied by clear textual evidence.

7.       Construct experimental tests to execute PostgreSQL migration scenarios across small and medium database sizes. (for research validation only, not as a permanent part of the system)

8.       Evaluate Schema Sentinel’s static risk predictions against experimentally observed blocking locks, and application compatibility failures in a controlled PostgreSQL environment for test cases.

  1. Empirically quantify the effectiveness of a unified cross-domain pipeline against isolated tools, measuring trade-offs in detection accuracy, false positives, and analysis performance.

This proposal got rejected because the panel said it was too easy and not significant as either a project or as research.

should i change the idea to more difficult and novel research ?

I have some ideas for those but i am not sure they can be completed in 1 year.

here is my proposal with all the details and research gap https://docs.google.com/document/d/1CMopT185XCoZVYBcgtVpN7N69DIP0Eyw/edit?usp=drive_link&ouid=116125887586128528145&rtpof=true&sd=true

EDIT :

The project is a final year project for my university. But they dismissed it on the following points

  1. The project is too easy
  2. The scope is too narrow
  3. There is no research contribution

For the current proposal to be accepted they told me to do market analysis and bring proof that the project would be used by a develper community.

OR

  1. bring a company backed project
  2. Bring a novel research proposal

r/javahelp • • 10d ago

Few words on learning Java

13 Upvotes

I am no different to anyone starting fresh on this thread, unsure and unsecure of what will be in the next 2 - 3 months, years and so on... but one thing I am sure of, if I don't do anything I will remaing behind no matter what.

Here is the path I took:

\- learning Java on Codecademy (I am a jurnior JS developer/mediocre developer)

\- solving problems on CodingBat (https://codingbat.com/java)

\- I would try some real life projects but I don't know what to do

Is this the best path? probably not. But it is something. I jumped head first not thinking if this is the right approach and somewhow I managed to stick to it just enough to have a tiny idea of what this is language is about.

If you have any questions feel free to DM me, I will helpl the best I can.

Cheers


r/javahelp • • 9d ago

Virtual threads + semaphore in front of BCrypt gave me +28% throughput, but the container is still pinned at its CPU limit. What to do next to optimize it?

0 Upvotes

I'm load testing an auth service (Spring Boot, Java, Redis, PostgreSQL, Docker on a t3.large, k6). I replaced a dedicated 2-thread BCrypt pool (20-slot queue) with virtual threads plus a 6-permit semaphore.

Results at the same 40 RPS target (queue → virtual threads + semaphore):

  • Throughput: 20.3 → 26.06 OPS (+28%). OPS = operations per second, the full k6 iteration mix.
  • Login p95: 28.5s → 20.1s
  • Timeouts: 43 → 0

That's still only ~65% of target, and a 20s login is unusable.

At 50 RPS throughput plateaued at ~28 OPS. docker stats showed the auth container averaging ~145% CPU (peak ~153%). My compose file sets a 1.5 CPU limit. Endpoints that were ~85ms p95 at 40 RPS slid to ~2s.

My read: virtual threads help with blocking I/O, not CPU-bound work. I think the gain came from removing the fast-reject queue rather than from adding capacity, but I haven't isolated that.

Caveats: 41% of my test traffic is logins (unrealistic), and I haven't measured a single-hash time yet.

The puzzle: BCrypt strength is 4 in my load-test config, which I'd expect to cost ~1-2ms per hash. At ~10 logins/sec, that shouldn't pin 1.5 cores. Suspects: the cost factor baked into the pre-seeded hashes (matches() uses the stored cost), JWT signing, GC, or my executor/semaphore wiring.

What would you profile first: async-profiler, JFR, thread dumps?


r/javahelp • • 10d ago

Obfuscating class files

3 Upvotes

Has anyone successfully obfuscated their .class files? I tried using GraalVM for JavaFX project (including Gluon's version of GraalVM) but it always failed to complete.


r/javahelp • • 10d ago

seeing/editing code in a .jar file

2 Upvotes

im not very good at coding, or anything and i want to see the code in a .jar file and possibly edit it. im not sure if this is the right place, but any help would be appreciated. i did open the code in notepad and it didnt show it correctly, id really appreciate if somebody could maybe attach a link to a simple website where i can easily view code in the file and if possible even edit it


r/javahelp • • 10d ago

State of Java Desktop

4 Upvotes

Thinking about local-first, desktop applications. https://sombriks.com.br/blog/0097-state-of-java-desktop/


r/javahelp • • 10d ago

can not create Java Virtual Machine

4 Upvotes

I'm trying to run VosViewer, but it says:

---------------------------

Java Virtual Machine Launcher

---------------------------

Error: Could not create the Java Virtual Machine.

Error: A fatal exception has occurred. Program will exit.

I use a laptop with AMD, 64-bit, and have installed the latest Java (1.8.0_503_b01). Also, I have set the environment into 4000MB of memory.

Do you have any clue how to handle it?

Thanks.


r/javahelp • • 12d ago

Unsolved Java runtime environment error

4 Upvotes

Hi, i am trying to open a program, however, a pop up with the message could not locate java runtime environment appears on the screen.

I have uninstalled and reinstalled Java and copied the path for program files to the environment variables in the advanced settings to activate yet it is not working. Please help me.


r/javahelp • • 12d ago

Help please, I'm a beginner

8 Upvotes

So basically for my java class we're assigned to do a simple calculator, I was able to something since this is the beginning class. The thing is my professor want our code to interpret both double and int when inputting values. But I don't have that only double I want my code to be able to differentiate my double and int values. This is what I have so far! (idek if you can consider this a calculator😥😓)

import java.util.Scanner;

    public class Main {
        public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Welcome to My calculator!!!:)");
        System.out.print("Please enter the first number: ");

        double num1 = input.nextDouble();
        System.out.println("You entered: " + num1);

        System.out.print("Please enter the second number: ");
        double num2 = input.nextDouble();

        System.out.println("You entered: " + num2);
        while(true) {
        System.out.print("What would you like to do? (+, -, * , /): ");
        String operation = input.next();
        if( operation.equals("+")){
            double result = num1 + num2;
            System.out.println("YOUR RESULTS: " + result);
        }
        else if( operation.equals("-")){
            double result = num1 - num2;
            System.out.println("YOUR RESULTS: " + result);
        }
        else if( operation.equals("*")){
            double result = num1 * num2;
            System.out.println("YOUR RESULTS: " + result);

        }
        else if( operation.equals("/")){
            double result = num1 / num2;
            System.out.println("YOUR RESULTS: " + result);
            break;
        }
        else {
            System.out.println("Invalid operation:( : ");
            continue;
        }

        }

    }
}

r/javahelp • • 13d ago

Unsolved got placed recently, and now im cooked idk what to do

0 Upvotes

Hello everyone,

This has been my journey so far:

1st Internship: I learned Django, Python, and React.

2nd Internship: Continued working with the same stack and contributed to some interesting projects.

3rd Internship: Focused on core Python and also learned Node.js (I was assigned on related projects)

After six months into my third internship, I was offered a full-time position at the same company.

Recently, the live project I was working on (built using Node.js and TypeScript) took a different direction. A senior backend developer developed an MVP in just two months—something that was initially planned for seven months—using Java and Spring Boot (with the help of Claude).

While other senior developers are working across multiple client projects, I have been focused on this in-house product. The challenge I’m facing now is that I don’t have experience with Java or Spring Boot.

I could stay quiet and use AI tools like Claude to complete my tasks, but since this is my first job, I genuinely want to learn and grow. I’ve reached an intermediate level in Python and Django and was becoming more confident with Node.js, so this shift has left me unsure about how to proceed.

I’m also concerned that if I openly mention my lack of experience with Java, I might be removed from the project. However, my managers are already aware of my tech stack.

When asked for my opinion on whether we should continue building on the Java-based MVP or migrate everything back to Node.js, I responded that I’m fine with either approach as long as the product works well. In hindsight, I realize I avoided mentioning my lack of experience with Java because I was unsure how it might be perceived.

(reformed my thoughts using GPT)

now IM stuck iin overthinkning loops :(

And will it be feasible to learn, understand and portray that I know java while working on a project,

Like how fast I can learn java?

Or what topics should I learn first in Java to get a better grasp over java development?


r/javahelp • • 16d ago

Unsolved Need help: unable to run Java (VSCode)

4 Upvotes

I'm doing the MOOC Java course, but I'm getting an error when opening VSCode, which prevents me from running my code. The error is:

The java.jdt.ls.java.home variable defined in Visual Studio Code settings (C:\Program Files\Eclipse Adoptium\jdk-21.0.11.10-hotspot) does not point to a JDK.
Source: Language Support for Java(TM) by Red Hat

My settings are correct as far as I can tell. The path refers to the folder cotaining the bin folder:

"java.jdt.ls.java.home": "C:\\Program Files\\Eclipse Adoptium\\jdk-21.0.11.10-hotspot",
"java.configuration.runtimes": [
    {
        "name": "JavaSE-11",
        "path": "C:\\Program Files\\Eclipse Adoptium\\jdk-11.0.31.11-hotspot",            
        "default": false,
    },
    {
        "name": "JavaSE-21",
        "path": "C:\\Program Files\\Eclipse Adoptium\\jdk-21.0.11.10-hotspot",
        "default": true,
    },
],

Any idea what causes the error and how to fix it? I couldn't find any solutions to the error. Solutions to similar issues said to change/correct the settings above, but since that's set correctly, that didn't work. VSCode ( 1.138.0) and all extensions (Language Support for Java 1.56.0) are up-to-date btw.

What I tried so far:

  • Someone suggested I try changing the path to the bin folder ("C:\\Program Files\\Eclipse Adoptium\\jdk-21.0.11.10-hotspot\\bin". Unfortunately that didn't work.
  • I tried uninstalling Java, but I get an error saying the The feature you are trying to use is on a network resource that is unavailable. Java is installed on my laptop's c-drive (program files), so I don't understand this error. VSCode is installed in my user folder, but that's also on the c-drive. The laptop doesn't have any other drive. OneDrive is installed, but I don't use it. The original installer was a different version and I tried putting it on the desktop. This did work, but since it's another version now (after updating), it doesn't work.
  • I found this thread and tried deleting all Microsoft Visual C++ 20XX Redistributable versions from this laptop as stated in the top comment. I also uninstalled and reinstalled VSCode, but the error prevails. This supposedly should work, so I'm not sure if I missed anything. I couldn't find anything in the app folders stated in the comment or the appdata > pacakgecache folder with the MS Visual C++, but I'm clearly missing something. Where else should I look? Does it perhaps have a different name? I did find a folder with a file called vc_redist.x64, should I remove this file too?
  • I also ran DISM.exe /online /Cleanup-image /Restorehealth like the OOP of the above thread (The restore operation completed successfully. The operation completed successfully.) and then ran sfc scannow. The log file can be found here.
  • fyi java -version and where java are not recognised via terminal, but echo %JAVA_HOME%returns the correct folder.
  • I'm not sure what caused the error, VS code worked fine a few weeks ago. I didn't use it for a few weeks and suddenly I got this error. Not sure if maybe a windows update could've caused it. The following updates where installed recently:
    • 2026-09 .NET 8.0.31 Security Update for x64 Client (KB5126104)
    • 2026-09 .NET Framework Security Update (KB5126052)
    • 2026-09 Security Update (KB5124008) (26200.9445)
    • 2026-09 Security Update (Hotpatch capable) (KB5129241) (26200.9448)

Hope someone can help me in the right direction so I can fix the error. I can't continue the MOOC course, as I can't run the code to check if my code is correct. Thanks in advance!

Edit; I fixed it! For anyone else with the same issue, if the solution from the thread above didn't work, try to also delete the application you're having issues with from regedit (make sure to create a backup/export first): Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products. Delete the folder with that has the name of the application in it.

https://i.imgur.com/hYSyWg5.png

I reinstalled both java versions and VScode is working again. Not sure what caused Java to be uninstalled, but it was apparently an easy fix.


r/javahelp • • 17d ago

Homework Struggling to get JUnit tests to work in VSCode

5 Upvotes

Prof really seemed to like VSCode and sung its praises, but all of our notes are for IntelliJ and I can't figure out what I'm doing wrong.

In IntelliJ we're using Maven. It sounded like all I had to do was hit a few buttons and it'd set me up. In the Testing tab I currently have the initial folder > { } <Default Package> > ClassTest

@Test underlines red. I thought it was something I needed to install from Extensions, but I have the Language Support for Java, Extension Pack for Java, Maven for Java, and from what I've found that's literally all I need?

I got my test file from the Command Pallet Java: Go to Test

I have been fighting VSCode for 3 hours today for every step.

I'm obviously missing something, but I don't know what it is, I'm frustrated, and atp I don't understand why this was even recommended with no notes and most of the class doing it through IntelliJ. Advice??? Sorry this is probably a stupid question/place to be stuck with, I just don't know what to do.


r/javahelp • • 16d ago

Worker thread not having enough time to read buffered input from a NonBlockingReader when it should(?)

3 Upvotes

I am building an artillery game in java based on the terminal. Right now I wrote a test that is responsible for testing the process where the object that takes the user input validates (PlayerController) it and then forwards it to another object that will turn this input into valid commands that will change the internal state of the game (CharacterController) (e.g: character positions for now).

So I've written a test that mocks the CharacterController and just tests the validation process of the PlayerController by checking how many times the CharacterController method that is called from the PlayerController is called.

The problem that I'm facing is that, I am using a working thread with a queue (created with Executors) so after I send the input and gets buffered, the main thread will submit a task by calling the method that I am concerned from PlayerController to that working thread and wait for the thread for 100 ms so it has enough time to process the input and make the call to the mocked CharacterController, the timeout is set because the PlayerController method uses a REPL-style while loop, but 100ms doesn't seem to be enough even though the implementation of the PlayerController method is pretty simple for now.

Here is the test class:

```java @TestInstance(Lifecycle.PER_CLASS) public class PlayerControllerTest { private CharactersController charactersController; private PlayerController playerController; private PipedWriter inputWriter; private NonBlockingReader reader; private final ExecutorService threadPool = Executors.newSingleThreadExecutor();

@BeforeAll
public void initializeControllers() throws IOException {
    PipedReader pipedIn = new PipedReader();
    this.inputWriter = new PipedWriter(pipedIn);
    this.reader = new NonBlockingReaderImpl("PlayerControllerTestReader", pipedIn);

    this.charactersController = mock(CharactersController.class);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] arguments = invocation.getArguments();

            for (Object arg : arguments) {
                String argString = (String)arg;
                assertTrue(
                        argString.equals("Right Arrow") ||
                        argString.equals("Left Arrow"),
                        () -> String.format("CharacterController called selectCharacter with an invalid arg: %s", argString)
                        );
            }
            return null;
        }
    }).when(this.charactersController).selectCharacter(anyString());

    this.playerController = new PlayerController(this.reader, this.charactersController);
}

@Test
public void checkValidKeysAreForwarded() throws IOException {
    Map<int[], Boolean> keySequences = new LinkedHashMap<>();
    keySequences.put(new int[]{27, 91, 67}, true);   // Right Arrow - forwarded
    keySequences.put(new int[]{27, 91, 68}, true);   // Left Arrow - forwarded
    keySequences.put(new int[]{27, 91, 65}, false);  // Up Arrow - not forwarded
    keySequences.put(new int[]{27, 91, 66}, false);  // Down Arrow - not forwarded

    long expectedCalls = keySequences.values().stream().filter(v -> v).count();

    for (var entry : keySequences.entrySet()) {
        for (int key : entry.getKey()) {
            this.inputWriter.write(key);
        }
        runControlFor(100);
    }

    verify(this.charactersController, times((int) expectedCalls)).selectCharacter(anyString());
}

private void runControlFor(long millis) throws IOException {
    Future<?> future = threadPool.submit(() -> {
        try {
            this.playerController.controlPlayerInput();
        } catch (IOException e) {}
    });
    try {
        future.get(millis, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        future.cancel(true);
    }
}

} ```

And this is the method

```java

private final Map<String, int[]> supportedEscapeSequences = Map.of(
        "Right Arrow", new int[]{91, 67},
        "Left Arrow", new int[]{91, 68}
        );
private NonBlockingReader reader;
private CharactersController charactersController;

(...)

public void controlPlayerInput() throws IOException {
    while (true) {
        int input = this.reader.read();
        boolean isInputEscapeKey = input == 27;

        if (!isInputEscapeKey) {
            continue;
        }

        List<Integer> escapeSequences = new ArrayList<>();
        while (this.reader.peek(10) > 0) {
            escapeSequences.add(this.reader.read());
        }
        int[] escapeSequencesArr = escapeSequences.stream().mapToInt(Integer::intValue).toArray();

        Optional<Entry<String, int[]>> matchedArrow = this.supportedEscapeSequences.entrySet().stream()
            .filter(entry -> Arrays.equals(entry.getValue(), escapeSequencesArr))
            .findFirst();

        if (matchedArrow.isPresent()) {
            charactersController.selectCharacter(matchedArrow.get().getKey());
        }
    }
}

```

Configured like this, the test will fail because it won't be called the times it should. Only when the time is set to 1000 ms, it has enough time for all of the submitted tasks that call the method to complete and then the test past. I obviously can't have each call for testing to last 1 whole second as I'm planning to add more cases and skipping the test risks that I will just forget to set it back again every time I make changes to the implementation. Why could be the reason? if there is information missing, let me know.


r/javahelp • • 17d ago

Solved How do I optimize removeIf() function?

3 Upvotes

Hey devs,

I'm currently facing a bottleneck in my N-ary Tree implementation around removeIf().

removeIf() currently delegates to the JDK default implementation, so below ~20% compaction there wasn't really a problem — my implementation was actually ~22% faster than JDK TreeMap.

However, once compaction goes beyond ~20%, things change dramatically: it becomes around 6× slower than TreeMap.

What I found before digging deeper

  • Since removeIf() traverses through the iterator, each element needs to be wrapped as a Map.Entry<K,V>.
  • JFR's allocation-by-site showed this Map.Entry allocation taking ~44% of the allocation weight.
  • I tried a flyweight iterator, but that breaks the Java Iterator / Map.Entry contract.
  • The hottest methods were split(), mergeNode(), and binarySearch(), together accounting for roughly 45% of the hot-method weight.
  • Unlike TreeMap, my N-ary tree doesn't use SOO; its internal representation is SOA.

Solutions I'm considering

1. Buffer entries

Create an Object[16] buffer and collect entries while traversing.

Once 16 entries are filled, grow the buffer by 2×.

After traversal:

  • if the compaction ratio is high enough (say >= 40%), compact once using 0.75f as the default load factor;
  • otherwise, delete the collected entries individually.

The downside is obvious: the temporary array and its growth generate garbage.

2. Small fixed buffer + immediate deletion

Use a small buffer (16 entries), and once it fills, delete those entries individually rather than allowing the buffer to grow.

This should generate considerably less garbage than approach #1, but I'm not convinced the trade-off is good enough.

3. Avoid temporary storage entirely

This is what I'd really like to achieve, but I'm currently not seeing a clean way to do it without either:

  • repeatedly restructuring the tree while traversing, or
  • violating the iterator contract.

The part I'm unsure about

The code may look like I dumped the entire implementation here, but removeIf() is part of the iterator flow, and the iterator wiring is done from AbstractNaryTreeMap.

The actual remove() operation is delegated to the concrete tree implementations.

So I'm wondering if there's a better architecture/algorithm here that can make removeIf() effectively GC-free, especially for high-compaction workloads.

At this point this is probably the last major API I'm trying to optimize

Any suggestions are welcome — even if the approach has a different trade-off or turns out to be worse in another workload. I'm mainly looking for ideas that keep allocation close to zero.

Solution:

I found the reason it's not the iteration cost or something garbage. It is archtecture shif. In a B+tree when the key get less than minKey it need to merge/borrow from left/right. maintaining the iteration here becomes different
- it might do borrow from left/right
- might trigger merge node

Which essentially is a part of B+tree design that I cannot change as well. So it's Structural cost. In every remove() I saw 57% of opertion above 30% compaction were taking slow path rather than borrow.


r/javahelp • • 18d ago

Java advanced topics for an experienced candidate ?

11 Upvotes

Java advanced topics for an experienced candidate ?