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
27161 votes
25 answers
1.9m 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
  • 497k
7757 votes
91 answers
2.7m 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 ...
7530 votes
11 answers
795k views

Why is subtracting these two epoch-milli Times (in year 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 sf ...
Freewind's user avatar
  • 195k
4700 votes
64 answers
2.6m views

How do I read / convert an InputStream into a String in Java?

If you have a 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 it to a String, so for ...
Johnny Maelstrom's user avatar
4396 votes
68 answers
1.4m views

How do I avoid checking for nulls in Java?

I use x != null to avoid NullPointerException. Is there an alternative? if (x != null) { // ... }
4304 votes
35 answers
1.7m views

What are the differences between a HashMap and a Hashtable in Java?

What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications?
dmanxiii's user avatar
  • 51.7k
4089 votes
42 answers
1.8m views

Create ArrayList from array

Element[] array = {new Element(1), new Element(2), new Element(3)}; How do I convert the above variable of type Element[] into a variable of type ArrayList<Element>? ArrayList<Element> ...
Ron Tuffin's user avatar
  • 54.1k
4086 votes
59 answers
5.2m 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
  • 49.1k
4010 votes
12 answers
364k 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 ...
Ovidiu Latcu's user avatar
  • 71.9k
3962 votes
45 answers
3.3m views

How do I efficiently iterate over each entry in a Java 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 ...
iMack's user avatar
  • 38.5k
3848 votes
12 answers
317k views

Why don't Java's +=, -=, *=, /= compound assignment operators require casting long to int?

Until today, I thought that for example: i += j; Was just a shortcut for: i = i + j; But if we try this: int i = 5; long j = 8; Then i = i + j; will not compile but i += j; will compile fine. ...
Honza Brabec's user avatar
  • 37.5k
3837 votes
17 answers
511k 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 ...
Ahamed's user avatar
  • 39.4k
3760 votes
7 answers
4.4m views

Iterate through a HashMap [duplicate]

What's the best way to iterate over the items in a HashMap?
burntsugar's user avatar
  • 57.6k
3721 votes
61 answers
746k views

How can I create a memory leak in Java?

I just had an interview where I was asked to create a memory leak with Java. Needless to say, I felt pretty dumb, having no idea how to start creating one. What would an example be?
3672 votes
31 answers
2.6m 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.3k
3602 votes
34 answers
1.4m views

When to use LinkedList over ArrayList in Java?

I've always been one to simply use: List<String> names = new ArrayList<>(); I use the interface as the type name for portability, so that when I ask questions such as this, I can rework ...
sdellysse's user avatar
  • 39.3k
3493 votes
30 answers
6.8m views

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

How can I convert a String value to an int type? "1234" → 1234
Unknown user's user avatar
  • 44.8k
3414 votes
25 answers
1.1m 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 final serialVersionUID field of type long What is serialVersionUID and why is ...
ashokgelal's user avatar
  • 80.4k
3322 votes
35 answers
3.7m views

Initialization of an ArrayList in one line

I wanted 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"); ...
Macarse's user avatar
  • 92.2k
3207 votes
59 answers
1.2m views

How do I test a class that has private methods, fields or inner classes?

How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test.
2986 votes
3 answers
257k 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 = ...
Kuba Spatny's user avatar
  • 26.7k
2883 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.4k
2718 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.5k
2701 votes
32 answers
2.7m views

How do I determine whether an array contains a particular value in Java?

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?
Mike Sickler's user avatar
  • 33.9k
2684 votes
52 answers
607k views

Does a finally block always get executed in Java?

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is? try { something(); return success; } catch (Exception e) { ...
jonny five's user avatar
  • 27.3k
2664 votes
22 answers
1.1m 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 ...
ashokgelal's user avatar
  • 80.4k
2559 votes
29 answers
1.1m 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 ...
Colin McCree's user avatar
  • 25.7k
2537 votes
25 answers
1.0m 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.
Lehane's user avatar
  • 47.8k
2526 votes
31 answers
5.7m views

How do I declare and initialize an array in Java?

How do I declare and initialize an array in Java?
bestattendance's user avatar
2398 votes
37 answers
3.2m 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
2366 votes
32 answers
1.6m views

How to get an enum value from a string value in Java

Say I have an enum which is just public 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 ...
Malachi's user avatar
  • 33.3k
2356 votes
42 answers
763k views

"implements Runnable" vs "extends Thread" in Java

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() { //...
user65374's user avatar
  • 24.2k
2348 votes
23 answers
789k 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 ...
Amir Rachum's user avatar
  • 77.4k
2286 votes
35 answers
1.9m views

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

How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean ...
SCdF's user avatar
  • 57.9k
2165 votes
15 answers
1.0m 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 ...
Matt Ball's user avatar
  • 356k
2129 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 ...
2124 votes
28 answers
2.0m 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 ...
gnavi's user avatar
  • 25.4k
2072 votes
28 answers
931k 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?
Omnipotent's user avatar
  • 27.8k
2069 votes
37 answers
1.4m views

How do I break 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; // Breaks ...
boutta's user avatar
  • 24.3k
1969 votes
46 answers
1.7m 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 ...
1917 votes
38 answers
4.8m views

How do I split a string in Java?

I want to split a string using a delimiter, for example split "004-034556" into two separate strings by the delimiter "-": part1 = "004"; part2 = "034556"; ...
riyana's user avatar
  • 21.4k
1900 votes
15 answers
221k 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: ...
0x56794E's user avatar
  • 21k
1884 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
  • 704k
1881 votes
65 answers
1.8m 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 ...
1861 votes
37 answers
545k 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.6k
1766 votes
31 answers
318k 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
1760 votes
35 answers
1.7m 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? ...
OscarRyz's user avatar
  • 197k
1735 votes
33 answers
884k 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?
blacktiger's user avatar
1730 votes
51 answers
2.3m 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.9k
1719 votes
29 answers
2.9m views

In detail, how does the 'for each' loop work in Java?

Consider: List<String> someList = new ArrayList<>(); // add "monkey", "donkey", "skeleton key" to someList for (String item : someList) { System.out....
Jay R.'s user avatar
  • 32k

1
2 3 4 5
38245