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

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>#...
5745
votes
8answers
521k views

Why is subtracting these two times (in 1927) giving a strange result?

If I run the following program, which parses two date strings referencing times 1 second apart and compares them:public static void main(String[] args) throws ParseException {SimpleDateFormat ...
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 ...
3372
votes
58answers
1.0m views

Avoiding !=null statements

I use object !=null a lot to avoid NullPointerExceptions.Is there a good alternative to this? For example:if (someobject !=null) {someobject.doCalc();}This avoids a ...
3164
votes
11answers
236k views

Java's +=, -=, *=, /=compound assignment operators

Until today, I thought that for example:i +=j;is just a shortcut for:i=i + j;But what if we try this:int i=5;long j=8;Then i=i + j; will not compile but i +=j; will compile fine....
3010
votes
55answers
1.6m views

Read/convert an InputStream to a String

If you have java.io.InputStream object, how should you process that object and produce a String?Suppose I have an InputStream that contains text data, and I want to convert this to a String. For ...
2968
votes
11answers
258k views

Proper use cases for Android UserManager.isUserAGoat()?

I was looking at the new APIs introduced in Android 4.2.While looking at the UserManager class I came across the following method:public boolean isUserAGoat()Used to determine whether the user ...
2935
votes
38answers
1.2m views

Differences between HashMap and Hashtable?

What are the differences between a HashMap and a Hashtable in Java?Which is more efficient for non-threaded applications?
2769
votes
32answers
1.2m views

Create ArrayList from array

I have an array that is initialized like:Element[] array={new Element(1), new Element(2), new Element(3)};I would like to convert this array into an object of the ArrayList class.ArrayList<...
2727
votes
16answers
291k views

Why is char[] preferred over String for passwords?

In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle ...
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)(...
2655
votes
7answers
2.9m views

Iterate through a HashMap [duplicate]

Possible Duplicate: How to efficiently iterate over each entry in a 'Map'?What's the best way to iterate over the items in a HashMap?
2467
votes
51answers
497k views

Creating a memory leak with Java

I just had an interview, and I was asked to create a memory leak with Java.Needless to say I felt pretty dumb having no clue on how to even start creating one.What would an example be?
2427
votes
31answers
836k views

When to use LinkedList over ArrayList?

I've always been one to simply use:List<String> names=new ArrayList<String>();I use the interface as the type name for portability, so that when I ask questions such as these I can ...
2327
votes
31answers
4.9m views

How do I convert a String to an int in Java?

How can I convert a String to an int in Java?My String contains only numbers, and I want to return the number it represents.For example, given the string "1234" the result should be the number ...
2305
votes
22answers
664k views

What is a serialVersionUID and why should I use it?

Eclipse issues warnings when a serialVersionUID is missing. The serializable class Foo does not declare a static finalserialVersionUID field of type longWhat is serialVersionUID and why is ...
2302
votes
2answers
201k views

Why is printing “B” dramatically slower than printing “#”?

I generated two matrices of 1000 x 1000:First Matrix: O and #.Second Matrix: O and B.Using the following code, the first matrix took 8.52 seconds to complete:Random r=new Random();for (int i ...
2269
votes
35answers
1.8m views

How to efficiently iterate over each entry in a 'Map'?

If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?Will the ordering of ...
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 ...
1964
votes
32answers
2.1m views

Initialization of an ArrayList in one line

I want to create a list of options for testing purposes. At first, I did this:ArrayList<String> places=new ArrayList<String>();places.add("Buenos Aires");places.add("Córdoba");...
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....
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?
1715
votes
24answers
1.4m views

How can I test if an array contains a certain value?

I have a String[] with values like so:public static final String[] VALUES=new String[] {"AB","BC","CD","AE"};Given String s, is there a good way of testing whether VALUES contains s?
1694
votes
43answers
348k views

Does finally always execute in Java?

I have a try/catch block with returns inside it. Will the finally block be called?For example:try { something(); return success; } catch (Exception e) { return failure; } ...
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. ...
1671
votes
16answers
609k views

How do I call one constructor from another in Java?

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do ...
1666
votes
39answers
564k views

“implements Runnable” vs. “extends Thread”

From what time I've spent with threads in Java, I've found these two ways to write threads:With implements Runnable:public class MyRunnable implements Runnable {public void run() {//...
1532
votes
14answers
171k views

Why does this code using random strings print “hello world”?

The following print statement would print "hello world".Could anyone explain this?System.out.println(randomString(-229985452) + " " + randomString(-147909649));And randomString() looks like this:...
1530
votes
20answers
697k views

What is reflection and why is it useful?

What is reflection, and why is it useful?I'm particularly interested in Java, but I assume the principles are the same in any language.
1485
votes
23answers
790k views

Lookup Java enum by string value

Say I have an enum which is justpublic enum Blah {A, B, C, D}and I would like to find the enum value of a string, for example "A" which would be Blah.A. How would it be possible to do this?...
1483
votes
17answers
3.4m views

How do I declare and initialize an array in Java?

How do I declare and initialize an array in Java?
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 ...
1468
votes
29answers
833k views

How do you assert that a certain exception is thrown in JUnit 4 tests?

How can I use JUnit4 idiomatically to test that some code throws an exception?While I can certainly do something like this:@Testpublic void testFooThrowsIndexOutOfBoundsException() {boolean ...
1459
votes
30answers
875k views

Breaking out of nested loops in Java

I've got a nested loop construct like this:for (Type type : types) {for (Type t : types2) {if (some condition) {// Do something and break...break; // ...
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 ...
1395
votes
23answers
598k views

Java inner class and static nested class

What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?
1355
votes
39answers
1.1m views

How to generate a random alpha-numeric string?

I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over ...
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++,...
1314
votes
15answers
461k views

Comparing Java enum members:==or equals()?

I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used .equals(), e.g.public ...
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 ...
1302
votes
24answers
553k views

What's the difference between @Component, @Repository & @Service annotations in Spring?

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?In other words, if I have a ...
1261
votes
31answers
645k views

Difference between StringBuilder and StringBuffer

What is the main difference between StringBuffer and StringBuilder?Is there any performance issues when deciding on any one of these?
1255
votes
18answers
297k views

How can I permanently enable line numbers in IntelliJ?

How can I permanently enable line numbers in IntelliJ IDEA?
1244
votes
14answers
402k views

What is a JavaBean exactly?

I understood, I think, that a "Bean" is a Java class with properties and getters/setters. As much as I understand, it is the equivalent of a C struct. Is that true?Also, is there a real syntactic ...
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 ...
1202
votes
8answers
65k views

Why is executing Java code in comments with certain Unicode characters allowed?

The following code produces the output "Hello World!" (no really, try it).public static void main(String... args) {// The comment below is not a typohttp:// \u000d System.out.println("Hello ...
1201
votes
19answers
787k views

Does Java support default parameter values?

I came across some Java code that had the following structure:public MyParameterizedFunction(String param1, int param2){this(param1, param2, false);}public MyParameterizedFunction(String ...
1164
votes
32answers
960k views

Dealing with “java.lang.OutOfMemoryError: PermGen space” error

Recently I ran into this error in my web application:java.lang.OutOfMemoryError: PermGen spaceIt's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6.Apparently ...
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 ...
1130
votes
28answers
1.0m views

How do I create a Java string from the contents of a file?

I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.Is there a better/different way to read a file into a string in Java?...

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