Java Interview Qs Flashcards
List all the primitives in Java
byte short int long float double char boolean
What is the difference between StringBuilder() and StringBuffer()?
StringBuffer() is threadsafe
What are the 4 principles of Object Oriented Programming?
Abstraction
Polymorphism
Inheritance
Encapsulation
Explain abstraction.
handle complexity by hiding unnecessary details from the user
Abstraction means using simple things to represent complexity. We all know how to turn the TV on, but we don’t need to know how it works in order to enjoy it. In Java, abstraction means simple things like objects, classes, and variables represent more complex underlying code and data. This is important because it lets us avoid repeating the same work multiple times.
Explain polymorphism.
“SAME NAME, MANY FORMS. This Java OOP concept lets programmers use the same word to mean different things in different contexts. It allows programmers to write code that doesn’t have to change when new subtypes are introduced into the program.
One form of polymorphism in Java is method overloading. That’s when there are multiple functions with the same name but with different arguments. Functions can be overloaded by change in number of arguments and/or change in type of arguments.
The other form is method overriding. That’s when the different meanings are implied by the values of the supplied variables. When overriding a method, the arguments must be the same as the super type and the return types must be compatible. The method cannot be less accessible than the super method call.
TWO TYPES:
Runtime Time Polymorphism handled during runtime: example (Overriding)
Compile Time Polymorphism (static polymorphism) handled in the compiler: example (Overloading)”
Explain inheritance.
"This is a special feature of Object Oriented Programming in Java. It lets programmers create new classes that share some of the attributes of existing classes. This lets us build on previous work without reinventing the wheel. * The ability for a sub class to access the super class's members implicitly through the keyword `extends`; Members include methods as well as variables."
Do not use ‘parent/ child’ to describe this relationship
Explain encapsulation.
This is the practice of keeping fields within a class private, then providing access to them via public methods. It’s a protective barrier that keeps the data and code safe within the class itself. This way, we can re-use objects like code components or variables without allowing open access to the data system-wide.
What are the 4 access modifiers and their access specifiers
Public: Global, Package, Class, Subclass, Variable
Protected: Package, Class, Subclass
Default: Package, Class,
Private: Class, Variable
“Default” is leaving the field/method without an access modifier
What are the 5 SOLID principles?
Single Responsibility Open/Close Principle Liskov's Substitution Principle Interface Segregation Principle Dependency Inversion
Explain “Single Responsibility”
a class should have only a single responsibility (i.e. changes to only one part of the software’s specification should be able to affect the specification of the class).
Explain “Open/Close Principle”
“open for extension, but closed for modification.” classes’ properties can be inherited and used by subclasses etc, but not altered directly.
Explain “Liskov’s Substitution Principle”
“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”
Enables you to replace objects of a parent class with objects of a subclass without breaking the application. This requires all subclasses to behave in the same way as the parent class. To achieve that, your subclasses need to follow these rules:
- Don’t implement any stricter validation rules on input parameters than implemented by the parent class.
- Apply at the least the same rules to all output parameters as applied by the parent class.
Explain “Interface Segregation Principle”
"many client-specific interfaces are better than one general-purpose interface." in other words, when you implement an interface, do you want your class flooded with empty methods you'll never use, or just the few that offer the functionality you are looking for?
Explain “Dependency Inversion”
one should “depend upon abstractions, [not] concretions.”
High-level modules, which provide complex logic, should be easily reusable and unaffected by changes in low-level modules, which provide utility features. To achieve that, you need to introduce an abstraction that decouples the high-level and low-level modules from each other.
In other words–don’t extend ArrayList class to get those functions; implement List interface instead.
What is the difference between overloading and overriding?
Overloading occurs when two or more methods in one class have the same method name but different parameters. Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding changes the BEHAVIOR of the method.
What is the difference between an abstract class and an interface?
An abstract class can contain non abstract methods and default methods, an interface can only contain method signatures.
A class can only extend one abstract class, but it can implement multiple interfaces.
An abstract class can have any access modifiers on its methods and fields, an interface can only be public. Interface fields are public static final.
Both can let you use classes of the same supertype.
For Interface and Abstract Class, why would you use one over the other?
You can implement multiple interfaces but you can only extend one abstract class. Also, you can flesh out methods more fully in an abstract class; Interfaces are for empty methods.
What is the difference between “Collection” and “Collections”
Collections is a utility class present in java.util. package to define several utility method (like sorting,searching ) for collection object. Collections is a class that defines methods that are used to operate on a collection.
Collection is an interface; the root interface in the collection hierarchy. It provides classes and interfaces to represent a group of individual objects as a single unit.
What is an ArrayStoreException? Is it checked or unchecked?
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. It is an unchecked error that occurs at runtime.
Describe JVM, JDK, and JRE
JDK: Java development kit is the tool necessary to compile, document and package Java programs. (like SDK)
JRE: A subset of the Java Development Kit (JDK) for end-users and developers who want to redistribute the runtime environment alone. The Java runtime environment consists of the Java virtual machine, the Java core classes, and supporting files. Abstracts away machine differences for java programs to run.
JVM: The java virtual machine is a specification that provides run-time environment in which java byte code can be executed. (Environment where Java programs can be run)
What is a HashMap?
HashMap is a Map based class that is used for storing Key & value pairs, does not sort the stored keys and Values
TALK ABOUT BUCKETS AND COLLISION
Key-value pairs are stored in what is known as buckets which together make up what is called a table, which is actually an internal array.
Hash maps store both key and value in the bucket location as a Map.Entry object.
A collision, or more specifically, a hash code collision in a HashMap, is a situation where two or more key objects produce the same final hash value and hence point to the same bucket location or array index.
This scenario can occur because according to the equals and hashCode contract, two unequal objects in Java can have the same hash code.
Java implements a hash code collision resolution technique.
It’s the hash value of the key that determines the bucket the object will be stored in. And so, if the hash codes of any two keys collide, their entries will still be stored in the same bucket.
And by default, the implementation uses a linked list as the bucket implementation.
Why is a HashMap unsorted?
Two reasons:
One, it IS sorted by Java’s own internal logic; entries are sorted by hashcode. It is not sorted in any human-readable way
Two, HashMaps are SETS of key-value pairs, and sets are (often) unsorted sets of unique values.
What is the difference between Comparable and Comparator?
Comparable: This interface has one method, compareTo() which compares a specific object to another. Class with objects to be sorted must implement this Comparable interface.
Comparator: It’s its own class that is designed to compare objects of the same type and is specifically for custom comparisons. This interface has two methods, equals() and compare(). Class with objects to be sorted do not need to implement this Comparator interface.
What is the Class Loader?
Part of JVM which is used to load classes and interfaces.
What are the 5 exception keywords?
Try, Catch, Finally, Throw, Throws
Difference between throw and throws?
"Throws" goes in signature: void method() throws Exception {}
"Throw"" goes in method body: void method() { throw new Exception; }
Difference between Final, Finally, Finalize?
Final: Final is a keyword used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.
Finally: Finally is a code block used to place important code, it will be executed whether exception is handled or not.
Finalize: Finalize is a method used to perform clean up processing just before object is garbage collected.
What is Dictionary in Java?
The Dictionary class is the abstract parent of classes like Hashtable , which maps keys to values. Any non- null object can be used as a key and as a value.
Which collection is the fastest?
Every collection type is suitable for a particular scenario. There is no fastest or best collection.
Need to access using INDEX -> ArrayList
Need to access using KEY -> HashMap
Need to access using VALUE -> HashSet
Need fast traversal or fast add/remove of elements -> LinkedList
Sets are internally backed by Map implementation, so performance technically is the same, although the performance of both degrades towards that of a LinkedList when hashing of key object is poor (many hash collisions)
ArrayList is backed by Arrays internally, so they are very fast for by-index access of elements
What is the difference between instance methods and static methods?
Static methods contain the keyword static in their signature and can be called without an instantiation of the class they belong to.
Instance methods are the opposite - do not contain static keyword in the signature and require you to call them from an instance of the class.
What is an instance variable?
An attribute, or field of an object.
What is the finalize method?
The method called before garbage collection on any Java object.
What is an access modifier?
A clause that describes who or what can access or modifiy the state of an object. Examples: public, private, default, protected
What is an abstract class?
A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.
What is an abstract method?
A method that has no implementation. ex interface methods are abstract
What is an API?
Application Programming Interface. The specification of how a programmer writing an application that accesses the behavior and state of classes and objects. A software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.
What is autoboxing?
Automatic conversion between reference (Wrapper classes) and primitive types.
DONE BY COMPILER
what is a class variable?
A data item associated with a particular class as a whole–not with particular instances of the class. Class variables are defined in class definitions. Also called a static field
What is a class path?
An environmental variable which tells the Java virtual machine and Java technology-based applications where to find the class libraries, including user-defined class libraries.
What does DOM stand for?
Document object model.
What is an enumerated type?
A type whose legal values consist of a fixed set of constants. An example of this would be an enum.
Explain garbage collection
The automatic detection and freeing of memory that is no longer in reference. The Java runtime system performs garbage collection so that programmers never explicitly free objects.
What is generics?
Definition: “A generic type is a generic class or interface that is parameterized over types.”
Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.
Rather than specifying obj to be of an int type, or a String type, or any other type, you define the Box class to accept a type parameter . Then, you can use T to represent that generic type in any part within your class.
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
Explain type erasure
The deletion of paramatized types at runtime.
To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded
Explain JAR (Java Archive)
Platform-independent file format that aggregates many files into one. Multiple applets written in the Java programming language, and their requisite components can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction.
Why is java considered dynamic?
It can run on any operating system that has a JVM.
What does it mean to be multithreaded?
Designed to have parts of its code execute concurrently (in parallel)
What does it mean to be protected?
Signifies that the method or variable can only be accessed by elements residing in its class, subclasses, or classes in the same package.
What is a Command pattern?
A request is wrapped under an object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command.
What is an Adapter pattern?
Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
What is a Facade pattern?
provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher- level interface that makes the subsystem easier to use.
It simplifies an interface and decouples a client from a subsystem of components. It hides complexities of a system and provides an interface to the client from where the client can access the system.
An example can be the startup of a computer. When a computer starts up, it involves the work of cpu, memory, hard drive, etc. To make it easy to use for users, we can add a facade which wrap the complexity of the task, and provide one simple interface instead.
What is the difference between Adapter and Facade?
Adapter links two incompatible interfaces and facade is used when you want an easier or simpler interface to work with.