Java general questions
After being in both sides of the interviews I want to share some questions. There are thousands or milions of different questions or forms of questions, but these are really common ones. In the next four posts I will share Java/full stack develper interview questions and here I start with pure Java.
Java 7 vs 8 vs 9 vs 10?
Major Java 7 features:
- enhanced exception handling
- switch on string
- concurrency utils
- fork/join framework
- type inference for generic instance creation
- G1 garbage collector
Major Java 8 features:
- streams API
- new date/time API
- default and static methods in interfaces
Major Java 9 features:
- module system
- JShell: the interactive Java REPL(Read-Eval-Print-Loop)
- collection factory methods(Set<Integer> ints = Set.of(1, 2, 3))
- private interface methods
Major Java 10 features:
- Local Variable Type Inference – var
- Docker support – additional JVM options and awareness of running in container
- Parallel full garbage collection for the G1 garbage collector
What are method references, and how are they useful?
Method references were introduced in Java 8 and allow constructors and methods to be used as lambdas. They allow one to discard the boilerplate of a lambda when the method reference matches an expected signature.
What is aggregation and composition?
Aggregation represents HAS-A relationship; it is a unidirectional association; both entries can survive individually. Code reuse is best achieved by aggregation. For ex: Car -> City <- Tree
Composition represents Part-Of relationship. Objects only exists inside a parent object(Hand -> Person <- Heart)
What is functional programming?
Functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
Don’t Repeat Yourself (DRY) is a principle of software development aimed at reducing repetition of software patterns, replacing them with abstractions; and several copies of the same data, using data normalization to avoid redundancy.
- Single responsibility – a class has just one reason to change, meaning that a class should only do one job.
- Open closed – objects or entities should be open for extension, but closed for modification.
- Liskov substitution – objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. In other words, methods inherited from base class must all be relevant for subclasses.
- Interface segregation – a client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they don’t use.
- Dependency inversion – entities must depend on abstractions not on concretions. High level module must not depend on the low level module, but they should depend on abstractions. Code to an interface.
What is autoboxing/unboxing?
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer.
What is static method?
Static keyword is used to describe how object is managed in memory. Features:
- static method belongs to the class rather than object of a class.
- static method can be invoked without the need for creating an instance of a class.
- static method can access static data member and can change the value of it.
Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.
Static vs dynamic binding(late binding)?
Static binding is determined during compile time, when dynamic binding occurs during runtime.
private, final and static methods and variables, method overloading use static binding while for virtual methods binding is done during run time based upon run time object.
Static binding uses Type information for binding while Dynamic binding uses Objects to resolve binding.
Overloaded methods are resolved using static binding while overridden methods using dynamic binding.
In Java, all non-static methods are by default “virtual functions”. Only methods marked with the keyword final and private are non-virtual.
How to create a virtual method in Java?
A virtual function or virtual method is an inheritable and overridable method which has a late binding. This concept is an important part of the polymorphism
In Java, all non-static methods are by default “virtual functions”. Only methods marked with the keyword final and private are non-virtual.
When designing an abstract class, why should we avoid calling abstract methods inside its constructor?
This is a problem of initialization order. The subclass constructor will not have had a chance to run yet and there is no way to force it to run it before the parent class.
What is final keyword in java?
Use final variable when the value is initialized and will never be changed(for primitives a value, for objects a reference).
What is the difference between String s = “Test” and String s = new String(“Test”)? Which is better and why?
In general, String s = “Test” is more efficient to use than String s = new String(“Test”).
In the case of String s = “Test”, a String with the value “Test” will be created in the String pool. If another String with the same value is then created (e.g., String s2 = “Test”), it will reference this same object in the String pool.
However, if you use String s = new String(“Test”), in addition to creating a String with the value “Test” in the String pool, that String object will then be passed to the constructor of the String Object (i.e., new String(“Test”)) and will create another String object (not in the String pool) with that value. Each such call will therefore create an additional String object.
How to make an immutable class?
- make the class final
- make all the fields final
- don’t expose setters
- when expose method which modifies a state – return a new instance of the class
- if the class holds a mutable object:
- inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through constructor, this is to prevent the clients who pass the object from modifying it afterwards
- make sure to always return a clone copy of the field and never return the real object instance
What are advantages of immutable class?
- thread safety. No matter which thread access it, it always gets the same state and no problems with synchronization
- no invalid state. The state will always remain safe
- better encapsulation
- easier to test. You know that every method is independent from each other
- easier maintainable code – it does not affect other areas of your code. This means there are less intermingled and moving parts in your code. Therefore, your code will be cleaner and easier to understand.
JAR vs WAR
These files are just zipped files using the java jar tool. These files are created for different purposes:
- .jar files contain libraries, resources and accessories files like property files
- .war files file contains a web application that can be deployed on any servlet/jsp container
- .jar is replacing .war, Spring Boot is pushing it forward
What is runtime polymorphism or dynamic method dispatch?
This is an old good late binding. Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.
What is just-in-time compiler?
JVM programs consists of classes which contains platform independent bytecode. At runtime, JVM loads a file and determines semantics for each bytecode and does computation(It needs to adopt the file for current platform). Interpretation requires a lot of processor and disk space. JIT is a component of JRE and is enabled by default. When a method is called, JIT compiles it into a native machine code “just in time”. The JVM executes the compiled code instead of interpreting it.
What is classloader?
Java class loader is a mechanism responsible to load java class into JVM. Classes loaded are first referenced by “public static void main(String args)” method. If the class is not found then it throws ClassNotFoundException. Classloaders has a hierarchy:
Bootstrap (JDK jars: rt.jar, i18.jar…) -> Extension (JDK extension dir “JAVA_HOME/jre/lib/ext”) -> System(loads classpath) Class Loaders.
What is hashCode?
hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
What is equals?
equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.
How does hashmap work?
Typical hashmap explanation is buckets. When you insert a key, value pair into a hashmap, a hashcode(using hashcode method) for a key object is calculated. A pair is put into a bucket with that hashcode number. When retrieving an object, key hashcode is calculated and then a key, value pair is retrieved from the bucket. It is possible that different keys have the same hashcode numbers. Then multiple objects are stored in the same bucket. In that case, our friend “equals” method(returns true/false) comes to help. It checks the equality of keys. When the key of requested object is equal to the key in the bucket – that means this is th object to return.
What is the difference between equals() and == ?
Main difference between == and equals in Java is that “==” is used to compare primitives while equals() method is recommended to check equality of objects. It is possible to compare objects with both “==” and equals(), but “==” returns true only if both references points to same object while equals() can return true or false based on its overridden implementation. In other words, “==” compares references, when “equal” usually is used to compare values(if implementation is provided) for objects.
What is the difference between abstract classes and interfaces? Java 8?
- abstract class can have abstract and non-abstract methods
- abstract class doesn’t support multiple inheritance
- abstract class can have final, non-final, static and non-static variables
- abstract class can have static methods, main method and constructor
- abstract class can provide the implementation of interface
- is the most abstract level of your app design
- interface supports multiple inheritance
- interface created just for describe signatures for sub classes
- interface has only static and final variables
Java 8 built a bridge between abstract class and interface. Even though, differences still exist. Abstract class can have state, constructor when default method can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation’s state. So the main use case is higher-level and convenience methods.
Why you might need to write a Custom ClassLoader in Java?
Java default ClassLoader can load files from local file system that is good enough for most of the cases. But if you are expecting a class at the runtime or from FTP server or via third party web service at the time of loading the class then you have to extend the existing class loader. For example, AppletViewers load the classes from remote web server.
Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?
In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it. In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.
What is difference between fail-fast and fail-safe iterators?
Fail-fast iterators in Java don’t play along when the underlying collection gets modified – it throws exception. When iterating, on each next() call, the current value of modCount gets compared with the initial value. If there’s a mismatch, it throws ConcurrentModificationException which aborts the entire operation. Default iterators for Collections from java.util package such as ArrayList, HashMap, etc. are Fail-Fast.
Fail-Safe iterator removes inconvenience of exception handling. might be called as weakly consistent. That means, if a Collection is modified while being iterated over, what the Iterator sees is weakly guaranteed. This behavior may be different for different Collections and is documented in Javadocs of each such Collection. Iterators on Collections from java.util.concurrent package such as ConcurrentHashMap, CopyOnWriteArrayList, etc. are Fail-Safe.
If one needs a Set, how do you choose between HashSet vs. TreeSet?
At first glance, HashSet is superior in almost every way: O(1) add, remove and contains, vs. O(log(N)) for TreeSet. However, TreeSet is indispensable when you wish to maintain order over the inserted elements or query for a range of elements within the set.
What’s difference between Stack and Queue?
Stack is a collection of objects in which objects are accessed in LIFO (Last In First Out) fashion. Whereas a queue is a collection of objects in which objects are accessed in FIFO (First In First Out) sequence.
Interviewing part 1 – Recruiters’ control <- Previous post
Next post -> Interviewing part 2.2: technical Java questions