Java (not to be confused with JavaScript or JScript) is a general-purpose object-oriented programming language designed to be used in conjunction with the Java Virtual Machine (JVM). "Java platform" is the name for a computing system that has installed tools for developing and running Java programs. ...

learn more…| top users | synonyms (8)|java jobs

211
votes
12answers
1.7m 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 ...
727
votes
23answers
2.9m 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 ...
5067
votes
76answers
1.5m views

Is Java “pass-by-reference” or “pass-by-value”?

I always thought Java was pass-by-reference; however I've seen a couple of blog posts (For example, this blog) that claim it's not. I don't think I understand the distinction they're making. What is ...
1818
votes
48answers
931k views

How do 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....
460
votes
9answers
96k 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 ...
566
votes
15answers
274k 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 ...
427
votes
15answers
284k views

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

I am using Scanner methods nextInt() and nextLine() for reading input. Basically, it looks like this:System.out.println("enter numerical value"); int option;option=input.nextInt();//read ...
168
votes
15answers
409k 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[] name={"tom", "dick", "harry"};for(int i=0; i<=name....
198
votes
11answers
35k 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.
1474
votes
28answers
237k views

How to avoid Java code in JSP files?

I'm new to Java EE and I know that something like the following three lines<%=x+1 %><%=request.getParameter("name") %><%! counter++; %>is an old school way of coding and in ...
419
votes
8answers
42k 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:setPreferredSizesetMinimumSizesetMaximumSizeon Swing components. I don't see any alternative to their use ...
649
votes
11answers
81k 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 here for code samples and comments illustrating various things to think about.Example: Should the benchmark measure time/...
128
votes
5answers
30k 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?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­...
472
votes
14answers
159k 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?
676
votes
28answers
1.0m views

How to parse JSON in Java

I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?{"pageInfo": {"pageName": "abc","pagePic": "http://example.com/content.jpg"}...
228
votes
7answers
557k views

What does a “Cannot find symbol” compilation error mean?

Please explain the following about the "Cannot find symbol" error:What does this error mean?What things can cause this error?How does the programmer go about fixing this error?This question is ...
577
votes
12answers
434k views

How to upload files to server using JSP/Servlet?

How can I upload files to server using JSP/Servlet? I tried this:<form action="http://stackoverflow.com.mevn.net/upload" method="post"><input type="text" name="description" /><input type="file" name="file" /&...
1408
votes
25answers
1.5m 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=new ...
477
votes
7answers
258k 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.NullPointerExceptionat com.example.myproject.Book.getTitle(Book.java:16)...
562
votes
12answers
82k 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<...
617
votes
11answers
544k views

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

What issues / pitfalls must be considered when overriding equals and hashCode?
2718
votes
55answers
3.3m 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?I have tried the following, but those do not work:Attempt 1:/ Bug: `randomNum` can be bigger than `maximum`.randomNum=minimum + (int)(...
188
votes
9answers
175k 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); ...
1685
votes
12answers
878k 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. ...
277
votes
7answers
253k views

How to use Servlets and Ajax?

I'm very new to web apps and Servlets and I have the following question:Whenever I print something inside the servlet and call it by the webbrowser, it returns a new page containing that text. Is ...
1317
votes
41answers
1.6m 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 .http://stackoverflow.com/bin directory.When I run my "Hello world" in Notepad++,...
386
votes
11answers
279k 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 ...
1159
votes
30answers
2.8m views

How to split a string in Java

I have a string, "004-034556", that I want to split into two strings:string1=004string2=034556That means the first string will contain the characters before '-', and the second string will ...
945
votes
30answers
1.3m 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 previous number. This is the ...
68
votes
4answers
4k views

Java 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. ...
20592
votes
21answers
1.2m views

Why is it faster to process a sorted array than an unsorted array?

Here is a piece of C++ code that seems very peculiar. For some strange reason, sorting the data miraculously makes the code almost six times faster.#include <algorithm>#include <ctime>#...
1234
votes
38answers
304k views

Why use getters and setters/accessors? [closed]

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 ...
675
votes
13answers
1.3m views

Java string to date conversion

Can somebody recommend 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 ...
939
votes
6answers
239k 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 ...
445
votes
20answers
681k views

Java 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)...
958
votes
19answers
403k views

Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop

We all know you can't do this:for (Object i : l) {if (condition(i)) {l.remove(i);}}ConcurrentModificationException etc... this apparently works sometimes, but not always. Here'...
-6
votes
2answers
33k views

How to avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]

If your question is I am getting a java.lang.ArrayIndexOutOfBoundsException in my code and I do not understand why it is happening. What does it mean and how can I avoid it?This is meant to be the ...
503
votes
9answers
60k 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?
1307
votes
45answers
1.2m views

Sort a Map<Key, Value> by values (Java)

I am relatively new to Java, and often find that 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 ...
2255
votes
26answers
1.5m views

In Java, difference between package private, public, protected, and private

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 ...
97
votes
1answer
4k views

Example images for code and mark-up Q&As [closed]

When preparing an MCVE/SSCCE that involves images, it is useful to have direct access to images. The types of images that would cover most questions are - small images in multiple colors or shapes, ...
564
votes
23answers
364k views

Sending Email in Android using JavaMail API without using the default/built-in app

I am trying to create a mail sending application in Android. If I use: Intent emailIntent=new Intent(android.content.Intent.ACTION_SEND);This will launch the built-in Android application; I'm ...
49
votes
3answers
17k views

Why does Spring MVC respond with a 404 and report “No mapping found for HTTP request with URI […] in DispatcherServlet”?

I'm writing a Spring MVC application, deployed on Tomcat. See the following minimal, complete, and verifiable example:public class Application extends ...
191
votes
11answers
424k 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....
1818
votes
33answers
928k views

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

I want to package my project in a single executable JAR for distribution.How can I make Maven package all dependency JARs into my JAR?
348
votes
17answers
508k 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?
824
votes
28answers
565k 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: ...
245
votes
12answers
390k views

Connect Java to a MySQL database

How do you connect to a MySQL database in Java?
906
votes
23answers
857k views

Sort ArrayList of custom Objects by property

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.I wanted to sort an ArrayList of custom ...
772
votes
38answers
1.6m 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 ...

153050per page
angop.ao, elkhabar.com, noa.al, afghanpaper.com, bbc.com, time.com, cdc.gov, nih.gov, xnxx.com, github.com,