Skip to content

Latest commit

 

History

History
198 lines (131 loc) · 19.5 KB

File metadata and controls

198 lines (131 loc) · 19.5 KB

Java Basics 2

List questions:

  1. What is the right data type to represent a price in Java?
  2. How do you convert bytes to String?
  3. Can we cast an int value into byte variable? what will happen if the value of int is larger than byte?
  4. There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C) B;
  5. Is ++ operator is thread-safe in Java?
  6. Difference between a = a + b and a += b ?
  7. Can I store a double value in a long variable without casting?
  8. What will this return 3*0.1 == 0.3? true or false?
  9. Which one will take more memory, an int or Integer?
  10. Why is String Immutable in Java?
  11. Can we use String in the switch case?
  12. What is a compile time constant in Java? What is the risk of using it?
  13. The difference between DOM and SAX parser in Java?
  14. Tell me 3 features introduced on JDK 1.7?
  15. Tell me 5 features introduced in JDK 1.8?
  16. What does the following Java program print?
  17. What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?
  18. What does the following Java program print?
  19. System.out.println
  20. How do you prevent SQL Injection in Java Code?
  21. How to Make an Object Immutable in Java? Why Should You Make an Object Immutable?
  22. Which Design Pattern Will You Use to Shield Your Code From a Third Party library Which Will Likely to be Replaced by Another in Couple of Months?
  23. Why Should an Object Used As the Key should be Immutable?
  24. How do you share an object between threads? or How to pass an object from one thread to another?

  1. What is the right data type to represent a price in Java?

BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision.

  1. How do you convert bytes to String?

You can convert bytes to the string using string constructor which accepts byte[], just make sure that right character encoding otherwise platform's default character encoding will be used which may or may not be same.

  1. Can we cast an int value into byte variable? what will happen if the value of int is larger than byte?

Yes, we can cast but int is 32 bit long in java while byte is 8 bit long in java so when you cast an int to byte higher 24 bits are lost and a byte can only hold a value from -128 to 128.

  1. There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C) B;

answer

  1. Is ++ operator is thread-safe in Java?

No it's not a thread safe operator because its involve multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.

  1. Difference between a = a + b and a += b ?

The += operator implicitly cast the result of addition into the type of variable used to hold the result. When you add two integral variable e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens. If result of addition is more than maximum value of a then a + b will give compile time error but a += b will be ok as shown below:

byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert from int to byte
b += a; // ok
  1. Can I store a double value in a long variable without casting?

No, you cannot store a double value into a long variable without casting because the range of double is more that long and you we need to type cast. It's not difficult to answer this question but many developer get it wrong due to confusion on which one is bigger between double and long in Java.

detail

  1. What will this return 3*0.1 == 0.3? true or false?

This is one of the really tricky questions. Out of 100, only 5 developers answered this question and only of them have explained the concept correctly. The short answer is false because some floating point numbers can not be represented exactly.

  1. Which one will take more memory, an int or Integer?

An Integer object will take more memory an Integer is the an object and it store meta data overhead about the object and int is primitive type so its takes less space.

  1. Why is String Immutable in Java?

One of my favorite Java interview question. The String is Immutable in java because java designer thought that string will be heavily used and making it immutable allow some optimization easy sharing same String object between multiple clients. See the link for the more detailed answer. This is a great question for Java programmers with less experience as it gives them food for thought, to think about how things works in Java, what Java designers might have thought when they created String class etc.

detail

  1. Can we use String in the switch case?

Yes from Java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. See the detailed answer for more explanation and discussion.

detail

  1. What is a compile time constant in Java? What is the risk of using it?

public static final variables are also known as a compile time constant, the public is optional there. They are replaced with actual values at compile time because compiler know their value up-front and also knows that it cannot be changed during run-time. One of the problem with this is that if you happened to use a public static final variable from some in-house or third party library and their value changed later than your client will still be using old value even after you deploy a new version of JARs. To avoid that, make sure you compile your program when you upgrade dependency JAR files.

  1. The difference between DOM and SAX parser in Java?

Another common Java question but from XML parsing topic. It's rather simple to answer and that's why many interviewers prefers to ask this question on the telephonic round.

DOM parser loads the whole XML into memory to create a tree based DOM model which helps it quickly locate nodes and make a change in the structure of XML.

While SAX parser is an event based parser and doesn't load the whole XML into memory. Due to this reason DOM is faster than SAX but require more memory and not suitable to parse large XML files.

detail

  1. Tell me 3 features introduced on JDK 1.7?

This is one of the good questions I ask to check whether the candidate is aware of recent development in Java technology space or not. Even though JDK 7 was not a big bang release like JDK 5 or JDK 8, it still has a lot of good feature to count on e.g.

  • try-with-resource statements, which free you from closing streams and resources when you are done with that, Java automatically closes that.
  • Fork-Join pool to implement something like the Map-reduce pattern in Java.
  • Allowing String variable and literal into switch statements.
  • Diamond operator for improved type inference, no need to declare generic type on the right-hand side of variable declaration anymore, results in more readable and succinct code.
  • Another worth noting feature introduced was improved exception handling e.g. allowing you to catch multiple exceptions in the same catch block.

detail

  1. Tell me 5 features introduced in JDK 1.8?

