Developers and beginners often get stuck in their career as a Java developer and every work need a certain effort and practice to master. Developers often ask questions to their team or the public for solutions. As a Java developer, there are thousands of problems that they face every day. This problem could be critical or minor. Java is a general-purpose object-oriented programming language. For a Java Developer or any developer, the errors keep on occurring. Most commonly programmers tend to face such errors while practicing or experimenting. So, we have created a list of most asked questions about Java to help you guys. Here is a list of questions about Java. 10 Most Asked Questions About Java If you are also a Java developer and if you have also faced errors while coding and if you have some questions about Java, then please first have a look at the solutions below. The below questions about Java are described with the best solutions as possible. 1. Is Java “pass-by-reference” or “pass-by-value”? Answer: Java is always . Unfortunately, when we pass the value of an object, we are passing the to it. This is confusing to beginners as these questions about java are frequently asked by beginners and it goes like this: pass-by-value reference public main( [] args) { Dog aDog = Dog( ); Dog oldDog = aDog; foo(aDog); aDog.getName().equals( ); aDog.getName().equals( ); aDog == oldDog; } public foo(Dog d) { d.getName().equals( ); d = Dog( ); d.getName().equals( ); } static void String new "Max" // we pass the object to foo // aDog variable is still pointing to the "Max" dog when foo(...) returns "Max" // true "Fifi" // false // true static void "Max" // true // change d inside of foo() to point to a new Dog instance "Fifi" new "Fifi" "Fifi" // true In the example above will still return . The value within is not changed in the function with the as the object reference is passed by value. If it were passed by reference, then the in would return after the call to . aDog.getName() "Max" aDog main foo Dog "Fifi" aDog.getName() main "Fifi" foo Likewise: public main( [] args) { Dog aDog = Dog( ); Dog oldDog = aDog; foo(aDog); aDog.getName().equals( ); aDog == oldDog; } public foo(Dog d) { d.getName().equals( ); d.setName( ); } static void String new "Max" // when foo(...) returns, the name of the dog has been changed to "Fifi" "Fifi" // true // but it is still the same dog: // true static void "Max" // true // this changes the name of d to be "Fifi" "Fifi" In the above example, is the dog’s name after a call to because the object’s name was set inside of . Any operations that performs on are such that, for all practical purposes, they are performed on , but it is possible to change the value of the variable itself. Fifi foo(aDog) foo(...) foo d aDog not aDog Additional Answer: The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. The key to understanding this is that something like Dog myDog; is a Dog; it’s actually a to a Dog. not pointer What that means, is when you have Dog myDog = Dog( ); foo(myDog); new "Rover" you’re essentially passing the of the created object to the method. address Dog foo Suppose the object resides at memory address 42. This means we pass 42 to the method. Dog if the Method were defined as public foo(Dog someDog) { someDog.setName( ); someDog = Dog( ); someDog.setName( ); } void "Max" // AAA new "Fifi" // BBB "Rowlf" // CCC let’s look at what’s happening. the parameter is set to the value 42 someDog at line “AAA” is followed to the it points to (the object at address 42) that (the one at address 42) is asked to change his name to Max someDog Dog Dog Dog at line “BBB” a new is created. Let’s say he’s at address 74 we assign the parameter to 74 Dog someDog at line “CCC” is followed to the it points to (the object at address 74) that (the one at address 74) is asked to change his name to Rowlf someDog Dog Dog Dog then, we return Now let’s think about what happens outside the method: Did myDog change? There’s the key. Keeping in mind that is a , and not an actual , the answer is NO. still has the value 42; it’s still pointing to the original (but note that because of the line “AAA”, its name is now “Max” – still the same Dog; ‘s value has not changed.) myDog pointer Dog myDog Dog myDog It’s perfectly valid to an address and change what’s at the end of it; that does not change the variable, however. follow Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method, and change the data that was pointed to. However, you cannot change where that pointer points. In C++, Ada, Pascal,m, and other languages that support pass-by-reference, you can actually change the variable that was passed. If Java had pass-by-reference semantics, the method we defined above would have changed where was pointing when it assigned on line BBB. foo myDog someDog Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in. 2. How to read/convert an InputStream into a String in Java? Answer: A nice way to do this is using to copy the into a , something like Apache commons IOUtils InputStream StringWriter StringWriter writer = StringWriter(); IOUtils.copy(inputStream, writer, encoding); theString = writer.toString(); new String or even theString = IOUtils.toString(inputStream, encoding); // NB: does not close inputStream, you'll have to use try-with-resources for that String Alternatively, you could use if you don’t want to mix your Streams and Writers ByteArrayOutputStream Additional Answer: Also, there are various ways to convert InputStream into a string in Java Using (Apache Utils) IOUtils.toString result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); String Using (Guava) CharStreams result = CharStreams.toString( InputStreamReader( inputStream, Charsets.UTF_8)); String new Using (JDK) Scanner Scanner s = Scanner(inputStream).useDelimiter( ); result = s.hasNext() ? s.next() : ; new "\\A" String "" Using (Java 8). : This solution converts different line breaks (like ) to . Stream API Warning \r\n \n result = BufferedReader( InputStreamReader(inputStream)) .lines().collect(Collectors.joining( )); String new new "\n" Using (Java 8). : This solution converts different line breaks (like ) to . parallel Stream API Warning \r\n \n result = BufferedReader( InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining( )); String new new "\n" Using and (JDK) InputStreamReader StringBuilder final int bufferSize = ; final char[] buffer = char[bufferSize]; final StringBuilder out = StringBuilder(); Reader = InputStreamReader(stream, StandardCharsets.UTF_8); int charsRead; ((charsRead = .read(buffer, , buffer.length)) > ) { out.append(buffer, , charsRead); } out.toString(); 1024 new new in new while in 0 0 0 return Using and (Apache Commons) StringWriter IOUtils.copy StringWriter writer = StringWriter(); IOUtils.copy(inputStream, writer, ); writer.toString(); new "UTF-8" return Using and (JDK) ByteArrayOutputStream inputStream.read ByteArrayOutputStream result = ByteArrayOutputStream(); byte[] buffer = byte[ ]; int length; ((length = inputStream.read(buffer)) != ) { result.write(buffer, , length); } result.toString( ); new new 1024 while -1 0 // StandardCharsets.UTF_8.name() > JDK 7 return "UTF-8" Using (JDK). This solution converts different line breaks (like ) to system property (for example, in Windows to “\r\n”). BufferedReader Warning: \n\r line.separator newLine = System.getProperty( ); BufferedReader reader = BufferedReader( InputStreamReader(inputStream)); StringBuilder result = StringBuilder(); boolean flag = ; ( line; (line = reader.readLine()) != ; ) { result.append(flag? newLine: ).append(line); flag = ; } result.toString(); String "line.separator" new new new false for String null "" true return Using and (JDK) BufferedInputStream ByteArrayOutputStream BufferedInputStream bis = BufferedInputStream(inputStream); ByteArrayOutputStream buf = ByteArrayOutputStream(); int result = bis.read(); (result != ) { buf.write((byte) result); result = bis.read(); } buf.toString( ); new new while -1 // StandardCharsets.UTF_8.name() > JDK 7 return "UTF-8" Using and (JDK). : This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text) inputStream.read() StringBuilder Warning int ch; StringBuilder sb = StringBuilder(); ((ch = inputStream.read()) != ) sb.append((char)ch); reset(); sb.toString(); new while -1 return : Warning Solutions 4, 5, and 9 convert different line break to one. Solution 11 can’t work correctly with Unicode text Performance tests Performance tests for small (length = 175), (mode = Average Time, system = Linux, score 1,343 is the best): String Benchmark Mode Cnt Score Units ByteArrayOutputStream and read (JDK) avgt , ± , us/op InputStreamReader and StringBuilder (JDK) avgt , ± , us/op BufferedInputStream, ByteArrayOutputStream avgt , ± , us/op InputStream.read() and StringBuilder (JDK) avgt , ± , us/op StringWriter and IOUtils.copy (Apache) avgt , ± , us/op IOUtils.toString (Apache Utils) avgt , ± , us/op Scanner (JDK) avgt , ± , us/op CharStreams (guava) avgt , ± , us/op Stream Api (Java ) avgt , ± , us/op BufferedReader (JDK) avgt , ± , us/op parallel Stream Api (Java ) avgt , ± , us/op Error 8. 10 1 343 0 028 6. 10 6 980 0 404 10. 10 7 437 0 735 11. 10 8 977 0 328 7. 10 10 613 0 599 1. 10 10 605 0 527 3. 10 12 083 0 293 2. 10 12 999 0 514 4. 8 10 15 811 0 605 9. 10 16 038 0 711 5. 8 10 21 544 0 583 Performance tests for big (length = 50100) (mode = Average Time, system = Linux, score 200,715 is the best): String Benchmark Mode Cnt Score Units ByteArrayOutputStream and read (JDK) avgt , ± , us/op IOUtils.toString (Apache Utils) avgt , ± , us/op InputStreamReader and StringBuilder (JDK) avgt , ± , us/op StringWriter and IOUtils.copy (Apache) avgt , ± , us/op CharStreams (guava) avgt , ± , us/op BufferedReader (JDK) avgt , ± , us/op parallel Stream Api (Java ) avgt , ± , us/op Stream Api (Java ) avgt , ± , us/op BufferedInputStream, ByteArrayOutputStream avgt , ± , us/op Scanner (JDK) avgt , ± , us/op InputStream.read() and StringBuilder (JDK) avgt , ± , us/op Error 8. 10 200 715 18 103 1. 10 300 019 8 751 6. 10 347 616 130 348 7. 10 352 791 105 337 2. 10 420 137 59 877 9. 10 632 028 17 002 5. 8 10 662 999 46 199 4. 8 10 701 269 82 296 10. 10 740 837 5 613 3. 10 751 417 62 026 11. 10 2919 350 1101 942 Graphs (performance tests depending on Input Stream length in Windows 7 system) Performance test (Average Time) depending on Input Stream length in Windows 7 system: length test8 test4 test5 test9 test6 test7 test1 test3 test2 test10 test11 182 546 1092 3276 9828 29484 58968 0.38 0.938 1.868 4.448 13.412 36.459 72.708 2.362 3.609 5.573 12.769 40.74 81.415 159.864 3.881 5.075 6.904 14.123 50.258 129.937 166.162 2.237 3.493 5.422 11.977 45.98 89.336 177.39 1.261 2.12 4.38 10.698 31.821 86.106 186.636 1.601 2.391 3.646 8.367 38.196 110.221 211.016 1.529 2.381 3.527 8.411 40.551 105.16 212.573 3.035 3.934 8.606 20.858 61.571 118.744 235.428 3.136 6.238 10.508 33.48 43.532 118.044 239.481 1.593 4.736 7.527 20.557 59.856 162.907 323.147 3.913 11.506 23.26 68.644 207.591 600.444 1211.545 3. How to Avoid != null statements? Answer: There are two instances where null checking comes up: Where null is a valid response in terms of the contract; and Where it isn’t a valid response. (2) is easy. Either use statements (assertions) or allow failure Assertions are a highly-underused Java feature that was added in 1.4. The syntax is: assert assert <condition> or assert <condition> : < > object where is a boolean expression and is an object whose method’s output will be included in the error. <condition> <object> toString() An statement throws an if the condition is not true. By default, Java ignores assertions. You can enable assertions by passing the option to the JVM. You can enable and disable assertions for individual classes and packages. This means that you can validate code with the assertions while developing and testing, and disable them in a production environment, although my testing has shown next to no performance impact from assertions. assert Error (AssertionError) -ea Not using assertions, in this case, is OK because the code will just fail, which is what will happen if you use assertions. The only difference is that with assertions it might happen sooner, in a more meaningful way and possibly with extra information, which may help you to figure out why it happened if you weren’t expecting it. (1) Is a little harder. If you have no control over the code you’re calling then you’re stuck. If null is a valid response, you have to check for it. If it’s code that you do control, however (and this is often the case), then it’s a different story. Avoid using nulls as a response. With methods that return collections, it’s easy: return empty collections (or arrays) instead of nulls pretty much all the time. With non-collections, it might be harder. Consider this as an example: if you have these interfaces: public interface Action { doSomething(); } public interface Parser { Action findAction( userInput); } void String Where Parser takes raw user input and finds something to do, perhaps if you’re implementing a command-line interface for something. Now you might make the contract that it returns null if there’s no appropriate action. That leads the null checking you’re talking about. An alternative solution is to never return null and instead use the : Null Object pattern public { private Action DO_NOTHING = Action() { public doSomething() { } }; public Action findAction( userInput) { ( ) { DO_NOTHING; } } } class MyParser implements Parser static new void /* do nothing */ String // ... if /* we can't find any actions */ return Compare: Parser parser = ParserFactory.getParser(); (parser == ) { } Action action = parser.findAction(someInput); (action == ) { } { action.doSomething(); } if null // now what? // this would be an example of where null isn't (or shouldn't be) a valid response if null // do nothing else to ParserFactory.getParser().findAction(someInput).doSomething(); which is a much better design because it leads to more concise code. That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message — especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation. { ParserFactory.getParser().findAction(someInput).doSomething(); } (ActionNotFoundException anfe) { userConsole.err(anfe.getMessage()); } try catch Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user. public Action findAction(final userInput) { Action() { public doSomething() { userConsole.err( + userInput); } } } String /* Code to return requested Action if found */ return new void "Action not found: " 4.Differences between HashMap and Hashtable? Answer: In Java, there are several differences between and : HashMap Hashtable is , whereas is not. This makes better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable synchronized HashMap HashMap does not allow keys or values. allows one key and any number of values. Hashtable null HashMap null null One of HashMap’s subclasses is , so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the for a . This wouldn’t be as easy if you were using . LinkedHashMap HashMap LinkedHashMap Hashtable Since synchronization is not an issue for you, then is better. If synchronization becomes an issue, you may also look at . HashMap oncurrentHashMap Additional Answer: A very common idiom is to “check then put” — i.e. look for an entry in the , and add it if it does not already exist. This is not in any way an atomic operation whether you use or . Map Hashtable HashMap An equivalently synchronized can be obtained by: HashMap Collections.synchronizedMap(myMap); But to correctly implement this logic you need of the form: additional synchronization synchronized(myMap) { (!myMap.containsKey( )) myMap.put( , ); } if "tomato" "tomato" "red" Even iterating over a ‘s entries (or a obtained by ) is not thread-safe unless you also guard the from being modified through additional synchronization. Hashtable HashMap Collections.synchronizedMap Map Implementations of the interface (for example ) solve some of this by including such as: ConcurrentMap ConcurrentHashMap thread-safe check-then-act semantics ConcurrentMap.putIfAbsent(key, value); 5. How and when should UserManager.isUserAGoat() be used? Answer: From the the method used to return until it was changed in API 21. source, false public boolean isUserAGoat() { ; } /** * Used to determine whether the user making this call is subject to * teleportations. * @return whether the user making this call is a goat */ return false It looks like the method has no real use for us as developers. In API 21 the implementation was changed to check if there is an installed app with the package com.coffeestainstudios.goatsimulator public boolean isUserAGoat() { mContext.getPackageManager() .isPackageAvailable( ); } /** * Used to determine whether the user making this call is subject to * teleportations. * * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can * now automatically identify goats using advanced goat recognition technology.</p> * * @return Returns true if the user making this call is a goat. */ return "com.coffeestainstudios.goatsimulator" 6. Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting? Answer: In this case . An extract: §15.26.2 Compound Assignment Operators A compound assignment expression of the form is equivalent to , where is the type of , except that is evaluated only once. Errors in casting can lead to critical failure. E1 op= E2 E1 = (T)((E1) op (E2)) T E1 E1 An example cited from §15.26.2 short x = ; x += ; 3 4.6 and results in x having the value 7 because it is equivalent to: short x = ; x = (short)(x + ); 3 4.6 In other words, is shortcut f . i += j; or i =(type of i) (i + j) 7. How to create ArrayList from array? Answer: In Java, array list can be created from an array using the code which something looks like this ArrayList<>(Arrays.asList(array)); Also the Simplest way can be new List<Element> list = Arrays.asList(array); Alternative Answer: Given: Element[] array = Element[] { Element( ), Element( ), Element( ) }; new new 1 new 2 new 3 The simplest answer is to do: List<Element> list = Arrays.asList(array); This will work fine. But some caveats: The list returned from asList has . So, if you want to be able to add or remove elements from the returned list in your code, you’ll need to wrap it in a new . Otherwise, you’ll get an . fixed size ArrayList UnsupportedOperationException The list returned from is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising. asList() 8. How to generate random integers within a specific range in Java? Answer: In , the standard way to do this is as follows: Java 1.7 or later java.util.concurrent.ThreadLocalRandom; int randomNum = ThreadLocalRandom.current().nextInt(min, max + ); import // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive 1 See . This approach has the advantage of not needing to explicitly initialize a instance, which can be a source of confusion and error if used inappropriately. the relevanpt JavaDoc java.util.Random However, conversely, there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used. , the standard way to do this is as follows: Before Java 1.7 java.util.Random; public int randInt(int min, int max) { Random rand; int randomNum = rand.nextInt((max - min) + ) + min; randomNum; } import /** * Returns a pseudo-random number between min and max, inclusive. * The difference between min and max can be at most * <code>Integer.MAX_VALUE - 1</code>. * * @param min Minimum value * @param max Maximum value. Must be greater than min. * @return Integer between min and max, inclusive. * @see java.util.Random#nextInt(int) */ static // This will (intentionally) not run as written so that folks NOTE: // copy-pasting have to think about how to initialize their // Random instance. Initialization of the Random instance is outside // the main scope of the question, but some decent options are to have // a field that is initialized once and then re-used as needed or to // use ThreadLocalRandom (if using at least Java 1.7). // // In particular, do NOT do 'Random rand = new Random()' here or you // will get not very good / not very random results. // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive 1 return See . In practice, the class is often preferable to . the relevant JavaDoc java.util.Random java.lang.Math.random() In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task. 9. Why is char[] preferred over String for passwords? Answer: . That means once you’ve created the , if another process can dump memory, there’s no way (aside from ) you can get rid of the data before kicks in. Strings are immutable String reflection garbage collection 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 before garbage collection. So yes, this a security concern – but even using only reduces the window of opportunity for an attacker, and it’s only for this specific type of attack. is char[] It’s also possible that arrays being moved by the garbage collector will leave stray copies of the data in memory. The garbage collector clear all memory as it goes, to avoid this sort of thing. Even if it does, there’s still the time during which the contains the actual characters as an attack window. may char[] 10. How to efficiently iterate over each entry in a Java Map? Answer: To efficiently iterate over each entry in a Java, use the following code: < , > map = ... for ( .Entry< , > entry : map.entrySet()) { System.out.println(entry.getKey() + + entry.getValue()); } Map String String Map String String "/" Additional Answer: Also, this description with example may be useful for you For example, if we want to find the sum of all of the keys and values of a map, we can write: Using and iterator Map.Entry long i = ; Iterator< .Entry<Integer, Integer>> it = map.entrySet().iterator(); (it.hasNext()) { .Entry<Integer, Integer> pair = it.next(); i += pair.getKey() + pair.getValue(); } 0 Map while Map Using and foreach Map.Entry long i = ; ( .Entry<Integer, Integer> pair : map.entrySet()) { i += pair.getKey() + pair.getValue(); } 0 for Map Using from Java 8 forEach final long[] i = { }; map.forEach((k, v) -> i[ ] += k + v); 0 0 Using and keySet foreach long i = ; (Integer key : map.keySet()) { i += key + map.get(key); } 0 for Using and keySet iterator long i = ; Iterator<Integer> itr2 = map.keySet().iterator(); (itr2.hasNext()) { Integer key = itr2.next(); i += key + map.get(key); } 0 while Using and for Map.Entry long i = ; (Iterator< .Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) { .Entry<Integer, Integer> entry = entries.next(); i += entry.getKey() + entry.getValue(); } 0 for Map Map Using the Java 8 Stream API final long[] i = { }; map.entrySet().stream().forEach(e -> i[ ] += e.getKey() + e.getValue()); 0 0 Using the Java 8 Stream API parallel final long[] i = { }; map.entrySet().stream().parallel().forEach(e -> i[ ] += e.getKey() + e.getValue()); 0 0 Using of IterableMap Apache Collections long i = ; MapIterator<Integer, Integer> it = iterableMap.mapIterator(); (it.hasNext()) { i += it.next() + it.getValue(); } 0 while Using of Eclipse (CS) collections MutableMap final long[] i = { }; mutableMap.forEachKeyValue((key, value) -> { i[ ] += key + value; }); 0 0 In Conclusion This is the list of 10 most asked questions about Java. Hope this article helped you. Also, don’t forget to share this post since others like you also may have similar problems related to Java. Also, please feel free to ask any questions related to Java, we will be glad to help you. This post was originally posted on DevPost .