/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
Is it all about the hashCode()
implementation, or does something else come into play?
I recently found out about being able to summon (minecraft) entities and overriding methods which would be useful with what I wanna do. Although I have 0 idea of how to create a class based on what the already-defined entity's class is. What I want to do (with "entity" variable):
Example (and the.. thing I want to do):
Entity zombie = new Zombie(EntityType.ZOMBIE, _level)
Entity zombie = new entity.getType().getBaseClass().class(EntityType.ZOMBIE, _level)
Don't have my pc right now but I was doing some testing(new at it by the way) and part of the tasks is checking that the code logs are present and making a makeshift external service that offers a Double(both of these are in their own packages and classes) I used logging.Logger for the logs and now I'm just trying to figure out how to do those tests as for mocking the external service it refuses .....I'll put the error later on when I see it
Hello everyone.. i want to ask is it possible to add a python script like this?
I have a functional spring boot + react app for users and they already using it. But they have a new change request to add a button to download the file as an excel with templates and data was fetch from the db. My friend help me by building a python script to generate this file (since we think python is good for working with data)
Is it possible to add a button in my react front end to run the python script and download the data as excel?
I’m trying to download Java for Minecraft mods and there is no “open with” option. It only gives me the option to open, and that’s it. I downloaded the default Java, then the x64 installer, and then the jarfix. I even restarted and undownloaded a bunch of time: and still nothing. What should I do?
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
Hey guys, I'm wondering how to incorporate the macOS Window menu bar features on a Swing application as depicted in the screenshot above.
Even just a link to a project on GitHub which does this would suffice.
Thanks so much!
Hi, I am in an introductory course for java programming, I am an anthropology major so this is not my strong suit. I am working on my final project where I am creating a calculator that converts a number of kilometers into miles. All of the code I have written seems to be in order and no errors come up yet whenever I run the code it prompts you to type a number of kilometers twice, only then will it convert it and run through the rest of the code. The end of the program prompts the user if they would like to go again, but when you do, no matter the number you type in to be converted it will convert the first number again.
Here is the paste bin of the code I have written:
For the record, I am very new to Java, and am working on a project for university, and I am tearing my hair out trying to figure out why this isn't working as currently implemented. I am trying to create a PriorityQueue for a best first search algorithm in Java, where instances of the Node class are given integer values by instances of the interface NodeFunction. I have created a comparator which, given an instance of NodeFunction, can compare two instances of Node, and as far as I can tell it should now be working, however I am getting the following error
Exception in thread "main" java.lang.ClassCastException: class search.Node cannot be cast to class java.lang.Comparable (search.Node is in unnamed module of loader com.sun.tools.javac.launcher.MemoryClassLoader u/36060e; java.lang.Comparable is in module java.base of loader 'bootstrap')
The relevant parts of the code are below:
public class BFF{
PriorityQueue<Node> queue;
NodeFunction function;
public BFF(NodeFunction f){
function = f;
queue = new PriorityQueue<>(new NodeComparator(function));
}
public void addNode(Node node){
queue.add(node); // This is where the error is coming from
}
public class NodeComparator implements Comparator<Node>{
NodeFunction function;
public NodeComparator(NodeFunction function){
this.function = function;
}
@Override
public int compare(Node n1, Node n2){
return Integer.compare(function.value(n1), function.value(n2));
}
}
public interface NodeFunction {
int value(Node node);
}
I don't believe the problem lies in the implementation of Node, nor the specific implementation of the interface NodeFunction, so I will omit these for brevity, but I could provide them if they would be of assistance. Like I said, as far as I can tell looking online the PriorityQueue should be able to compare instances of Node now the comparator is provided, but for some reason can not. Any help in figuring out why would be appreciated.
Let's say that I have application A, which depends on libraries B and C. These are all written by me, and all in separate source code repositories.
Is there some tool that, when I clone application A, can be run to automatically clone the source code for libraries B and C?
I want to clone the source code - not download compiled jars - so I don't think Maven is the right solution.
I'm using IntelliJ; ideally this would be an easy operation to do from within the IDE.
Some button & slider aren’t responding to mouse clicks normally now they only work occasionally the code seems right idk what’s wrong anyone had the same problem before?
So I'm trying to make a minecraft mod for the first time and it said I needed JDK. So after a while of figuring out how to extract it (Winrar helped me) there is no EXE file anywhere. It was extracted in the same place. Do I have to put the files in another Java Program? Is there something I am missing? I am a total beginner so any help is appriciated, thank you.
I found myself updating some old codebase (Java 7) which had the following line of code:
var path = getClass().getClassLoader().getResource(".");
It used to work well and returned the resource folder. Be it on the file system, in a jar or anywhere, actually.
Now with Java 21 it returns null
.
Why is it so, and what is the updated way of having this work?
Edit:
The exact code I run is the following:
public class Main {
public static void main(String[] args) {
System.out.println(Main.class.getClassLoader().getResource("."));
}
}
I have the following function which I need to test -
private HashMap<String, Dataset<Row>> getDataSources(SparkSession spark) {
HashMap<String, Dataset<Row>> ds = new HashMap<String, Dataset<Row>>();
Dataset<Row>dimTenant = spark.table(dbName + "." + SparkConstants.DIM_TENANT)
.select("tenant_key", "tenant_id");
Map<String, String> options = new HashMap<>();
mockOptions.put("table", bookValueTable);
mockOptions.put("zkUrl", zkUrl);
Dataset<Row> bookValue = spark.read().format("org.apache.phoenix.spark")
.options(options)
.load();
ds.put("dimTenant", dimTenant);
ds.put("bookValue", bookValue);
return ds;
}
In this case, I actually need to execute spark.table
but need to mock the output of spark.read().format(formatParam).options(optionsParam).load()
based on formatParam
and optionsParam
Note that spark.table
internally calls spark.read().table
How can I achieve this?
hey, I keep trying to install JRE 64-bit, but always getting error 1603. There is no problem with permissions. I tried on different folder, even on different disk - same error. I can install with online installer no problem, but that's 32 bit version. I tried older versions - same stuff. I'm running windows 11.
Can someone please help me? Been stuck for hours
im dowing a 2d game, i created a bomb but i dont know how to make it unregister actors of the cells next to her
thx
I am building a website using Microsoft Powerpages and I want to post data to our SQL database using an Azure function. The function receives the multipart/form-data from the frontend, but I am unable to read the values into my function. I want my Azure function to do something like this:
1 package com.itstyringsmartsales;
2 import java.util.*;
3 import com.microsoft.azure.functions.annotation.*;
4 import com.microsoft.azure.functions.*;
5
6 import java.io.ByteArrayInputStream;
7 import java.io.IOException;
8 // import <package.Class>
9 import java.io.InputStream;
10 import java.sql.Date;
11 import java.util.Map;
12
13 import javax.faces.annotation.RequestParameterMap;
14
15 import java.util.HashMap;
16
17 /*
18 * TODOS:
19 * - Add connection string
20 * - Parse multipart/formdata
21 * -
22 */
23
24 /**
25 * Azure Functions with HTTP Trigger.
26 */
27
28 // This function receives form data from the client and triggers a storedprocedure with a connection string.
29 // - receives form data
30 // - the form data is parsed by the function
31 // - the stored procedure is triggered with the parsed form data as parameters
32 public class Sales implements org.apache.commons.fileupload.UploadContext {
33 /**
34 * This function listens at endpoint "/api/Sales". Two ways to invoke it using "curl" command in bash:
35 * 1. curl -d "HTTP Body" {your host}/api/Sales
36 * 2. curl {your host}/api/Sales?name=HTTP%20Query
37 **/
38
39 @FunctionName("Sales")
40 public HttpResponseMessage run(
41 @HttpTrigger(
42 name = "req",
43 methods = {HttpMethod.POST},
44 authLevel = AuthorizationLevel.ANONYMOUS)
45 HttpRequestMessage<Optional<String>> request,
46 @RequestParameterMap
47 final ExecutionContext context) {
48 context.getLogger().info("Java HTTP trigger processed a request.");
49
50 // - [x] get request body
51 String requestBody = request.getBody().orElse("");
52
53 String product_name = "Football";
54 int production_cost = "";
55 float price = "";
56 int units_sold = "";
57 float profit = "";
58 String date = "";
59 int month_number = "";
60 int year = "";
61 float indirect_costs = "";
62
63 // parse the request body
64 try {
65
66
67 // - [ ] trigger stored procedure with parsed data as parameters
68 Connection connection = new SQLConnection("<connection-string>");
69 connection.triggerSproc.addSale(product_name, production_cost, price, 70units_sold, profit, date, month_number, year, indirect_costs);
71 } catch (Exception e) {
72 context.getLogger().severe("Failed to parse form data: " + e.getMessage());
73 return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
74 .body("Invalid form data")
75 .build();
76 }
77 return request.createResponseBuilder(HttpStatus.OK).body(requestBody).build();
78 }
79 }
My question boils down to the lines 53 to 61. How do I store each field in the form inside their own variable?
Once that is done I can easily use JDBC to trigger a stored procedure in SQL Server. Is there a term for what my question is about? The closest thing I can think of is parsing.
Ive been trying to understand it for a week now and have gotten nowhere. I feel like if i can just find a good simple example i can understand it.
Hi all, so I've been doing some benchmarking at work to suss out how good (or bad) things are at various places. One of the instances I benchmarked recently was an instance where someone had coded up two nested parallelStreams. Something like so:
inputStream.parallel().forEach(
streamElement -> someList.stream().parallel()
.forEach(
innerEle -> {
// some work here using streamElement and innerEle
}).toList();
)
My immediate thought was that since all parallelStreams draw from ForkJoinPool.commonPool() they'd end up fighting for resources and potentially make the whole thing slower.
But my next thought was...how much slower ?
So I went ahead and made a benchmark with JMH where I tested 3 conditions:
The results are ... interesting. Here's my benchmarking code:
public class ParallelPerf {
u/State(Scope.Benchmark)
public static class StateData{
public static final List<Integer> outerLoop = IntStream.range(0, 32).boxed().toList();
public static final List<Integer> innerLoop = IntStream.range(0, 32).boxed().toList();
}
private static void runInNewPool(Runnable task) {
ForkJoinPool pool = new ForkJoinPool();
try {
pool.submit(task).join();
} finally {
pool.shutdown();
}
}
private static void innerParallelLoop() {
StateData.innerLoop.parallelStream().unordered().forEach(i -> {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
private static void innerSequentialLoop() {
StateData.innerLoop.stream().unordered().forEach(i -> {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
@Benchmark
public void testingNewPool(Blackhole bh){
StateData.outerLoop.parallelStream().unordered().forEach(i -> {
runInNewPool(ParallelPerf::innerParallelLoop);
bh.consume(i);
});
}
@Benchmark
public void testingCommonPoolWithSequentialInner(Blackhole bh){
StateData.outerLoop.parallelStream().unordered().forEach(i -> {
innerSequentialLoop();
bh.consume(i);
});
}
@Benchmark
public void testingCommonPool(Blackhole bh){
StateData.outerLoop.parallelStream().unordered().forEach(i -> {
innerParallelLoop();
bh.consume(i);
});
}
}
And here are the results on my system:
Benchmark Mode Cnt Score Error Units
ParallelPerf.testingCommonPool thrpt 25 1.992 ± 0.018 ops/s
ParallelPerf.testingCommonPoolWithSequentialInner thrpt 25 1.802 ± 0.015 ops/s
ParallelPerf.testingNewPool thrpt 25 23.136 ± 1.738 ops/s
Assuming my benching code is correct and I haven't screwed anything up, I'm quite surprised that the code with new pools is around 20x faster than the others. Why is it so much faster ?
One potential reason I could think of (caveat - I haven't verified this at all) is that maybe the new pool is able to grab one of the waiting threads from the common pool ? But this would indicate that the threads within commonPool are unable to do so, which doesn't seem right.
So fellow redditors - any guesses/insights as to what might be happening here ?
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
Hi,
I have a requirement where I have two beans, namely Form and DTO, both having the same properties for which I have to map property values from Form -> DTO in JDK 21.
Example bean POJO:
Form{mask: Boolean, height: Integer, active: Boolean, name: String, history: List<String>}
DTO{id: UUID, height: Integer, active: Boolean, name: String, history: List<String>}
Now, I receive a collection of property names as Set<String> belonging to Form type bean that I have to consider while mapping the values of the properties specified in the received set from Form to DTO. This collection of property names specifies the properties in the instance of Form type in context that has its values changes as compared to its counterpart on the DTO side.
Since, the collection of property names is dynamic in nature, how do I perform a dynamic mapping from Form -> DTO using the provided collection of property names?
I have tried different mapping frameworks like JMapper and Dozer but they are all last supported till 2016 and 2014 respectively and does not offer concrete examples or strong documentation to my liking. MapStruct does not seem to offer any API way of doing it.
My last resort is to implement my own mapping framework using reflections but I really don't want to go down that rabbit hole. Any suggestions on how I can achieve this with a readymade mapping library?
TLDR: How can I dynamically map a set of properties from bean A to B where the property names to be considered for mapping are only available at runtime and a full mapping from A to B should never be considered unless specified?
Firstly, I am autistic. I've tried to learn java from more “traditional” languages (C# & Python), but I just can't understand java and OOP in general. I just want to learn enough to make Minecraft mods (Minecraft subs told me to post here instead), so does anyone have anything that could help me understand java? My main problems are with general OOP and Javas buses.
I've looked up so many tutorials trying to get this but none seem to work. What's the most straightforward way to activate a method when a certain button is pressed? Where can I read about the specifics of your answer? All the tutorials I've found are too surface level for me to know how to adapt them to my project. I'm using javafx if that makes a difference.
Let's assume we have class B
, contents of which is irrelevant to the following discussion. I want this class with one additional field. Solutions? Well, there are two I've found.
Derived class.
public class D extends B { public int tag = 0; }
Cool, but if I want to use this class as the replacement of B
, I have to duplicate all constructors of B
:
public class D extends B {
public int tag = 0;
public D () { super B (); }
public D (int x) { super (x); }
public D (String x) { super (x); }
public D (int x, int y, String z) { super (x, y, z); }
// TODO: all others
}
B x = new D (...);
Java has anonimous classes. They do inherit base class constructors!
B x = new B (...) { public int tag = 0; };
Wait how am I supposed to get value of this field?..
So I've started to ask myself the following question: why constructor inheritence is limited to anonymous classes?
Hello all I am still learning a for a final project I have to make Pac-Man move by inputting 1 - forward, 2 - left, 3 - right and 4 - stop and any other number won’t work. Can anyone give me any pointers by using while or if statements or something. Thnaks
So I am thinking of learning java and get serious about my career I know programming as companies ask for DSA so I was thinking of doing it in java but problem is i am not aware of development scenario in JAVA like JAVA have springboot but i don't think it is demand same for app development people are using kotlin so wanted to ask is it worth learning or i am not informed yet ?
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
Whenever I open up visual studio and go to java I get an error saying “Cannot find 1.8 or higher” I have 0 clue what this means other than its not detecting the jdk
The other problem is my coding pack from the same website isn’t finishing installation either so im looking for any advice if possible.
I am wondering if this code can be further optimized to reduce runtime?
It is supposed to find all of the combinations possible for a given string.
So for the string "ABC": A, AB, ABC, AC, ACB, B, BA, BAC, BC, BCA, C, CA, CAB, CB, CBA
protected void getCombos(String str, String sub) {
int stringLen = str.length();
System.out.println(sub);
if (stringLen > 0) {
for (int i = 0; i < stringLen; i++) {
getCombos(str.substring(0, i) + str.substring(i + 1, stringLen), sub + str.charAt(i));
}
}
}
The title, basically.
Thanks!