/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
im trying to run a jar file that i compiled from https://github.com/Runsafe/Framework/tree/develop , When i attempt to run with java -jar framework.jar i get the error "no manifest attribute, in Framework.jar" what do i do? im new to java so help is appreciated
Hi everyone, I'm new to spring boot and currently learning spring security. Do you have any youtube channel or website to suggest? I'm tired of watching tutorial with the tutor just writing his/her pre-written code. I still couldn't find a channel that really teach how each component works in spring security.
I couldnt also find a session-based authentication tutorial, most of the tutorials are implementing JWT.
I have gone through many blogs about my question, but I need a quick clarification on the usage of createTempFile. Does this really create a file and stores it in some location permanently or does this delete the file when the execution of the program or batch that’s completed and what is the location of the file created using this is this tmp directory? Please redirect me to the correct place of this isn’t the place to ask this question. Thanks in advance
Hi! I'm making a resource to help explore different software ecosystems called Echo, and I made a directory for Java: https://ecosystems.gitwallet.co/ecosystems/java/
You can think of this as a different take on Github Explore (although we're getting repos from Gitlab as well), but also featuring some of the people in the community too. I think we need better tools for exploring open source in this way, and we're experimenting with it.
We also made a different take on the Github repo page to make it a bit more readable, see related repos, and a few more things. Here's an example for GraalVM, which compiles Java into native executables:
https://ecosystems.gitwallet.co/ecosystems/java/projects/graal
Anyways would love some feedback from other folks from the Java ecosystem! I learned Java early in my career (J2SE/J2ME days!!) but haven't quite kept up with the ecosystem to be frank, so hoping that folks here might be able to smoketest this - let me know if / how it's useful to you!
Thanks so much!!
public class WrapTest
{
public static void main(String [] args)
{
int result = 0;
short s = 42;
Long x = new Long("42");
Long y = new Long(42);
Short z = new Short("42");
Short x2 = new Short(s);
Integer y2 = new Integer("42");
Integer z2 = new Integer(42);
if (x == y) /* Line 13 */
result = 1;
if (x.equals(y) ) /* Line 15 */
result = result + 10;
if (x.equals(z) ) /* Line 17 */
result = result + 100;
if (x.equals(x2) ) /* Line 19 */
result = result + 1000;
if (x.equals(z2) ) /* Line 21 */
result = result + 10000;
System.out.println("result = " + result);
}
}
what will be result of the result here ?? I understand regarding the pooling but that way shouldn't x==y be true... the answer given in 10 but i calculated it to be 11... please help... I just started learning....
Also it would be highly helpful if there is any suggestion regarding resources that will me learn these little extraordinary things..
Hey,
I want to get started with the Spring framework. Could y'all post some good resources you've learned from? I would prefer free resources though, as I'm a student.
public static int smallest(int number1, int number2) {
if (number1 < number2) {
return number1;
} else {
return number2;
}
}
What is the point in using else? If the conditions of the if statement aren't met, the code outside of the if statement will run anyway. Is it just simply more understandable or are there other benefits to doing so?
hello
recently I was looking for how to run Java if the computer doesn't have it, I found jpackage for Java 17, I used the command
jpackage --type app-image --app-version 1.0.0.0 --name test --dest .\Game --input . --main-class org/example/Main.java --main-jar PackerTest.jar --runtime-image "C:\Program Files\Java\jdk-17"
and everything was fine until there were 257 different folders in the app folder, each with the same name app->Game, why did this happen?
Can anyone recommend a good java Tutorial i can follow to learn from and recommend to others please just put it into the comments
I’m looking into changing my role into a senior Java developer and I’m constantly running into intro interviews that demand 5+ years of java and spring experience as a hard must, which blocks me from going to technical phase od the interview.
How does someone transition into another language with a carear switch from Node.js for example? It doesn’t make sense that you need to start from beginning as it’s the same domain (HTTP services, microservices, event system etc etc).
Background: I have more than 9 years of experience primarily as a backend engineer (and don’t know how much time besides work, because who tracks that) starting with PHP, Node.js and Java. Commercialy I have Java the least (1 year in my bio), but am practicing Node, Go and Java the most (and love the latter two) and know a great deal from concurrency to data structures, language traps (or lib traps like ORMs and quite a bit of Hibernate), reactive programming and the memory model of the language. Plus, the language is only one small cog in this domain (db, event streams, caching, batching, resilience, k8s, etc etc).
Maybe I’m not having a good view from my end and want to see if I’m missing something or just some advice?
Hey, I am trying to learn java in 2024. I am in my 2nd year at college with no work experience, just some js and react projects on my github. I learned java in high school through an AP course. I know basics but not all. Would it be worth learning java in 2024? Also, any suggestions on projects I should work on?
I have been having this issue that I cant seem to fix wondering if you have any tips
So everything works fine until a button ends up along the bottom right, then you can't move it
Any help would be appreciated
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
public class FifteenPuzzle extends JFrame {
private JButton[] buttons;
private final int SIZE = 4;
private int emptyIndex = SIZE * SIZE - 1;
public FifteenPuzzle() {
setTitle("15-game");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(SIZE, SIZE));
buttons = new JButton[SIZE * SIZE];
initializeButtons();
for (JButton button : buttons) {
panel.add(button);
}
JButton newGameButton = new JButton("New Game");
newGameButton.addActionListener(e -> shuffleButtons());
add(panel, BorderLayout.CENTER);
add(newGameButton, BorderLayout.SOUTH);
setVisible(true);
}
private void initializeButtons() {
for (int i = 0; i < SIZE * SIZE - 1; i++) {
buttons[i] = new JButton(String.valueOf(i + 1));
buttons[i].setFont(new Font("Arial", Font.BOLD, 20));
buttons[i].addActionListener(new ButtonClickListener());
}
buttons[emptyIndex] = new JButton("");
buttons[emptyIndex].setEnabled(false);
}
private void shuffleButtons() {
ArrayList<String> values = new ArrayList<>();
for (int i = 1; i < SIZE * SIZE; i++) {
values.add(String.valueOf(i));
}
values.add("");
Collections.shuffle(values);
for (int i = 0; i < buttons.length; i++) {
buttons[i].setText(values.get(i));
buttons[i].setEnabled(!values.get(i).equals(""));
if (values.get(i).equals("")) {
emptyIndex = i;
}
}
}
private boolean isSolved() {
for (int i = 0; i < buttons.length - 1; i++) {
if (!buttons[i].getText().equals(String.valueOf(i + 1))) {
return false;
}
}
return true;
}
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton clickedButton = (JButton) e.getSource();
int clickedIndex = -1;
for (int i = 0; i < buttons.length; i++) {
if (buttons[i] == clickedButton) {
clickedIndex = i;
break;
}
}
System.out.println("Clicked button: " + clickedIndex);
if (isAdjacent(clickedIndex, emptyIndex)) {
buttons[emptyIndex].setText(clickedButton.getText());
buttons[emptyIndex].setEnabled(true);
clickedButton.setText("");
clickedButton.setEnabled(false);
emptyIndex = clickedIndex;
if (isSolved()) {
JOptionPane.showMessageDialog(null, "Congrats, you won!");
}
} else {
System.out.println("Clicked button is not next to a empty place");
}
}
}
private boolean isAdjacent(int index1, int index2) {
int row1 = index1 / SIZE, col1 = index1 % SIZE;
int row2 = index2 / SIZE, col2 = index2 % SIZE;
return (Math.abs(row1 - row2) + Math.abs(col1 - col2)) == 1;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(FifteenPuzzle::new);
}
}
Hello! I am trying to recreate an app using java and is connected to an arduino. I only needed help with some codes for the java. Basically it is an app that makes a computer coin operated. The app technically locks a computer by making it full screen and untoggable. Is that possible with java? Also, it must be unclosable with alt+f4 or when trying to terminate it via task manager or are there any other ways that basically makes it foolproof.
Scenario: A client puts a coin down the coinslot then the arduino sends pulses to the java app via serial communication(DSR DTR PINS) then java app starts a timer based on how many pulses it received from the coinslot. If there is a timer the fullscreened app will be removed and will have a small window on the bottom right corner for the timer. Once the timer runs out the java app will go full screen again and could not be bypassed. Then another timer starts for like a minute before shutting down the pc since no one uses it.
I made this scenario since coin operated computers are only popular here in the philippines. Been stressing this out lately. Any feedback would be appreciated. Thank you!
The task is to create a program that allows the user to input two numbers and then provides the sum of the numbers inbetween. eg firstNum = 2, secondNum = 4, sum = 2 + 3 + 4.
I'm getting this error:
Output should be of the type "The sum is 10". Now you printed: First number? Last number?
However I know my code is correct because I checked the solutions on gitHub.
My code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int result = 0;
System.out.print("First number? ");
int firstNum = Integer.valueOf(scanner.nextLine());
System.out.print("Last number? ");
int lastNum = Integer.valueOf(scanner.nextLine());
for (int i = firstNum; i <= lastNum; i++) {
result += i;
}
System.err.println("The sum is: " + result);
}
Solution:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int result = 0;
System.out.println("First number? ");
int givenNumber = Integer.valueOf(scanner.nextLine());
System.out.println("Last number? ");
int given2Number = Integer.valueOf(scanner.nextLine());
for (int i=givenNumber;i<=given2Number;i++){
result += i;
}
System.out.println("The sum is " + result);
}
So, basically I'm in 3rd year(mid of 5th sem) and know little bit of JAVA programming language and want to become a Java developer but my friends are telling me that you can't do because there is very little time left for the drive and you can't do in this period. But I've started learning Java.. What should I do now go for JAVA or for MERN ??
Hey,
Im a 4th year computer science student and i have an interview in a few days, can anyone help me how to prepare and what should i focus on?
So I downloaded Wix toolkit v5 and made sure enviorment variables are correct. When I run wix -h
it works. However when I try to use JPackage it says this error:
[19:57:15.961] Can not find WiX tools (light.exe, candle.exe)
[19:57:15.962] Download WiX 3.0 or later from https://wixtoolset.org and add it to the PATH.
Error: Invalid or unsupported type: [exe]
I read somewhere on stack overflow that the exe error is happening due to it not being able to find Wix. I can't seem to find a solution someone please help me.
I'm trying to do have a method in this format:
public class Class1
...
public void method1(Class2 c2)
..
They're in the same package so I shouldn't have to import them but I keep getting "error: cannot find symbol" with an arrow pointing towards Class2. The (public) class Class2 is compiled so that shouldn't be an issue either. I'm using vlab as an IDE if that's relevant, and javac as the compiler.
So I'm doing the University of Helsinki course on java and this is one of the exercises, If the input is divisible by 400 the program outputs "This is a leap year." same situation if it is divisible by 4. The program is supposed to output "This is not a leap year." when the input doesn't meet the conditions. However when 1700 or 1500 is the input it says 'This is a leap year.'. I am so confused.
public class LeapYear {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Give a year: ");
int year = Integer.valueOf(scan.nextLine());
if (year % 400 == 0 || year % 4 == 0) {
System.out.println("This year is a leap year.");
} else {
System.out.println("This year is not a leap year.");
}
}
}
I've noticed that my jasper report compilation time has tripled going from java 8 to java 17. 48s to compile 140 reports to 150s. This really only effects clean build time for me so I'm not terribly concerned, but it raises two questions.
Are there any other areas that I should specifically check for performance regressions?
Any ideas why this particular task would be so adversely effected?
Hello everybody. I have problem, I compiled and got this error, I understood what the problem was, but I don’t know how to solve it, so I tried to change the list in ArrayList<String>, but the error keeps popping up, how can I do this correctly so that everything works?
My code:
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
public void setLocationCells (ArrayList<String> locs) {
locationCells = locs;
}
Error-
theDotCom.setLocationCells(locations);
^
required: ArrayList<String>
found: int[]
reason: argument mismatch; int[] cannot be converted to ArrayList<String>
1 error
error: compilation failed
Final edit.
The answer was wait()
.
Wait forces a "waiting" concurrent process.. waiting to enter the synchronized block,,, to "stop" waiting, and allows the next one to enter the block.
The purpose of "losing monitors" is so that syntaxes like this are possible:
public synchronized int getValue() throws InterruptedException {
while (value == 0) {
// Thread A enters here, sees value is 0
wait(); // Thread A RELEASES monitor and sleeps
// This allows Thread B to enter getValue() or setValue()!
}
return value;
}
If we assume the syncrhonized as a -ticket based spinlock with adaptive parking- (like the one I speculated bellow)... then the .wait()
will adopt the logic that belongs to the last line of the synchronized
keyword (in my case, the compareAndSwap to the done
flag, so that the next process can enter.)... but place the Thread (that executed wait()
) in a secondary queue of parked processes, which will sleep until notify()
gets called (which I assume calls .unpark(t)
), and then resume in the same ticket based order,,, for exiting the block.
(After more careful thought... the most likely scenario is that the implementation is actually using something like an atomic linkedDeque, that somehow reliably parks Threads until the leading head pops and unparks the next one... I am still thinking how the JVM creates this synchronization...)
///////////////////////////
After thinking more broadly about the issue, I have come to think that there is NOTHING that could potentially make a Thread "lose a monitor".
Why??, because the phrasing is misleading...
It assumes that the synchronization of the syncrhonized
keyword is somehow a sequential ** event-loop **, which is not.
and even if it behaves sequentially from the perspective of the main memory, it is not doing that from the perspective of each Thread.
I tried replicating a barebones synchronization tool, using what I think the JVM may be doing under the hood.
I believe the JNI is assigning 2 int flags and atomically autoincrementing one for each incoming Thread (providing fairness), while another is making every concurrent Thread spin wait until the previous action one has executed.
The difference between my version and the syncrhonized
keyword is my version is 2 millis faster than the keyword on a 50 iteration loop, even with the virtual method call added... which means is alot faster with optimizations. This is not to toot my own horn; I know that a parking is left inside the empty body of the busy wait. so, this may be the thing that is adding those extra millis, this is to say that the syncrhonized
keyword may be doing something very similar. And it should be even faster if .incrementAndGet()
gets translated into getAdd()
AtomicInteger ticket = new AtomicInteger();
AtomicInteger done = new AtomicInteger();
void getMonitor(Runnable syncrhonizedAction) {
int ticket = this.ticket.incrementAndGet();
int curr;
while (ticket != ((curr = done.getOpaque()) + 1)) {}
syncrhonizedAction.run();
assert done.compareAndSet(curr, ticket);
}
I've tried a robustPark(long)
vs a .sleep(long)
and BOTH behave exactly the same.
Every concurrent Thread is made to wait until BOTH .sleep
or robustPark
ends.
So the tooltip from the .sleep(long)
saying that using it will not make the Thread "lose it's monitor"... I think there is nothing able to freeze incoming operations... as long as is not a truly sequential action like:
==========================
As far as I understand... LockSupport.parkNanos()
is the cornerstone of any waiting mechanic.
From Executors
... to Reentrantlocks
, to .sleep()
...
Granted... .sleep
calls whatever parking behavior .parkNanos
is using but does this on the JNI.
but .sleep
says this:
" Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. "
So, the distinction between the .parkNanos
becomes clear with the "subject to the precision and accuracy of system timers" which means the .sleep
will not be bound by spurious wakeups.
So, what is this "monitor"?
If you, (or an AI...) says:
"Monitor ownership: The thread does not release any locks or "monitors" it holds while sleeping.
This means that if the thread has acquired a monitor on an object (e.g., via a synchronized block), it keeps the lock, preventing other threads from accessing synchronized code for that object until sleep() ends."
This "monitor ownership" can ONLY occur while the sequence is ALIVE... not sleeping.
Once the parking subsides... then anything that happens AFTER the parking will still happen, including this "monitoring of main memory flags" or whatever.
Unless... .sleep()
was created with the afterthought that maybe someone may use it inside a busy wait spinlock... which is... weird... since a LockSupport.unpark(t)
method is extremely clear that, the parking side will stop being parked, regardless of time set...
This means that people are more inclined on using .parkNanos()
inside busy waits than .sleep()
. including the fact that the busy wait is supposed to monitor the flag that the unparking side should've swapped... what else could it be watching??
Granted... ChatGPT is not smart, and this may not be the monitor the documentation is referring to... so what is this monitor. and which is the type of parking behavior that could make the Thread "lose its monitors"?
Maybe a .parkNanos()
or any other parking behavior could potentially hoist the flag after the time has subsided creating a memory visibility issue? This is the only thing that may create this "monitor losing" thing.
while (volatileFlag) {
rebustParkNanos(someNanos); //will not spuriously wake.
} // then retry.
But I haven't seen this happen... ever. volatileFlag
has never been hoisted...
Why would it?? If the flag is memory fenced... with volatile or opaqueness... the compiler should be able to respect the fence, and the parking shouldn't affect the load.
I am new to Java, and the concept of OOP as a whole.
Let's say that I have a class with a static variable called "count" which keeps track of the number of objects created from that class. It will have a constructor with some parameters, and in that constructor it will increase the count by 1.
Now let's say I also have a default constructor in that class. In the default constructor, I use the "this" keyword to call the other constructor (with the parameters.)
Here is what the problem is. I want to use the "count" variable as one of the arguments. But if I do that, then it will be called with one less than what the object number actually is. The count only gets increased in the constructor that it's calling.
Is there any way I can still use the "this" keyword in the default constructor, or do I have to manually write the default constructor?
Hi everyone
Im a 3rd year biology student, currently doing a module called Programming with Java. I have never coded before in my life. While the lectures are pretty basic, the exercises and exam papers are super super hard.
I absolutely need to pass this course in order to graduate. We’re fortunately at the beginning of the semester and for now, i’m thinking of doing the mooc course, which was recommended in this sub. And also understand the solutions of the exercises being done (doing them from scratch seems impossible really right now)
Additionally, if anyone has any resources or is willing to help me out, please reach out 🙏
Thank you
Hi all, I want to pretty print some code-like String. (However not the full compiler facilities, no check whether it is valid code). Could antrl be used therefore? (basically only brace identation and maybe some keyword highlighting by uppercase).
I cannot find examples therefor (so maybe antrl is overkill therefore?) - so I kindly ask if it is done; and if not howto, and if there is some implemenation example I would be grateful :)
Thank you
New to java and I was just wondering whether I can follow the controller, services and interfaces architecture when implementing auth in java(through session tokens). I dont think I am allowed to use any external libraries and I cant find any manual auth implementation of authentication. My questions are :
i) Would it be viable to use the structure below or am I overcomplicating stuffs?
ii) I dont need a database so how do I how make my system connect to external services such as a user database.
This is the directory structure that I am following:
authentication_system/
│
├── controllers/
│ ├── AuthController
│ └── ProfileController
│
├── models/
│ └── User
└── Profile
│
├── interfaces/
│ └── AuthInterface
└── ProfileInterface
│
├── services/
│
│
└── utils/
└── PasswordUtils(for hashing pass and stuff)
I’ve been trying to install Java for hours, but nothing works. I’ve tried versions 21, 8 (the recommended one), and even 17, which I thought was already installed. I’ve tried every possible fix: turning off the antivirus, running commands in CMD, deleting temporary files, and using programs to remove older Java versions (but none were found). I’m at a loss as to why Java isn’t on my PC—especially since I play Minecraft daily, and as far as I know, Java is needed to run it. I simply can’t install Java on my PC. What else can I try to solve this?
hi guys i was wondering if there is any swing java library specifically that can help in making a java application that should be like autocad and similar applications ( for space planning ). The only thing I've found is JDXF: Java DXF Library, so I'm wondering if anyone has any suggestions?
this is an example of a java fx application that exists in this way
import java.util.Scanner;
public class Task9 {
public static void main(String\[\] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter the score:");
double score = in.nextDouble();
if (score>100 || score<0)
System.out.println("score is impossible");
else {
int middle = (int) Math.round(score);
double excess = score-middle;
System.out.println("the middle score is: "+middle+", and the excess is: "+excess);
}
}
}
// input 86.4
// output 86 , 0.4000000000000057 (the second number is supposed to be 0.4)
How do I updata Java past version 8? My java is on version 8 and if I click update it claims to be up to date. I tried installing it again but that didnt work.