Questions tagged [java]

Java (not to be confused with JavaScript or JScript or JS) 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 ...

210
votes
12answers
2.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 ...
727
votes
23answers
3.3m 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 ...
5595
votes
77answers
1.7m 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 that it isn't.I don't think I understand the distinction they're making. ...
2048
votes
50answers
1.0m 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....
491
votes
9answers
104k 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 ...
643
votes
16answers
333k 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 ...
214
votes
21answers
480k 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....
510
votes
15answers
340k 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 ...
211
votes
11answers
37k 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.
1547
votes
29answers
254k 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 ...
445
votes
9answers
46k 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 ...
724
votes
11answers
89k 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/...
537
votes
14answers
176k 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?
138
votes
6answers
34k 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?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­...
802
votes
31answers
1.2m 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"}...
290
votes
10answers
680k 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 ...
629
votes
12answers
480k 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" /&...
1600
votes
30answers
1.8m 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 ...
534
votes
7answers
304k 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)...
639
votes
16answers
91k 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<...
229
votes
10answers
213k 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); ...
617
votes
11answers
559k views

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

What issues / pitfalls must be considered when overriding equals and hashCode?
463
votes
12answers
334k 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 ...
2978
votes
61answers
3.6m views

How to 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:randomNum=minimum + (int)(Math.random() * maximum);// Bug: `randomNum` can ...
295
votes
7answers
283k 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 ...
1784
votes
11answers
924k 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. ...
1413
votes
43answers
1.7m 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++,...
1334
votes
31answers
3.2m views

How to split a string in Java

I have a string, "004-034556", that I want to split into two strings:string1="004";string2="034556";That means the first string will contain the characters before '-', and the second string will ...
22014
votes
22answers
1.3m 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>#...
571
votes
11answers
72k 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?
1051
votes
29answers
1.4m 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 ...
74
votes
5answers
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. ...
749
votes
13answers
1.5m 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 useDate date=...
1333
votes
38answers
332k 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 ...
1053
votes
22answers
434k views

Iterating through a Collection, avoiding ConcurrentModificationException when modifying (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'...
2607
votes
24answers
1.7m 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 ...
1011
votes
7answers
259k 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 ...
1413
votes
49answers
1.2m views

Sort a Map<Key, Value> by values

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 ...
483
votes
20answers
730k 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)...
413
votes
19answers
581k 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?
116
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, ...
277
votes
12answers
458k 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/tableat java.sql.DriverManager.getConnection(...
2003
votes
33answers
1.0m 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 a Maven project package all dependency JARs into my output JAR?
974
votes
41answers
1.9m 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 ...
223
votes
14answers
492k 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....
598
votes
22answers
386k 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 ...
128
votes
10answers
50k views

Android permission doesn't work even if I have declared it

I'm trying to write code to send an SMS from an Android app, but when I try to send the SMS it sends me back the error:09-17 18:37:29.974 12847-12847/**.**.****E/AndroidRuntime﹕ FATAL EXCEPTION: ...
64
votes
3answers
29k 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 examplepublic class Application extends ...
911
votes
29answers
630k 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: ...
976
votes
24answers
935k 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 ...

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