Questions tagged [java]

Java is a high-level object-oriented programming language. Use this tag when you're having problems using or understanding the language itself. This tag is frequently used alongside other tags for libraries and/or frameworks used by Java developers.

Filter by
Sorted by
Tagged with
209 votes
12 answers
4.0m views

What is a NullPointerException, and how do I fix it?

What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program ...
723 votes
23 answers
4.5m views

How do I compare strings in Java?

I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug. Is == bad? When should it ...
7729 votes
91 answers
2.6m views

Is Java "pass-by-reference" or "pass-by-value"?

I always thought Java uses pass-by-reference. However, I read a blog post which claims that Java uses pass-by-value. I don't think I understand the distinction the author is making. What is the ...
354 votes
25 answers
975k views

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

What does ArrayIndexOutOfBoundsException mean and how do I get rid of it? Here is a code sample that triggers the exception: String[] names = { "tom", "bob", "harry" }; for (int i = 0; i <= ...
Aaron's user avatar
  • 11.3k
935 votes
25 answers
830k views

Scanner is skipping nextLine() after using next() or nextFoo()?

I am using the Scanner methods nextInt() and nextLine() for reading input. It looks like this: System.out.println("Enter numerical value"); int option; option = input.nextInt(); // Read ...
blekione's user avatar
  • 10.2k
877 votes
23 answers
550k views

Unfortunately MyApp has stopped. How can I solve this?

I am developing an application, and everytime I run it, I get the message: Unfortunately, MyApp has stopped. What can I do to solve this? About this question - obviously inspired by What is a ...
nhaarman's user avatar
  • 98.7k
2711 votes
64 answers
1.5m views

How can I fix 'android.os.NetworkOnMainThreadException'?

I got an error while running my Android project for RssReader. Code: URL url = new URL(urlToRssFeed); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory....
bejoy george's user avatar
  • 29.4k
811 votes
16 answers
348k views

What is a raw type and why shouldn't we use it?

Questions: What are raw types in Java, and why do I often hear that they shouldn't be used in new code? What is the alternative if we can't use raw types, and how is it better?
polygenelubricants's user avatar
548 votes
9 answers
146k views

The Use of Multiple JFrames: Good or Bad Practice? [closed]

I'm developing an application which displays images, and plays sounds from a database. I'm trying to decide whether or not to use a separate JFrame to add images to the database from the GUI. I'm ...
Peddler's user avatar
  • 6,045
972 votes
11 answers
141k views

How do I write a correct micro-benchmark in Java?

How do you write (and run) a correct micro-benchmark in Java? I'm looking for some code samples and comments illustrating various things to think about. Example: Should the benchmark measure time/...
John Nilsson's user avatar
535 votes
18 answers
1.6m views

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

Please explain the following about "Cannot find symbol", "Cannot resolve symbol" or "Symbol not found" errors (in Java): What do they mean? What things can cause them? ...
Stephen C's user avatar
  • 699k
1311 votes
36 answers
2.4m views

How to parse JSON in Java

I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.? { "pageInfo": { "pageName": "abc", "pagePic":...
Muhammad Maqsoodur Rehman's user avatar
245 votes
11 answers
50k views

How to add JTable in JPanel with null layout?

I want to add JTable into JPanel whose layout is null. JPanel contains other components. I have to add JTable at proper position.
Sagar's user avatar
  • 2,475
1763 votes
31 answers
317k views

How can I avoid Java code in JSP files, using JSP 2?

I know that something like the following three lines <%= x+1 %> <%= request.getParameter("name") %> <%! counter++; %> is an old school way of coding and in JSP version 2 ...
chmoelders's user avatar
  • 18.6k
506 votes
9 answers
67k views

Should I avoid the use of set(Preferred|Maximum|Minimum) size methods in Java Swing?

Several times I've been criticized for having suggested the use of the following methods: setPreferredSize() setMinimumSize() setMaximumSize() on Swing components. I don't see any alternatives to ...
Heisenbug's user avatar
  • 38.8k
765 votes
21 answers
719k views

Why is my Spring @Autowired field null?

Note: This is intended to be a canonical answer for a common problem. I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I ...
chrylis -cautiouslyoptimistic-'s user avatar
2387 votes
37 answers
3.1m views

What's the simplest way to print a Java array?

In Java, arrays don't override toString(), so if you try to print one directly, you get the className + '@' + the hex of the hashCode of the array, as defined by Object.toString(): int[] intArray = ...
Alex Spurling's user avatar
407 votes
14 answers
557k views

How do I print my Java object without getting "SomeType@2f92e0f4"?

I have a class defined as follows: public class Person { private String name; // constructor and getter/setter omitted } I tried to print an instance of my class: System.out.println(myPerson); ...
Duncan Jones's user avatar
  • 67.4k
783 votes
7 answers
599k views

What is a stack trace, and how can I use it to debug my application errors?

Sometimes when I run my application it gives me an error that looks like: Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) ...
Rob Hruska's user avatar
  • 119k
173 votes
6 answers
62k views

Providing white space in a Swing GUI

A GUI with no white space appears 'crowded'. How can I provide white space without resorting to explicitly setting the position or size of components?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­...
Andrew Thompson's user avatar
896 votes
19 answers
137k views

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List<...
froadie's user avatar
  • 80.1k
1720 votes
51 answers
2.2m views

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I am trying to use Notepad++ as my all-in-one tool edit, run, compile, etc. I have JRE installed, and I have setup my path variable to the .../bin directory. When I run my "Hello world" in Notepad++,...
ERJAN's user avatar
  • 23.7k
118 votes
19 answers
236k views

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

I have an HTML form in a JSP file in my WebContent/jsps folder. I have a servlet class servlet.java in my default package in src folder. In my web.xml it is mapped as /servlet. I have tried several ...
pongahead's user avatar
  • 1,984
895 votes
16 answers
161k views

What is PECS (Producer Extends Consumer Super)?

I came across PECS (short for Producer extends and Consumer super) while reading up on generics. Can someone explain to me how to use PECS to resolve confusion between extends and super?
peakit's user avatar
  • 28.6k
719 votes
14 answers
647k views

How can I upload files to a server using JSP/Servlet?

How can I upload files to server using JSP/Servlet? I tried this: <form action="upload" method="post"> <input type="text" name="description" /> ...
Thang Pham's user avatar
  • 38.2k
4076 votes
59 answers
5.1m views

How do I generate random integers within a specific range in Java?

How do I generate a random int value in a specific range? The following methods have bugs related to integer overflow: randomNum = minimum + (int)(Math.random() * maximum); // Bug: `randomNum` can be ...
user42155's user avatar
  • 49k
1866 votes
64 answers
4.3m views

What does "Could not find or load main class" mean?

A common problem that new Java developers experience is that their programs fail to run with the error message: Could not find or load main class ... What does this mean, what causes it, and how ...
Stephen C's user avatar
  • 699k
27093 votes
25 answers
1.8m views

Why is processing a sorted array faster than processing an unsorted array?

In this C++ code, sorting the data (before the timed region) makes the primary loop ~6x faster: #include <algorithm> #include <ctime> #include <iostream> int main() { // ...
GManNickG's user avatar
  • 495k
1912 votes
38 answers
4.8m views

How do I split a string in Java?

I want to split the string "004-034556" into two strings by the delimiter "-": part1 = "004"; part2 = "034556"; That means the first string will contain the ...
riyana's user avatar
  • 21.4k
354 votes
7 answers
373k views

How should I use servlets and Ajax?

Whenever I print something inside the servlet and call it by the webbrowser, it returns a new page containing that text. Is there a way to print the text in the current page using Ajax? I'm very new ...
Amir Rachum's user avatar
  • 76.9k
362 votes
14 answers
759k views

Connect Java to a MySQL database

How do you connect to a MySQL database in Java? When I try, I get java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table at java.sql.DriverManager.getConnection(...
abson's user avatar
  • 9,148
617 votes
11 answers
606k views

What issues should be considered when overriding equals and hashCode in Java?

What issues / pitfalls must be considered when overriding equals and hashCode?
Matt Sheppard's user avatar
664 votes
31 answers
1.1m views

Why am I getting a NoClassDefFoundError in Java?

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
John Meagher's user avatar
  • 22.8k
1004 votes
17 answers
2.4m views

Java string to date conversion

What is the best way to convert a String in the format 'January 2, 2010' to a Date in Java? Ultimately, I want to break out the month, the day, and the year as integers so that I can use Date date = ...
littleK's user avatar
  • 19.5k
2871 votes
33 answers
1.9m views

How can I create an executable/runnable JAR with dependencies using Maven?

I want to package my project in a single executable JAR for distribution. How can I make a Maven project package all dependency JARs into my output JAR?
soemirno's user avatar
  • 29.3k
1461 votes
39 answers
2.1m views

How to round a number to n decimal places in Java

What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the ...
Alex Spurling's user avatar
2124 votes
12 answers
1.2m views

How to use java.net.URLConnection to fire and handle HTTP requests

Use of java.net.URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it. That tutorial basically only shows how to fire a GET request and read the response. It ...
1295 votes
31 answers
519k views

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

We all know you can't do the following because of ConcurrentModificationException: for (Object i : l) { if (condition(i)) { l.remove(i); } } But this apparently works sometimes, but ...
Claudiu's user avatar
  • 224k
1844 votes
37 answers
540k views

Why use getters and setters/accessors?

What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables? If getters and setters are ever doing more than just the simple ...
Dean J's user avatar
  • 39.4k
3656 votes
31 answers
2.5m views

What is the difference between public, protected, package-private and private in Java?

In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with ...
intrepion's user avatar
  • 38.1k
361 votes
15 answers
989k views

Non-static variable cannot be referenced from a static context

I've written this test code: class MyProgram { int count = 0; public static void main(String[] args) { System.out.println(count); } } But it gives the following error: Main....
Greg's user avatar
  • 3,643
1872 votes
65 answers
1.7m views

Sort a Map<Key, Value> by values

I need to sort a Map<Key, Value> on the values. Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom ...
59 votes
6 answers
46k views

How to return DataSnapshot value as a result of a method?

I don't have much experience with Java. I'm not sure if this question is stupid, but I need to get a user name from Firebase realtime database and return this name as a result of this method. So, I ...
Ilya S's user avatar
  • 751
151 votes
19 answers
194k views

Int division: Why is the result of 1/3 == 0?

I was writing this code: public static void main(String[] args) { double g = 1 / 3; System.out.printf("%.2f", g); } The result is 0. Why is this, and how do I solve this problem?
Tofiq's user avatar
  • 2,911
88 votes
5 answers
6k views

Swing GUI listeners without AWT

I am a starting Java developer, learning just from internet tutorials. I am learning full-screen GUI applications. I was told yesterday that I shouldn't use AWT in my programs because it is outdated. ...
Hidde's user avatar
  • 11.5k
1231 votes
32 answers
985k views

How to create a generic array in Java?

Due to the implementation of Java generics, you can't have code like this: public class GenSet<E> { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // error: ...
tatsuhirosatou's user avatar
1251 votes
8 answers
325k views

How do servlets work? Instantiation, sessions, shared variables and multithreading

Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables. Now, if 2 or more users send request to this ...
Ku Jon's user avatar
  • 12.5k
51 votes
6 answers
73k views

Connect to Kafka running in Docker

I setup a single node Kafka Docker container on my local machine like it is described in the Confluent documentation (steps 2-3). In addition, I also exposed Zookeeper's port 2181 and Kafka's port ...
Sasha Shpota's user avatar
  • 9,476
102 votes
5 answers
73k views

Why does my ArrayList contain N copies of the last item added to the list?

I'm adding three different objects to an ArrayList, but the list contains three copies of the last object I added. For example: for (Foo f : list) { System.out.println(f.getValue()); } ...
Duncan Jones's user avatar
  • 67.4k
582 votes
20 answers
937k views

String.equals versus == [duplicate]

This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working? public static void main(String...aArguments)...
franvergara66's user avatar

1
2 3 4 5
3849