Core Java FAQ
Core Java FAQ
There are four principle concepts upon which object oriented design and programming rest.
They are:
• Abstraction
• Polymorphism
• Inheritance
• Encapsulation (i.e. easily remembered as A-PIE).
2.What is Abstraction?
Abstraction refers to the act of representing essential features without including the
background details or explanations.
3.What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and
allowing outside access only as appropriate. It prevents other objects from directly altering or
accessing the properties or methods of the encapsulated object.
• Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation
(information hiding) prevents clients from seeing it’s inside view, where the behavior
of the abstraction is implemented.
• Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
• Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about
grouping up your abstraction to suit the developer needs.
5. What is Inheritance?
• Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
• A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• Inheritance is done by using the keyword extends.
• The two most common reasons to use inheritance are:
o To promote code reuse
o To use polymorphism
6. What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a
characteristic of being able to assign a different meaning or usage to something in different
contexts - specifically, to allow an entity such as a variable, a function, or an object to have
more than one form.
• In some cases, multiple methods have the same name, but different formal argument
lists (overloaded methods).
• In other cases, multiple methods have the same name, same return type, and same
formal argument list (overridden methods).
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
13. What are the differences between method overloading and method overriding?
Overloaded Method Overridden Method
• If even a single method is abstract, the whole class must be declared abstract.
• Abstract classes may not be instantiated, and require subclasses to provide
implementations for the abstract methods.
• You can’t mark a class as both abstract and final.
27. What are the differences between Interface and Abstract class?
Abstract Class Interfaces
An abstract class can have any visibility: An Interface visibility must be public (or)
public, private, protected. none.
28. When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
• If various implementations are of the same kind and use common behavior or status
then abstract class is better to use.
• When you want to provide a generalized form of abstraction and leave the
implementation task with the inheriting subclass.
• Abstract classes are an excellent way to create planned inheritance hierarchies.
They're also a good choice for nonleaf classes in class hierarchies.
29. When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.
• A constructor is a special method whose task is to initialize the object of its class.
• It is special because its name is the same as the class name.
• They do not have return types, not even void and therefore they cannot return values.
• They cannot be inherited, though a derived class can call the base class constructor.
• Constructor is invoked whenever an object of its associated class is created.
Return No return type, not even void void or a valid return type
Type
Name Same name as the class (first Any name except the class.
letter is capitalized by Method names begin with a
convention) -- usually a noun lowercase letter by convention --
usually the name of an action
• Constructors use this to refer to another constructor in the same class with a different
parameter list.
• Constructors use super to invoke the superclass's constructor. If a constructor uses
super, it must use it in the first line; otherwise, the compiler will complain.
36. What are the differences between Class Methods and Instance Methods?
Class Methods Instance Methods
Class methods can only operate on class Instance methods of the class can also not
members and not on instance members as be called from within a class method
class methods are unaware of instance unless they are being called on an instance
members. of that class.
• Constructors use this to refer to another constructor in the same class with a different
parameter list.
• Constructors use super to invoke the superclass's constructor. If a constructor uses
super, it must use it in the first line; otherwise, the compiler will complain.
• Public- public classes, methods, and fields can be accessed from everywhere.
• Protected- protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes of the
same package.
• Default(no specifier)- If you do not set access to specific level, then such a class,
method, or field will be accessible from inside the same package to which the class,
method, or field belongs, but not from outside this package.
• Private- Private Methods and fields can only be accessed within the same class to
which the methods and fields belong. Private methods and fields are not visible within
subclasses and are not inherited by subclasses.
Accessible to class
yes yes yes no
from same package?
Accessible to class
yes no, unless it is a subclass no no
from different package?
Where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized
with a default value. The default value depends on the data type of the variables.
• Obtain an iterator to the start of the collection by calling the collection’s iterator
() method.
• Set up a loop that makes a call to hasNext(). Have the loop iterate as long as
hasNext() returns true.
• Within the loop, obtain each element by calling next ().
The ArrayList increases its array size by 50 A Vector defaults to doubling the size of
percent if it runs out of room. its array if it runs out of room
ArrayList has no default size. While vector has a default size of 10.
• ArrayList internally uses and array to store the elements, when that array gets filled
by inserting elements a new array of roughly 1.5 times the size of the original array is
created and all the data of old array is copied to new array.
• During deletion, all elements present in the array after the deleted elements have to
be moved one step back to fill the space created by deletion. In linked list data is
stored in nodes that have reference to the previous node and the next node so adding
element is simple as creating the node an updating the next pointer on the last node
and the previous pointer on the new node. Deletion in linked list is fast because it
involves only updating the next pointer in the node before the deleted node and
updating the previous pointer in the node after the deleted node.
58. How do you decide when to use ArrayList and When to use Linked List?
If you need to support random access, without inserting or removing elements from any place
other than the end, then ArrayList offers the optimal collection. If, however, you need to
frequently add and remove elements from the middle of the list and only access the list
elements sequentially, then Linked List offers the better implementation.
59. What is the Set interface ?
• The Set interface provides methods for accessing the elements of a finite mathematical
set
• Sets do not allow duplicate elements
• Contains no methods other than those inherited from Collection
• It adds the restriction that duplicate elements are prohibited
• Two Set objects are equal if they contain the same elements
HashSet is under set interface i.e. it does not TreeSet is under set i.e. it provides
guarantee for either sorted order or elements in a sorted order (acceding
sequence order. order).
• A map is an object that stores associations between keys and values (key/value pairs).
• Given a key, you can find its value. Both keys and values are objects.
• The keys must be unique, but the values may be duplicated.
• Some maps can accept a null key and null values, others cannot.
• HashMap
• HashTable
• TreeMap
• EnumMap
67. What is a TreeMap?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a
TreeMap the data will be sorted in ascending order of keys according to the natural order for
the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-
Black tree data structure.
68. How do you decide when to use HashMap and when to use TreeMap?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your
better alternative. Depending upon the size of your collection, it may be faster to add
elements to a HashMap, and then convert the map to a TreeMap for sorted key traversal.
HashMap lets you have null values as well as HashTable does not allow null values as
one null key. key and value.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to
be NULL. Nevertheless, it can have multiple NULL values.
71. What are the different Collection Views That Maps Provide?
Maps Provide Three Collection Views.
75. How do you sort an ArrayList (or any list) of user-defined objects?
Create an implementation of the java.lang.Comparable interface that knows how to order your
objects and pass it to java.util.Collections.sort(List, Comparator).
All classes implementing the Comparable interface must implement the compareTo() method
that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
77. What are the differences between the Comparable and Comparator interfaces ?
Comparable Comparato
It is necessary to modify the class whose A separate class can be created in order to
instance is going to be sorted. sort the instances.
Only one sort sequence can be created. Many sort sequences can be created.
Member classes
Local classes
A local class is a class defined within a block of Java code. Like a local variable,
a local class is visible only within that block. Although local classes are not
member classes, they are still defined within an enclosing class, so they share
many of the features of member classes. Additionally, however, a local class can
access any final local variables or parameters that are accessible in the scope of
the block that defines the class. Interfaces cannot be defined locally.
Anonymous classes
An anonymous class is a kind of local class that has no name; it combines the
syntax for class definition with the syntax for object instantiation. While a local
class definition is a Java statement, an anonymous class definition (and
instantiation) is a Java expression, so it can appear as part of a larger expression,
such as method invocation. Interfaces cannot be defined anonymously.
Patterns
Creational Patterns
Factory Pattern
Abstract Factory Pattern
Singleton Pattern
Builder Pattern
Prototype Pattern
Structural Patterns
Adapter Pattern
Bridge Pattern
Composite Pattern
Decorator Pattern
Facade Pattern
Flyweight Pattern
Proxy Pattern
Behavioral Patterns
Chain of Responsibility Pattern
Command Pattern
Interpreter Pattern
Iterator Pattern
Mediator Pattern
Momento Pattern
Observer Pattern
State Pattern
Strategy Pattern
Template Pattern
Visitor Pattern
AllAppLabs.com