This is the follow-up question of the previous one. Java 8 is path breaking release in Java's history, here are the top 5 features from JDK 8 release

  • Lambda expression, which allows you pass an anonymous function as object.
  • Stream API, take advantage of multiple cores of modern CPU and allows you to write succinct code.
  • Date and Time API, finally you have a solid and easy to use date and time library right into JDK.
  • Extension methods, now you can have static and default method into your interface.
  • Repeated annotation, allows you apply the same annotation multiple times on a type.

detail

  1. What does the following Java program print?
public class Test { public static void main(String[] args)
{
  System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
  }
}

This questions is tricky because unlike the Integer, where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because Double.MIN_VALUE is greater than 0.

  1. What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?

This is another tricky question from Double class. Though Java developer knows about the double primitive type and Double class, while doing floating point arithmetic they don't pay enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw ArithmeticExcpetion and return Double.INFINITY.

Also, note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN. To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. If you know SQL, this is very close to NULL there.

  1. What does the following Java program print?
public class Test {
  public static void main(String[] args) throws Exception {
    char[] chars = new char[] {'\u0097'};
    String str = new String(chars);
    byte[] bytes = str.getBytes();
    System.out.println(Arrays.toString(bytes));
  }
}

The trickiness of this question lies on character encoding and how String to byte array conversion works. In this program, we are first creating a String from a character array, which just has one character '\u0097', after than we are getting byte array from that String and printing that byte. Since \u0097 is within the 8-bit range of byte primitive type, it is reasonable to guess that the str.getBytes() call will return a byte array that contains one element with a value of -105 ((byte) 0x97). However, that's not what the program prints and that's why this question is tricky. As a matter of fact, the output of the program is operating system and locale dependent. On a Windows XP with the US locale, the above program prints [63], if you run this program on Linux or Solaris, you will get different values.

To answer this question correctly, you need to know about how Unicode characters are represented in Java char values and in Java strings, and what role character encoding plays in String.getBytes(). In simple word, to convert a string to a byte array, Java iterate through all the characters that the string represents and turn each one into a number of bytes and finally put the bytes together. The rule that maps each Unicode character into a byte array is called a character encoding. So It's possible that if same character encoding is not used during both encoding and decoding then retrieved value may not be correct. When we call str.getBytes() without specifying a character encoding scheme, the JVM uses the default character encoding of the platform to do the job. The default encoding scheme is operating system and locale dependent. On Linux, it is UTF-8 and on Windows with a US locale, the default encoding is Cp1252. This explains the output we get from running this program on Windows machines with a US locale. No matter which character encoding scheme is used, Java will always translate Unicode characters not recognized by the encoding to 63, which represents the character U+003F (the question mark, ?) in all encodings.

  1. System.out.println
    • System – is a final class in java.lang package. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…“
    • out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data.
    • println – is a method of PrintStream class. println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. print calls write() and the story goes on like that. System.out.println()

    detail

  2. How do you prevent SQL Injection in Java Code?

    This question is more asked to J2EE and Java EE developers than core Java developers, but, it is still a good question to check the JDBC and Security skill of experienced Java programmers.

    You can use PreparedStatement to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack.

    On a similar note, If you are working more on Java EE or J2EE side, then you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them. These are some fields and questions where a good answer can make a lot of difference on your selection.

  3. How to Make an Object Immutable in Java? Why Should You Make an Object Immutable?

    Well, Immutability offers several advantages including thread-safety, ability to cache and result in more readable multithreading code. See here to learn how to make object Immutable. Once again, this question can also go into more detail and depending on your answer, can bring several other questions e.g. when you mention Spring is Immutable, be ready with some reasons on Why String is Immutable in Java.

    • Make your class final - You already have
    • Make all the fields private and final - Make appropriate changes in your code
    • Don't provide any methods that change the state of your instance
    • If you have mutable fields in your class, like List, or Date, making them final won't suffice. You should return a defensive copy from their getters, so that their state isn't mutated by calling methods. stackoverflow
  4. Which Design Pattern Will You Use to Shield Your Code From a Third Party library Which Will Likely to be Replaced by Another in Couple of Months?

    This is just one example of the scenario-based design pattern interview question. In order to test the practical experience of Java developers with more than 5 years experience, companies ask this kind of questions. You can expect more real-world design problems in different formats, some with more detail explanation with context, or some with only intent around.

    One way to shield your code from third party library is to code against an interface rather than implementation and then use dependency injection to provide a particular implementation. This kind of questions is also asked quite frequently to experienced and senior Java developers with 5 to 7 years of experience.

  5. Why Should an Object Used As the Key should be Immutable?

    This is another follow-up of previous core Java interview questions. It's good to test the depth of technical knowledge of candidate by asking more and more question on the same topic. If you know about Immutability, you can answer this question by yourself. The short answer to this question is key should be immutable so that hashCode() method always return the same value.

    Since hash code returned by hashCode() method depends on upon the content of object i.e. values of member variables. If an object is mutable than those values can change and so is the hash code. If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That's why a key object should be immutable. It's not a rule enforced by the compiler but you should take care of it as an experienced programmer.

  6. How do you share an object between threads? or How to pass an object from one thread to another?

    There are multiple ways to do that e.g. Queues, Exchanger etc, but BlockingQueue using Producer Consumer pattern is the easiest way to pass an object from thread to another.