/r/javahelp
General subreddit for helping with Java code.
General subreddit for helping with Java code.
Message the mods if you have suggestions.
Java Discord server (unofficial)
Learning Java
Please head over to /r/learnjava and read the sidebar there.
The best free Java tutorials are:
Use the MOOC as main course and Java for Complete Beginners as secondary resource.
Don't forget the Official Oracle Java Tutorials and the Official Java Documentation as they are extremely valuable resources.
Where should I download Java?
With the introduction of the new release cadence, many have asked where they should download Java, and if it is still free. To be clear, YES — Java is still free.
If you would like to download Java for free, you can get OpenJDK builds from the following vendors, among others:
Some vendors will be supporting releases for longer than six months. If you have any questions, please do not hesitate to ask them!
Posting rules
DO NOT DELETE your posts once they are solved!
No illegal/pirated content!
No "Do my homework" posts!
Describe the problem and what you want to achieve.
Do not ask for or reply with solutions or keys to solutions.
Use the search function.
No offers/requests to/for help via PM, Discord, Skype, etc.
Post titles must be descriptive.
No promises of rewards of any kind!
Don't be a Jerk!
No JavaScript, Android, Minecraft or Processing!
No links to your stackoverflow questions.
Format your code.
No screenshots of code!
No AI generated content!
/r/javahelp
Don’t know if anyone in here knows but I figured I’d try. So I’m trying to download mods on Minecraft and to do so I need Java installed to open .jar files to be able to install forge but every time I try and go to install forge it pops up with an error saying Java not installed even though it was so I tried jarfix which got rid of that error but it still wouldn’t open forge installer for me to be able to install forge. So I tried 3 different versions of Java and even tried 3 different versions of the forge installer and still nothing. I have no clue what else to try, please I need help!!!!
Some of my projects are stuck in Java 8. I am doing some work with parallel streams, and I ran into something super weird.
I was doing some semi-complex work in a forEach()
call on my parallel stream, and part of that work involved throwing a RuntimeException
if some constraint got violated.
What was COMPLETELY INSANE to me was that sometimes, the ForkJoin framework would eat my exception.
I can't point out my specific examples, but here are some StackOverflow posts that demonstrate this. And to be clear, I am on Java 8b392.
Why does the ForkJoin framework do this? And does it still do it, even on later versions like Java 23?
Is it bad that it took at least 3 years for me to fully grasp what was happening in organisational Java code/ in general ? I wasn’t from programming background at all . Although I do feel proud where I am now , I just want to know :)
In vertx I can validate my openapi as a contract in the router. Is there a way to do this in Helidon SE? The OpenAPIFeature seem only to provide the api spec..
I want to validate if my Redis Spring Cache is set up correctly. Below is the configuration and the function whose results are being cached. After I call the function, I see no new keys created in Redis and in the logs, I see the function being executed every time I call it with the same parameters instead of using the result from the cache. What am I missing and how do I fix this?
This is my CacheConfiguration
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "my-service.redis")
@ConditionalOnProperty(value = "spring.cache.type", havingValue = "redis")
public class MyServiceCacheConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(MyServiceCacheConfiguration.class);
private String hostname;
private int port;
private String username;
private String password;
private int connectionPoolSize;
private int retryAttempts;
private int minimumIdleConnections;
private int connectionTimeout;
private int idleTimeout;
protected static final Map<String, Object> CACHE_CONFIG = new HashMap<>();
@PostConstruct
public void setupCacheConfig() {
LOG.info("Getting redis config");
CACHE_CONFIG.put(HOST, hostname);
CACHE_CONFIG.put(PORT, port);
CACHE_CONFIG.put(USERNAME, username);
CACHE_CONFIG.put(PASSWORD, password);
CACHE_CONFIG.put(CONNECTION_POOL_SIZE, connectionPoolSize);
CACHE_CONFIG.put(RETRY_ATTEMPTS, retryAttempts);
CACHE_CONFIG.put(MINIMUM_IDLE_CONNECTIONS, minimumIdleConnections);
CACHE_CONFIG.put(CONNECTION_TIMEOUT, connectionTimeout);
CACHE_CONFIG.put(IDLE_TIMEOUT, idleTimeout);
}
@Bean("redissonCacheClient")
RedissonClient initRedissonClient() {
try {
Config config = new Config();
config.setCodec(JsonJacksonCodec.INSTANCE);
SingleServerConfig singleServerConfig = config.useSingleServer();
singleServerConfig.setAddress(getAddress())
.setUsername((String) CACHE_CONFIG.get(USERNAME))
.setConnectionPoolSize((Integer) CACHE_CONFIG.get(CONNECTION_POOL_SIZE))
.setRetryAttempts((Integer) CACHE_CONFIG.get(RETRY_ATTEMPTS))
.setConnectionMinimumIdleSize((Integer) CACHE_CONFIG.get(MINIMUM_IDLE_CONNECTIONS))
.setConnectTimeout((Integer) CACHE_CONFIG.get(CONNECTION_TIMEOUT))
.setIdleConnectionTimeout((Integer) CACHE_CONFIG.get(IDLE_TIMEOUT));
LOG.info("Creating RedissonClient client");
if (CACHE_CONFIG.get(PASSWORD) != null && !((String) CACHE_CONFIG.get(PASSWORD)).isEmpty()){
singleServerConfig.setPassword((String) CACHE_CONFIG.get(PASSWORD));
}
return Redisson.create(config);
} catch (Exception e) {
LOG.error("Exception while creating initRedissonClient client", e);
}
return null;
}
@Bean
CacheManager cacheManager(
@Qualifier("redissonCacheClient")
RedissonClient redissonClient
) {
LOG.info("Creating cache manager");
Map<String, CacheConfig> config = new HashMap<>();
return new RedissonSpringCacheManager(redissonClient, config);
}
private static String getAddress() {
return String.format("%s%s%s%s", "redis://", CACHE_CONFIG.get(HOST), ":", CACHE_CONFIG.get(PORT));
}
}
This is the function whose result I'm caching
@Cacheable(key = "#application.concat('::').concat(#label).concat('::').concat(#locale)")
public Keyword findKeyword(String application, String label, LocaleEnum locale){
Optional<Keyword> optionalKeyword = keywordRepository.findByApplicationAndLabelAndLocale(application, label, locale);
return optionalKeyword.orElse(null);
}
I am starting a new job working at a bank, and they use Java/Maven/Springboot for everything.
I am knee-deep in research and beginner courses on youtube/MOOC.fi.
I just want to know if I put my all into learning everything I can, should I be able to guarantee myself a full (35 years) career using these technologies?
I have only ever worked with C, Python, PHP, JS, Typescript, React and React Native so far in a professional setting.
I am willing to put in the work and go deep into learning everything I can, but at this point I don't know if I have the willingness to keep doing these deep-dives in so many different technologies.
Can Java be the last stop for my learning journey? I am tired of feeling like a jack of all trades, master of none.
I'm working on a Swing project using MVC and Maven, but I'm stuck. I’ve created three modules (four including the main one), and in the main module (pom.xml
), I’ve already defined model
, view
, and controller
.
I understand the MVC flow—client sends a request to the controller, which calls the model, the model interacts with the DB, and the response goes back through the controller to the view.
However, I’m struggling with actually linking the modules in practice. How do I properly connect them in a Maven-based project? Any guidance would be appreciated!
Hello! I've been studying Java for a semester now in school (Learned the basics for 2 months and object oriented programming for 2 months). I have a 3 week break and was looking for a 1-2 week intensive bootcamp to get better during these vacations. However all of the courses are super basic and teach stuff like how to print messages and how to create arrays. I'm looking for a way (doesn't have to be a course, but if it is, should be a bit more advanced) to get better during these two weeks. Thanks for your tips/help!
I do not understand what I am doing wrong here. I am new to Java. Can anyone explain to me what I am doing wrong? I am using NetBeans if that matters.
package mypointlab;
import java.util.Scanner;
public class MyPointLab {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(
"Please enter the x coordinate for your point: ");
double x = input.nextDouble();
System.out.print(
"Please enter the y coordinate for your point: ");
double y = input.nextDouble();
/* Create two points and find distance */
System.out.print("The distance between " + getX + " and " +
getYy + " is " + getDistance);
System.out.print("The distance between " + getX + " and " +
getY + " is " + getDistance);
}
}
class MyPoint{
private double x;
private double y;
//No Arg
public MyPoint(){
this.x = 0;
this.y = 0;
}
// Normal Constructor
public MyPoint(double x, double y){
this.x = x;
this.y = y;
}
// getters
private double getX(){
return this.x;
}
private double getY(){
return this.y;
}
//Distance between points
private double distance(double x, double y){
return Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
}
//Distance using getters
public double getDistance(){
return distance;
}
}
I am attempting to set up java in VScode but whenever I attempt to run my code, I ge tthis error:
Error: Could not find or load main class PrimeFactors
Caused by: java.lang.ClassNotFoundException: PrimeFactors
I thought that it was due to my file having a different name but that does not seem to be the case. Any ideas?
What are other easy ways to implement multithreading in Java? I have gone through this video, but it makes me feel unsure that are these the only ways to implement multithreading.
I'm trying to help out with a java app on Github. Most of the developers don't have Macs so the current implementation on a Mac requires running a script from the command line. Not very user friendly.
I'm not a Java developer, but I was able to get jpackage to work great and I have an app that runs great (after giving it permissions since it is unsigned). The problem is that I can not get it to log anywhere. The app is using slf4j.Logger. I've edited the logback.xml file so I can use a separate file to specify where the log should be. When launching from the script on the command line (essentially just executing the .jar) it works fine. I can log alongside the .jar, or in my Library/Application Support/... Once it's all packaged into an app bundle there's nothing. I've given the app Full Disk Access and it still doesn't work. What is needed for it to be able to write to a log?
I did find that if I run it from the command line inside the bundle (./MyApp.app/Contents/MacOS/MyApp) the log is created. If I just double-click the app, it's not.
Been reading about reflection and testing out code. Mainly from link 1, link 2 (results of link 2 seem outdated). Using the following CODE I made, I notice the performance of LambdaMetaFactory (LMF) is quite fast comparable to a direct call. Here are the results (rudimentary, no JMH)...
Direct call: 0d 0h 0m 0s 46ms
Method handle: 0d 0h 0m 0s 80ms
LambdaMetaFactory: 0d 0h 0m 0s 51ms
Record inline: 0d 0h 0m 0s 881ms
Is it possible to avoid the Functional Interface in the LMF, to be able to instantiate arbitrary records through reflection, through discoverability of types of constructor. LMF, it seems one can't avoid the strict types required in the parameters of the first methodType of the metaFactory. If not, is there a way to do it and which is fast as a direct call while avoid final static (for inlining). Just out of curiosity.
I'm using jdk 23.
Long story short, I have multiple threads writing to the same file, and all of those threads are calling the following method.
private static void writeThenClearList(final String key, final List<String> list)
{
if (list.isEmpty())
{
return;
}
try {
Files
.write(
parentFolder.resolve(key),
list,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.SYNC
);
} catch (final Exception e) {
throw new RuntimeException(e);
}
list.clear();
}
However, when I use the above method, I end up with output that is clearly multiple threads output jumbled together. Here is a runnable example that I put together.
Am I misunderstanding the documentation? Here is that too.
It seems clear and simple to me.
Now, this problem is easy enough for me to solve. I can probably just go into the java.util.concurrent
package and find some variant of a lock that will solve my problem.
I just want to make sure that I am not missing something here.
I need to fill a binary tree with the left part containing only even numbers, and the right part odd numbers.
Both should also follow the normal binary tree structure by adding the smaller one left and the larger ones to the right.
I tried a few things but then gave up. Asked some LLMs, they start hallucinating...
Now I thought about adding a method which counts the number of nodes of the tree, and use it to assist/modify the insert method.
For every insert I check if the tree has less than 3 nodes, if that's the case, I fill the three following odd and even.
If the tree has 3 or more nodes and the number to insert is even, I set root.getLeft() as the new root, and fill normally from that point on, and do the same for odd numbers starting from the right child of the root.
Would this even work? Or is there a better way to do it?
Want guidance
Hi, does anyone know how to properly setup a redirect uri for oauth2 with google and github?
When i try to login with both, i get to the screen where they (google and github) ask for username and password. then both of them error out, github with a 404 not found page, google with a 400 redirect_uri_missmatch.
I want to be able to redirect to the main page of my website (aka. "localhost:8080/")
[What the title says]. Essentially, I kept getting notifications about Java being outdated, or needing an update, and decided that it would be easier to simply uninstall and reinstall.
The problem is, I'm not very good with computers. I went to my Apps and Features and uninstalled anything with the word Java. Trying to reinstall resulted in a message reading, "There are some files or directories left behind from a previous installation. Please remove them and rerun the installer."
I would really appreciate any help.
( Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz
Windows 10 Pro
22H2 )
Hey myself a student in 4th year and currently starting my Springboot after core Java. His content is Engaging but when I see Anujbhaiya, genie ashweine, Tulsko and their courses of line up then, I get doubt that is I am studying right or his content really worth to get me a job and clear my interview. So anybody who studied from him can tell about about his course Or any other suggestions for Springboot Java and my journey. Please share
Hi
I wanted to ask for an advice with my problem. I'm running self-hosted github action runner which runs all the tests.
There are plenty integration tests using kafka, some redis with testcontainers. The issue i'm experiencing is `Exception: java.lang.OutOfMemoryError` in the middle of the tests (on local machine all works fine). I'm trying to debug/figure out how to fix it.
Some background.
Self hosted runner is on k8s. Pod itself has 10g ram available, process is not killed by k8s, thus i assume it is enough. When running `kubectl top pod` i noticed, that github runner reach maximum 7000m than `Exception: java.lang.OutOfMemoryError` error occur. What could be the reason? Tests are run by gradle - changing org.gradle.jvmargs had no effect, Xmx4g or Xmx6g all resulted in OOM error when pod hit 7000m.
Read testcontainers docs, but no much help, it theory it should consume all the memory available.
Is there anything which is preventing to allocate more than 7000m for tests?
Hello , so I've been learning core java stuff for the past months, but I'm now looking forward to build something resume-worthy for an internship.
The only thing is I am not sure what to build considering I want to be forced to use core java concepts and all that stuff.
This is because I think I struggle how and when to implement things without being given instructions, e.g. I'm given an assignment to implement such , and I'm instructed to make a class, then implement a interface, or use arraylists, for example.
Hey guyz
So I am trying for a career switch. I am currently working as a QA in Oracle for the last two years. I am mostly not doing anything essential, just testing their pre written tools, analyzing their results and getting information from one team to another. The work is soul crushing
I am good in C++ and would like to learn and switch to a proper JAVA backend roles. From LinkedIN, I made a post of the skills mostly required for this job.
Now I want to build some good projects which integrates the above things but I do not know how to start or what to do so please help me a guy out :)
Eg see we have one project name called 'jdbc_employeedb'
Inside this project we have two packages named as 1)'com.jsp.jdbc.employeedb' 2)'com.jsp.jdbc.employeedb.dao'
In first package we have our App.java In second package we have our logic emoloyeedao.java
Inside employeedao.java I have to implement the DDL query by using method name called add employee(with some parameters like whatever we have given in database column names)
Then we have insert the data by using any of these methods those are like excute() return type is ResultSet excute update() return type is int.
How can we insert using method? If anyone didn't get this question let me know I'll share the source code!!!!
Hi
I am a newbie in java and doing this assignment where I need Mail Users objects which I can create/store/remove as well. The assignment asks for a Sorted Set so there are no duplicates. I want to create an attribute of ID for every user which increments automatically as I add objects in it? Bu I can't really figure out this part, can anyone please help with this?
I don't want to use chatgpt for quick fixes.
Hello all. Bit of context - I'm a Java dev working with code that involves a fair bit of computational geometry in Java. Obviously the lack of direct memory control makes things a bit more interesting, but one particular problem I'm trying to solve is that of massively duplicated geometry objects.
The problem - We currently have two main record type classes Point3d
and Vector3d
. Obviously both of these classes are immutable. This unfortunately also means that for any and every basic geometry operation involving these objects, a new object is created (no in-place mutations allowed)....and we're doing a LOT of geometric operations, and it's adding a fair bit of GC and memory pressure (on one of our runs, the code generated over a billion vectors as part of transformations - these are unfortunately unavoidable. I've already look through the logic so optimising things there is a bit of a no go).
Now many of these operations end up essentially creating the same point and vector objects so deduplication would go a long way towards reducing the object count.
One approach I thought of to alleviate this (without affecting immutability) was to create a simple threadsafe cache. Testing indicates that this does reduce object creation a fair bit, but I'm wondering if there are other better/more efficient approaches for this ?
Like I am confusing between method overriding and method hiding.
Where I can hear whispers of the past?
Recently I land a position as Java EE 6 developer, with an Oracle Fusion Middleware 12c. It’s my first experience with this programming model (Oracle’s definition), and I need to learn EJB, Servlets, Portlets, JSP, JQuery, etc… My previous experience was with Node and most up-to-date frameworks.
It’s a very interesting time travel, where I found some foundational patterns for other languages and frameworks. (As an example: It’s easy to compare annotation and layer names from the Java EE Realm with NestJS).
I would like to ask about blogs and resources to learn what architects do with applications of this time. Some questions that I have in mind:
I find Oracle docs very good and think the EE have a corporate price because that. Big companies consider to use Jakarta EE 10 (2022) latest edition or stop at Java EE 8 (2017)?
In Java World, everybody consider to migrate to Spring or Quarkus?
What happens with applications servers like Weblogic (most recent version of 2024)?
If the corporate business ask to update applications due to lack of support, what to do?
There’s viability to update monoliths with servlets and portlets? Let’s say, add jax-ws or jax-rs to separate backend and frontend? Let’s say use an angular app to consume and provide data.
EE 6 are update friend to EE 7, EE 8? Also Java version from 1.8?
Commonly I hear that “everything must be migrate to node”, but I see some beauty in this EE standard.
Thank you in advance
Design mode: https://i.imgur.com/BXfKsVF.png
Runtime: https://i.imgur.com/Ka5Uf7r.png
As you can see, I have two unicode characters which are flags which display accurately in design mode but not at runtime. I'm using IntelliJ IDEA CE 2024.3.2.1.
Any ideas?
even though interfaces have default methods then how can they support multiple inheritance?
is the explanation in this video correct? i don;t feel fully satisfied
https://www.youtube.com/watch?v=r-aMsEwn35E&ab_channel=SumoCode
Hi, I am passout of 2023 class with Electrical Engineering degree. I wanted to make a career in the tech. And started to learn Java, Spring Boot from 2024, after I didn't get qualified in gate ee. I am looking for opportunities and its been over a year. And still no one gives a positive reply for my 100s jobs applications every month.
Ps I can build java full stack applications using Spring Boot and React. I can dm my portfolio if you are interested in hiring or know someone.