(3623 Upvotes) If I run the following program, which parses two date strings referencing times one second apart and compares them: public static void main ( String [] args ) throws ParseException { SimpleDateFormat sf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ); String str3 = "1927-12-31 23:54:07" ; String str4 = "1927-12-31 23:54:08" ; Date sDt3 = sf . parse ( str3 ); Date sDt4 = sf . parse ( str4 ); long ld3 = sDt3 . getTime () / 1000 ; long ld4 = sDt4 . getTime () / 1000 ; System . out . println ( ld4 - ld3 ); } The output is: 353 Why is ld4-ld3 not 1 (as I would expect from the one-second difference in the times), but 353 ? If I change the dates to times one second later: String str3 = "1927-12-31 23:54:08" ; String str4 = "1927-12-31 23:54:09" ; Then ld4-ld3 will be 1 . sun.util.calendar.ZoneInfo[id="Asia/Shanghai", offset=28800000,dstSavings=0, useDaylight=false, transitions=19, lastRule=null] Locale(Locale.getDefault()): zh_CN Solution It's a time zone change on December 31st in Shanghai. See this page for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the later possible instant for that local date/time - hence the difference.

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

(2480 Upvotes)

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 do not think I understand the distinction they are making. What is the explanation? Solution Java is always pass-by-value. Unfortunately, they decided to call pointers references, thus confusing newbies. Because those references are passed by value.







(2223 Upvotes) 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. Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j) ? Solution As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract: A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)) , where T is the type of E1 , except that E1 is evaluated only once. An example cited from §15.26.2 [...] the following code is correct: short x = 3 ; x += 4.6 ; and results in x having the value 7 because it is equivalent to: short x = 3 ; x = ( short )( x + 4.6 ); In other words, your assumption is correct.

4) Differences between HashMap and Hashtable?

(1769 Upvotes)

What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications? Solution There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HashMap allows one null key and any number of NULL values. One of HashMap's subclasses is LinkedHashMap , so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn't be as easy if you were using Hashtable . Since synchronization is not an issue for you, I'd recommend HashMap . If synchronization becomes an issue, you may also look at ConcurrentHashMap .

5) (How to) Read/convert an InputStream to a String

(1724 Upvotes)

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 example, so I can write the contents of the stream to a log file). What is the easiest way to take the InputStream and convert it to a String ? Solution A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter ... something like StringWriter writer = new StringWriter (); IOUtils . copy ( inputStream , writer , encoding ); String theString = writer . toString (); or even // NB: does not close inputStream, you can use IOUtils.closeQuietly for that String theString = IOUtils . toString ( inputStream , encoding ); Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

6) Why is char[] preferred over String for passwords in Java?

(1574 Upvotes)

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 passwords. Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[] . Solution Strings are immutable. That means once you've created the string, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before GC kicks in. With an array, you can explicitly wipe the data after you're done with it: you can overwrite the array with anything you like, and the password won't be present anywhere in the system, even beforegarbage collection. So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.

7) (The best way to) Iterate through a HashMap

(1504 Upvotes)

What's the best way to iterate over the items in a HashMap ?

Solution

Iterate through the entrySet like so: public static void printMap ( Map mp ) { Iterator it = mp . entrySet (). iterator (); while ( it . hasNext ()) { Map . Entry pair = ( Map . Entry ) it . next (); System . out . println ( pair . getKey () + " = " + pair . getValue ()); it . remove (); // avoids a ConcurrentModificationException } } Read more on Map



(1486 Upvotes)

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. Solution new ArrayList < Element >( Arrays . asList ( array ))

(1478 Upvotes) 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? Solution Here's a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java: The application creates a long-running thread (or use a thread pool to leak even faster). The thread loads a class via an (optionally custom) ClassLoader. The class allocates a large chunk of memory (e.g. new byte[1000000] ), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster. The thread clears all references to the custom class or the ClassLoader it was loaded from. Repeat. This works because the ThreadLocal keeps a reference to the object, which keeps a reference to its Class, which in turn keeps a reference to its ClassLoader. The ClassLoader, in turn, keeps a reference to all the Classes it has loaded. It gets worse because in many JVM implementations Classes and ClassLoaders are allocated straight into permgen and are never GC'd at all.

10) Generating random integers in a range with Java

(1422 Upvotes)

I am trying to generate a random integer with Java, but random in a specific range. For example, my range is 5-10, meaning that 5 is the smallest possible value the random number can take, and 10 is the biggest. Any other number in between these numbers is possible to be a value, too.







Solution