CORE JAVA COMPLETE LIST OF QUESTIONS
Is JVM Platform independent?
Answer is No, JVM is platform dependent.
JVM depends on the operating system – so if you are running Mac OS X you will have a different JVM than if you are running Windows or some other operating system. This fact can be verified by trying to download the JVM for your particular machine – when trying to download it, you will be given a list of JVM’s corresponding to different operating systems, and you will obviously pick whichever JVM is targeted for the operating system that you are running.
What is Inheritance in Java ?
Inheritance is a mechanism that allows a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods.
Inheritance is-a relationship between a Super class and its Sub class. extends keywords are used to describe inheritance in Java.
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Now based on above example.
In OOPs term we can say that,
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Purpose of Inheritance
è Purpose of Inheritance is :
1. To promote code reuse.
2. To use Polymorphism.
Why multiple inheritance is not supported in Java?
1. To remove ambiguity.
2. To provide more maintainable and clear design.
Which are the different segments of memory ?
1. Stack Segment - Contains Class / Interface names and references.
2. Heap Segment - Contains all created objects in runtime, objects only plus their object attributes (instance variables), Static variables are also stored in heap.
3. Code Segment - The segment where the actual compiled Java bytecodes resides when loaded
What do you mean by "Java is a statically typed language" ?
It means that the variables are checked at compile time in Java .The main advantage here is that all kinds of checking can be done by the compiler and hence will reduce bugs.
How can we run a java program without making any object?
By putting code within static method. With Java 6 and earlier versions, even static block can be used.
What are the different ways to create object in Java?
There are five different ways to create objects in java:
1. Using new keyword
2. Using Class.forName():
3. Using clone():
4. Using Object Deserialization:
5. Using newIntance() method
Using new keyword:
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object=new Object();
Using Class.forName():
If we know the name of the class & if it has a public default constructor we can create an object in this way.
Syntax:
Myobject obj=(MyObject) class.forName("object").newInstance();
Using clone():
The clone() can be used to create a copy of an existing object.
Syntax:
MyObject obj=new MyObject();
MyObject object=(MyObject )obj.clone();
Using Object Deserialization:
Object deserialization is nothing but creating an object from its serialized form.
Syntax:
objectInputStream istream=new objectInputStream(some data);
MyObject object=(MyObject) instream.readObject();
Using newInstance() method
Object obj = DemoClass.class.getClassLoader().loadClass("DemoClass").newInstance();
What is a Lambda Expression ? What's its use ?
Its an anonymous method without any declaration. Lambda Expression are useful to write shorthand Code and hence saves the effort of writing lengthy Code. It promotes Developer productivity, Better Readable and Reliable code.
What is the difference between declaration, instantiation and initialization ?
Declaration is intimation to the compiler about the nature of Data a reference is going to hold.
For example - List myList;
Instantiation is reservation of memory.
For example
myList = new ArrayList();
Initialization or construction is setting the default values for member elements.
For example
myList = new ArrayList(mySet);
** Example 2nd is both for instantiation as well as initialization. The only difference is that 2nd will initialized the member elements to their default values whereas 3rd will initialized it with the elements from set.
Describe what happens when an object is created in Java ?
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
What is Polymorphism in Java?
Polymorphism is the ability to create a reference variables, a function, or an object that has more than one form.”
An example of polymorphism is referring the instance of subclass, with reference variable of super-class. e.g.
Object o = new Object(); //o can hold the reference of any subtype
Object o = new String();
Object o = new Integer();
Here, String is subclass of Object class. This is basic example of polymorphism.
In java language, polymorphism is essentially considered into two versions.
1. Compile time polymorphism (static binding or method overloading)
2. Runtime polymorphism (dynamic binding or method overriding)
è Compile time polymorphism (static binding or method overloading)
In method overloading, an object can have two or more methods with same name, BUT, with their method parameters different. These parameters may be different on two bases:
1) Parameter type: Type of method parameters can be different. e.g. java.util.Math.max() function comes with following versions:
public static double Math.max(double a, double b){..}
public static float Math.max(float a, float b){..}
public static int Math.max(int a, int b){..}
public static long Math.max(long a, long b){..}
The actual method to be called is decided on compile time based on parameters passed to function in program.
2) Parameter count: Functions accepting different number of parameters. e.g. in employee management application, a factory can have these methods:
EmployeeFactory.create(String firstName, String lastName){...}
EmployeeFactory.create(Integer id, String firstName, String lastName){...}
Both methods have same name “create” but actual method invoked will be based on parameters passed in program.
è Runtime polymorphism (dynamic binding or method overriding)
Runtime polymorphism is essentially referred as method overriding. Method overriding is a feature which you get when you implement inheritance in your program. Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding.
A simple example can be from real world e.g. Animal. An application can have Animal class, and its specialized sub classes like Cat and Dog. These subclasses will override the default behavior provided by Animal class + some of its own specific behavior.
public class Animal {
public void makeNoise()
{
System.out.println("Some sound");
}
}
class Dog extends Animal{
public void makeNoise()
{
System.out.println("Bark");
}
}
class Cat extends Animal{
public void makeNoise()
{
System.out.println("Meawoo");
}
}
Now which makeNoise() method will be called, depends on type of actual instance created on runtime e.g.
public class Demo
{
public static void main(String[] args) {
Animal a1 = new Cat();
a1.makeNoise(); //Prints Meowoo
Animal a2 = new Dog();
a2.makeNoise(); //Prints Bark
}
}
Rules for Method Overloading
1. Overloading can take place in the same class or in its sub-class.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be the part of the same class (can also take place in sub class), with same name but different parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.
Rules for Method Overriding:
1. Applies only to inherited methods
2. object type (NOT reference variable type) determines which overridden method will be used at runtime
3. Overriding method can have different return type (refer this)
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.
Usages and Advantages of Polymorphism
• Method overloading allows methods that perform similar or closely related functions to be accessed through a common name. For example, a program performs operations on an array of numbers which can be int, float, or double type. Method overloading allows you to define three methods with the same name and different types of parameters to handle the array operations.
• Method overloading can be implemented on constructors allowing different ways to initialize objects of a class. This enables you to define multiple constructors for handling different types of initializations.
• Method overriding allows a sub class to use all the general definitions that a super class provides and add specialized definitions through overridden methods.
• Method overriding works together with inheritance to enable code reuse of existing classes without the need for re-compilation.
What is Inheritance in Java ?
Inheritance is a mechanism that allows a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods.
Inheritance is-a relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java.
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Purpose of Inheritance
Advantages:-
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of code and smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass
Reusability -- facility to use public methods of base class without rewriting the same
Extensibility -- extending the base class logic as per business logic of the derived class
Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class
Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.
Disadvantages:-
1. One of the main disadvantages of inheritance in Java (the same in other object-oriented languages) is the increased time/effort it takes the program to jump through all the levels of overloaded classes. If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to run through a function defined in each of those classes
2. 2.Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled.
3. This means one cannot be used independent of each other.
4. Also with time, during maintenance adding new features both base as well as derived classes are required to be changed. If a method signature is changed then we will be affected in both cases (inheritance & composition)
5. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that method.Here things can get a bit complicated in case of inheritance because our programs will still compile, but the methods of the subclass will no longer be overriding superclass methods. These methods will become independent methods in their own right.
Is Constructor Inherited
In simple words, a constructor cannot be inherited, since in sub classes it has a different name (the name of the subclass).
class A {
A();
}
class B extends A{
B();
}
You can do only:
B b = new B(); // and not new A()
Methods, instead, are inherited with "the same name" and can be used.
As for the reason: It would not have much sense to inherit a constructor, since constructor of class A means creating an object of type A, and constructor of class B means creating an object of class B.
You can still use constructors from A inside B's implementation though:
class B extends A{
B() { super(); }
}
Difference between null and empty (“”) Java String
String s1 = ""; means that the empty String is assigned to s1. In this case, s1.length() is the same as "".length(), which will yield 0 as expected.
String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Instance Variable Inheritance
It might occur to you to wonder what happens with instance variables. If the superclass has some instance variables, do the child classes also have access to these variables?
This depends on whether you define the instance variables in the parent class using the public, private or protected access specifiers, or with none at all.
As long as instance variables are not private, they can be accessed by subclasses.
Let's see an example. Here I've placed all relevant code in one file to make it easier to read.
class Fruit {
String name;
Fruit() {
name = "Fruit";
}
public String getName() {
return name;
}
}
class Banana extends Fruit {
Banana() {
name = "Banana";
}
}
public class Application {
public static void main(String[] args) {
Fruit fruit = new Fruit();
Banana banana = new Banana();
System.out.println(fruit.getName());
System.out.println(banana.getName());
}
}
The constructors of both classes set the name instance variable. The Banana class extends the Fruit class (i.e. inherits from it); its constructor also has access to the name instance variable, which it sets. Then when name is retrieved from either class using the getName() method, an appropriate name is returned and displayed.
Output:
Fruit
Banana
Abstraction:
Abstraction captures only those details about an object that are relevant to the current perspective.
In simple words i can say: "Abstraction implies providing something, but not everything".
abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need to type the content, mention the address of the receiver, and click send.
Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.
Rules:-
· Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
· But, if a class has at least one abstract method, then the class must be declared abstract.
· If a class is declared abstract, it cannot be instantiated.
· To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
· If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Example for the above illustration:
Let us consider an interface (you can take abstract class also) Addicted.
public interface Addicted {
public String[] getAddictedListOfPersons();
}
In the above interface, getAddictedListOfPersons() is the abstract method (by default all the methods in an interface are public abstract ) which returns list of all the addicted persons. By looking at the method declaration we can infer this.
But we don't know how exactly the method will be implemented in it's (interface) implementation classes.
Following are the implementation classes for the interface Addicted.
public class AddictedToJava implements Addicted{
@Override
public String[] getAddictedListOfPersons() {
// here we will provide implementation (getting list of persons who were addicted to Java)
return null;
}
}
The class AddictedToJava is providing implementation to the abstract method which returns the list of persons who were addicted to Java.
public class AddictedToAndroid implements Addicted {
@Override
public String[] getAddictedListOfPersons() {
// here we will provide implementation (getting list of persons who were addicted to Android)
return null;
}
}
The class AddictedToAndroid is providing implementation to the abstract method which returns the list of persons who were addicted to Android.
Now , by looking at these implementations we came to know that the implementation is different in both of the implementation classes for the interface(Addicted).
Only after providing implementation, we came to know how exactly the method was implemented.
Encapsulation is a practice to bind related functionality (Methods) & Data (Variables) in a protective wrapper (Class) with required access modifiers (public, private, default & protected) so that the code can be saved from unauthorized access by outer world and can be made easy to maintain.
We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters. Although a lesser degree of encapsulation can be achieved by making the members public or protected.
As we know a private access specifier specifies access with in the class (local access), the data can't be exposed to the other classes (in same application or different application).
Let me elaborate this with an example.
CapsulateData is the class with some variables as given below.
public class CapsulateData {
public String branchName;
private long accountNumber;
private String accountName;
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public long getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(long accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
As accountNumber, accountName are private variables they can't be accessed outside the class.
If we try to do so, following will be the result.
Abstraction is more about ‘What‘ a class can do. [Idea]
– Encapsulation is more about ‘How‘ to achieve that functionality. [Implementation]
– Encapsulation is more about ‘How‘ to achieve that functionality. [Implementation]
Relation between Abstraction and Encapsulation?
I will take example of our well known class HashMap. This class is responsible for storing key-value pair, searching based on key and do more things. From outside, client code only knows the method names and their behavior. It calls these methods and live happily. This is actually what abstraction guidelines are.
Abstraction says that client code should call a method to add key-value pair, a method to retrieve value based on key and so on. How it should be done? is not business of abstraction.
And here comes encapsulation, when you start writing actual code. You write HashMap.Entry class and create variable table of type Entry[]. Then you declare all such things private and give public access to only put() and get() methods etc. This is actually encapsulation.
Abstraction : Things to Remember
1) Use abstraction if you know something needs to be in class but the implementation of that varies. Abstraction is actually resulting of thought process and it really need good experience of both domain and Object oriented analysis and design to come up with good abstraction for your project.
2) In Java, you cannot create an instance of the abstract class using the new operator, its compiler error. Though abstract class can have a constructor.
3) abstract is a keyword in Java, which can be used with both class and method. Abstract class can contain both abstract and concrete method. An abstract method doesn't have the body, just declaration.
4) A class automatically becomes abstract class when any of its methods declared as abstract.
5) abstract method doesn't have method body.
6) In Java, a variable cannot be made abstract , its only class or methods which would be abstract.
7) If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. Alternatively, this class can also be abstract.
Difference between Abstraction and Encapsulation:
1) First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.
2) Encapsulation is also called data hiding.
What are the difference between composition and inheritance in Java?
Ans. Composition - has-a relationship between classes.
Inheritance - is-a relationship between classes.
Composition - Composing object holds a reference to composing classes and hence relationship is loosely bound.
Inheritance - Derived object carries the base class definition in itself and hence its tightly bound.
Composition - Used in Dependency Injection
Inheritance - Used in Runtime Polymorphism
Composition - Single class objects can be composed within multiple classes.
Inheritance - Single class can only inherit 1 Class.
Composition - It’s the relationship between objects.
Inheritance - It’s the relationship between classes.
Explain the scenerios to choose between String , StringBuilder and StringBuffer ?
If the Object value will not change, use String Class because a String object is immutable.
If the Object value can change and will only be modified from a single thread, use StringBuilder because StringBuilder is unsynchronized(means faster).
If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).
Does garbage collection guarantee that a program will not run out of memory?
Ans. Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
If you are given a choice to use either ArrayList and LinkedList, Which one would you use and Why ?
Ans. ArrayList are implemented in memory as arrays and hence allows fast retrieval through indices but are costly if new elements are to be inserted in between other elements. LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements
1. Retrieval - If Elements are to be retrieved sequentially only, Linked List is preferred.
2. Insertion - If new Elements are to be inserted in between other elements, Array List is preferred.
3. Search - Binary Search and other optimized way of searching is not possible on Linked List.
4. Sorting - Initial sorting could be pain but lateral addition of elements in a sorted list is good with linked list.
5. Adding Elements - If sufficiently large elements need to be added very frequently, Linked List is preferable as elements don't need consecutive memory location.
Why do we need Inner classes ? Can't we just work with outer classes wherever we implement Inner classes ?
Ans. Yes, we can substitute outer classes wherever we need to have inner classes but Inner classes have advantage in certain cases and hence preferred -
Ease - Why to implement a class outside if its objects are only intended to be part of an outer object. Its easy to define the class within another class if the use is only local.
Protection - Making a call an outer exposes a threat of it being used by any of the class. Why should it be made an outer class if its object should only occur as part of other objects.
For example - You may like to have an class address whose object should have a reference to city and by design that's the only use of city you have in your application. Making Address and City as outer class exposes City to any of the Class. Making it an inner class of Address will make sure that its accessed using object of Address.
What are the common uses of "this" keyword in java ?
Ans. "this" keyword is a reference to the current object and can be used for following -
1. Passing itself to another method.
2. Referring to the instance variable when local variable has the same name.
3. Calling another constructor in constructor chaining.
Difference between TreeMap and HashMap ?
Ans. They are different the way their elements are stored in memory. Tree Map stores the Keys in order whereas Hash Map stores the key value pairs randomly.
What is the difference between ArrayList and LinkedList ?
Ans. Underlying data structure for ArrayList is Array whereas LinkedList is the linked list and hence have following differences -
1. ArrayList needs continuous memory locations and hence need to be moved to a bigger space if new elements are to be added to a filled array which is not required for LinkedList.
2. Removal and Insertion at specific place in ArrayList requires moving all elements and hence leads to O(n) insertions and removal whereas its constant O(1) for LinkedList.
3. Random access using index in ArrayList is faster than LinkedList which requires traversing the complete list through references.
4. Though Linear Search takes Similar Time for both, Binary Search using LinkedList requires creating new Model called Binary Search Tree which is slower but offers constant time insertion and deletion.
5. For a set of integers you want to sort using quicksort, it's probably faster to use an array; for a set of large structures you want to sort using selection sort, a linked list will be faster.
Can you give a real world example of Encapsulation and Abstraction ?
Ans. Car Engine is an example of encapsulation and abstraction. You ignite the car using an interface called starter and least bothered about how the tire actually moves (This is abstraction). The engine encapsulates the complete process to itself only and doesn't allow you to start the other components like the radiator etc ( this is excapsulation )
Describe, in general, how java's garbage collector works ?
Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.
What are various types of Class loaders used by JVM ?
Ans. Bootstrap - Loads JDK internal classes, java.* packages.
Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE
System - Loads classes from system classpath.
Difference Between this() and super() ?
Ans. 1. this is a reference to the current object in which this keyword is used whereas super is a reference used to access members specific to the parent Class.
2. this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.
What is a Final Variable ?
Ans. Final variable is a variable constant that cannot be changed after initialization.
What is a final method ?
Ans. Its a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class.
What is an API ( Application Programming Interface ) ?
Ans. An API is a kind of technical contract which defines functionality that two parties must provide: a service provider (often called an implementation) and an application. an API simply defines services that a service provider (i.e., the implementation) makes available to applications.
What is URL?
Ans. URL is Uniform Resource Locator which is representation of HTTP address.
What is HTTP ?
Ans. HTTP or Hypertext Transfer Protocol is internet protocol for transmission of hypertext ( text with meta data ) over internet.
Can I import same package/class twice? Will the JVM load the package twice at runtime?
Ans. One can import the same package or same class multiple times. Neither compiler nor JVM complains wil complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.
Which access specifier can be used with Class ?
Ans. For top level class we can only use "public" and "default". We can use private with inner class.
Difference between Abstract and Concrete Class ?
Ans. Abstract classes are only meant to be sub classed and not meant to be instantiated whereas concrete classes are meant to be instantiated.
What is Volatile keyword used for ?
Ans. Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldn’t be cached.
What is the use of Transient Keyword ?
Ans. It in Java is used to indicate that a field should not be serialized.
Does Declaring an object "final" makes it immutable ?
Ans. Only declaring primitive types as final makes them immutable. Making objects final means that the object handler cannot be used to target some other object but the object is still mutable.
Can we reduce the visibility of the inherited or overridden method ?
Ans. No.
Which of the following is tightly bound ? Inheritance or Composition ?
Ans. Inheritance.
How can we make sure that a code segment gets executed even in case of uncatched exceptions ?
Ans. By putting it within finally.
Difference between boolean and Boolean ?
Ans. boolean is a primitive type whereas Boolean is a class.
What is an Enum type ?
Ans. An enum type is a special data type that enables for a variable to be a set of predefined constants.
What is "Import" used for ?
Ans. Enables the programmer to abbreviate the names of classes defined in a package.
Can we declare interface methods as private ?
Ans. No.
Why do member variables have default values whereas local variables don't have any default value ?
Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.
Difference between static vs. dynamic class loading?
Ans. static loading - Classes are statically loaded with Java new operator.
dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
Class.forName (Test className);
What are the disadvantages of using arrays ?
Ans. Arrays are of fixed size and have to reserve memory prior to use. Hence if we don't know size in advance arrays are not recommended to use.
Arrays can store only homogeneous elements.
Arrays store its values in contentious memory location. Not suitable if the content is too large and needs to be distributed in memory.
There is no underlying data structure for arrays and no readymade method support for arrays, for every requirement we need to code explicitly.
What are the Disadvantages of using Collection Classes over Arrays ?
Ans. Collections can only hold objects, It can't hold primitive data types.
Collections have performance overheads as they deal with objects and offer dynamic memory expansion. This dynamic expansion could be a bigger overhead if the collection class needs consecutive memory location like Vectors.
Collections doesn't allow modification while traversal as it may lead to concurrentModificationException.
Is it possible to compile and run a Java program without writing main( ) method?
Ans. Yes, it is possible by using a static block in the Java program.
Can we call the garbage collector explicitly ?
Ans. Yes, We can call garbage collector of JVM to delete any unused variables and unreferenced objects from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes of java.lang package.
Why are Getter and Setter better than directly changing and retrieving fields ?
Ans. 1. Methods can participate in runtime polymorphism whereas member variables cannot.
2. Validations can be performed before setting the variables.
3. If the input format changes , that can be absorbed by making change ( wrapping ) in the setter and getter.
What are the considerations to be made in case of loops in Java ?
Ans. 1. It shouldn't result in infinite loop. Please make sure that you have a condition that will terminate the loop and that condition should be reached.
2. Make sure to use the break statement if you aspire to only look for something. Not using break will unnecessarily execute it till the end of for loop in some cases.
3. Similarly use continue to execute the loop with next iteration and bypass the rest of the code block if required.
4. Try to avoid multiple nesting of for loops. If it''s required, Make sure to use break and continue properly so as to avoid some unnecessary processing.
5. Make sure to use try catch within the loop and not outside the for loop if you expect it to continue if one of the iteration fails.
Why do we write public static void main ? Can we use some other syntax too for main ?
Ans. 1. public is the access modifier that makes the method accessible from anywhere, static is the keyword that makes it accessible even without creating any object and using class name only , void means it doesn't return anything , String args[] is the array of argument that this method receives.
2. If I use Main , it will compile correctly as Java will treat it as just another method but it won't be the method "main" which Java looks for when it looks to execute the class and hence will throw
Error: Main method not found in class , please define the main method as:
public static void main(String[] args)
3. Main is not a keyword but a special string that Java looks for while initiating the main thread.
Why Java is not considered pure OOP's language ?
Ans. There are 2 reasons for it.
1. Usage of Primitive types - Though Java provides classes for the primitive data types but as the usage of primitives is permissible, its considered unpure OOP's language.
2. Usage of Static members - Static members belong to the class and not objects and hence not considered fit for pure OOP's programming.
What is a package and what are its advantages ?
Ans. Package is a namespace that organizes a set of related classes.
Advantages of Packages
1. Better Organization of classes.
2. Saves from the problem of duplicate names as duplicate class names are allowed across different packages.
What is a cookie ?
Ans. A cookie is a small piece of text stored on a user's computer by the browser for a specific domain. Commonly used for authentication, storing site preferences, and server session identification.
Can we reduce the visibility of the overridden method ?
Ans. No
What is the difference between List, Set and Map ?
Ans. List - Members are stored in sequence in memory and can be accessed through index.
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates.
Map - Contains Key , Value pairs.
Difference between Public, Private, Default and Protected ?
Ans. Private - Not accessible outside object scope.
Public - Accessible from anywhere.
Default - Accessible from anywhere within same package.
Protected - Accessible from object and the sub class objects.
Does Constructor creates the object ?
Ans. New operator in Java creates objects. Constructor is the later step in object creation. Constructor's job is to initialize the members after the object has reserved memory for itself.
Can static method access instance variables ?
Ans. Though Static methods cannot access the instance variables directly, They can access them using instance handler.
Difference between Checked and Unchecked exceptions ?
Ans. Checked exceptions and the exceptions for which compiler throws an errors if they are not checked whereas unchecked exceptions and caught during run time only and hence can't be checked.
Which interface does java.util.Hashtable implement?
Ans. Java.util.Map
Which interface provides the capability to store objects using a key-value pair?
Ans. java.util.map
Does java allow overriding static methods ?
Ans. No. Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.
Difference between long.Class and Long.TYPE ?
Ans. They both represent the long primitive type. They are exactly the same
Does Java provides default copy constructor ?
Ans. No
What is the use of hashcode in Java ?
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.
What is the use of cookie and session ? and What is the difference between them ?
Ans. Cookie and Session are used to store the user information. Cookie stores user information on client side and Session does it on server side. Primarily, Cookies and Session are used for authentication, user preferences, and carrying information across multiple requests. Session is meant for the same purpose as the cookie does. Session does it on server side and Cookie does it on client side. One more thing that quite differentiates between Cookie and Session. Cookie is used only for storing the textual information. Session can be used to store both textual information and objects.
How does a try statement determine which catch clause should be used to handle an exception?
Ans. When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
Are constructors inherited? Can a subclass call the parent's class constructor? When?
Ans. You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to override the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.
Explain use of nested or inner classes ?
Ans. Sometime we just need classes or class objects just to be used as part of a particular class or objects. Making them non nested won't make any difference as far as functionality is concerner but making them Nested provide a level of convenience and protection fro, being used anywhere else. Moreover it helps reducing the Code.
Explain Annotations ?
Ans. Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
Give an Example of checked and unchecked exception ?
Ans. ClassNotFoundException is checked exception whereas NoClassDefFoundError is a unchecked exception
Eplain the use of "Native" keyword ?
Ans. Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language
What are Marker Interfaces ? Name few Java marker interfaces ?
Ans. These are the interfaces which have no declared methods. Serializable and cloneable are marker interfaces.
What is a Static import ?
Ans. By static import , we can access the static members of a class directly without prefixing it with the class name.
Difference between loadClass and Class.forName ?
Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.
Which kind of memory is used for storing object member variables and function local variables ?
Ans. Local variables are stored in stack whereas object variables are stored in heap.
What is a Default Constructor ?
Ans. The no argument constructor provided by Java Compiler if no constructor is specified.
Will Compiler creates a default no argument constructor if we specify only multi argument constructor ?
Ans. No, Compiler will create default constructor only if we don't specify any constructor.
Can we overload constructors ?
Ans. Yes.
What will happen if we make the constructor private ?
Ans. We can't create the objects directly by invoking new operator.
How can we create objects if we make the constructor private ?
Ans. We can do so through a static public member method or static block.
Why Java don't use pointers ?
Ans. Pointers are vulnerable and slight carelessness in their use may result in memory problems and hence Java intrinsically manage their use.
Do we need to import java.lang.package ?
Ans. No, It is loaded by default by the JVM.
Is it necessary that each try block to be followed by catch block ?
Ans. It should be followed by either catch or finally block.
Can finally block be used without catch ?
Ans. Yes but should follow "try" block then.
Difference between nested and inner classes ?
Ans. Inner classes are non static nested classes.
What is a nested interface ?
Ans. Any interface declared inside a class or an interface. It is static by default.
What is reflection ?
Ans. It is the process of examining / modifying the runtime behaviour of an object at runtime.
Can we instantiate the object of derived class if parent constructor is protected ?
Ans. No
Can we declare an abstract method private ?
Ans. No Abstract methods can only be declared protected or public.
What is the difference between System.console.write and System.out.println ?
Ans. System.console() returns null if your application is not run in a terminal (though you can handle this in your application)System.console() provides methods for reading password without echoing charactersSystem.out and System.err use the default platform encoding, while the Console class output methods use the console encoding
What is the benefit of inner / nested classes ?
Ans. You can put related classes together as a single logical group.
Nested classes can access all class members of the enclosing class, which might be useful in certain cases.
Nested classes are sometimes useful for specific purposes. For example, anonymous inner classes are useful for writing simpler event-handling code with AWT/Swing.
Explain Static nested Classes ?
Ans. The accessibility (public, protected, etc.) of the static nested class is defined by the outer class.
A static nested class is not an inner class, it's a top-level nested class.
The name of the static nested class is expressed with OuterClassName.NestedClassName syntax.
When you define an inner nested class (or interface) inside an interface, the nested class is declared implicitly public and static.
Static nested classes can be declared abstract or final.
Static nested classes can extend another class or it can be used as a base class.
Static nested classes can have static members.
Static nested classes can access the members of the outer class (only static members, obviously).
The outer class can also access the members (even private members) of the nested class through an object of nested class. If you don’t declare an instance of the nested class, the outer class cannot access nested class elements directly.
What will happen if class implement two interface having common method?
Ans. That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.
Can we create an object if a Class doesn't have any constructor ( not even the default provided by constructor ) ?
Ans. Yes , using Class.getInstance.
Can we call constructor explicitly ?
Ans. Yes.
What is the difference between float and double?
Ans. Float can represent up to 7 digits accurately after decimal point, where as double can represent up to 15 digits accurately after decimal point.
What is the difference between >> and >>>?
Ans. Both bitwise right shift operator ( >> ) and bitwise zero fill right shift operator ( >>> ) are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bit.
Why is Java considered Portable Language ?
Ans. Java is a portable-language because without any modification we can use Java byte-code in any platform(which supports Java). So this byte-code is portable and we can use in any other major platforms.
How to find if JVM is 32 or 64 bit from Java program. ?
Ans. You can find JVM - 32 bit or 64 bit by using System.getProperty() from Java program.
Does every class needs to have one non parameterized constructor ?
Ans. No. Every Class only needs to have one constructor - With parameters or without parameters. Compiler provides a default non parameterized constructor if no constructors is defined.
Can we use "this" within static method ? Why ?
Ans. No. Even though "this" would mean a reference to current object id the method gets called using object reference but "this" would mean an ambiguity if the same static method gets called using Class name.
What are the platforms supported by Java Programming Language?
Ans. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc
How Java provide high Performance ?
Ans. Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor.
What is a Class ?
Ans. A class is a blue print or Mold using which individual objects are created. A class can contain fields and methods to describe the behavior of an object.
What is an Object ?
Ans. Object is a run time entity whose state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
What is the difference between a break statement and a continue statement?
Ans. Break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
Can try statements be nested?
Ans. Yes
What environment variables do I need to set on my machine in order to be able to run Java programs?
Ans. CLASSPATH and PATH are the two variables.
What is constructor chaining and how is it achieved in Java?
Ans. A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement
Why Java provides default constructor ?
Ans. At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.
In a case where there are no instance variables what does the default constructor initialize?
Ans. Java expects the superclass ( Object Class ) constructor to be called while creation of any object. So super constructor is called in case there are no instance variables to initialize.
Why String is popular HashMap key in Java?
Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesnt need to be calculated again. This makes it a great candidate for key in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
Will finally be called always if all code has been kept in try block ?
Ans. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.
Difference between Static and Singleton Class ?
Ans. 1. Static class is a class which cannot be instantiated and all its members are static whereas Singleton is the class that only permit creation of single object and then the object is reused.
2. As there is no object in Static class, it cannot participate in runtime Polymorphism.
3. As Static class doesnt allow creating objects and hence it cannot be serialized.
4. Static class body is initialized eagerly at application load time whereas Singleton object can be initiated eagerly using static blocks or lazily on first need.
5. Its not recommended to use pure static class as it fails to use many OOPs concepts.
Difference between new operator and Class.forName().newInstance() ?
Ans. new operator is used to statically create an instance of object. newInstance() is used to create an object dynamically ( like if the class name needs to be picked from configuration file ). If you know what class needs to be initialized , new is the optimized way of instantiating Class.
What is Java bytecode ?
Ans. Java bytecode is the instruction set of the Java virtual machine. Each bytecode is composed by one, or two bytes that represent the instruction, along with zero or more bytes for passing parameters.
Difference between PATH and CLASSPATH ?
Ans. PATH is the variable that holds the directories for the OS to look for executables. CLASSPATH is the variable that holds the directories for JVM to look for .class files ( Byte Code ).
Name few access and non access Class Modifiers ?
Ans. private , public and protected are access modifiers.
final and abstract are non access modifiers.
Which Java collection class can be used to maintain the entries in the order in which they were last accessed?
Ans. LinkedHashMap
Can we add duplicate keys in a HashMap ? What will happen if we attempt to add duplicate values ?
Ans. No, We cannot have duplicate keys in HashMap. If we attempt to do so , the previous value for the key is overwritten.
What are different types of cookies ?
Ans. Session cookies , which are deleted once the session is over.
Permanent cookies , which stays at client PC even if the session is disconnected.
Can finally block throw an exception ?
Ans. Yes.
Which are the sorted collections ?
Ans. TreeSet and TreeMap
What is the difference between Collection and Collections ?
Ans. Collection is an interface whereas Collections is a utility class.
How TreeMap orders the elements if the Key is a String ?
Ans. As String implements Comparable, It refers to the String compareTo method to identify the order relationship among those elements.
Explain What is System, out, println in System.out.println() in Java?
System is a final class from the java.lang package.
out is a class variable of type PrintStream declared in the System class.
println is a method of the PrintStream class.
-------------------------------------------------------------------------------------------------------------------------
ahese exception that might be thrown from the program. Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.
Exception is the super class of all checked exceptions.
RuntimeException is the super class of all unchecked exceptions.
Checked exceptions are error scenarios that are not caused by program, for example FileNotFoundException in reading a file that is not present,
Unchecked exceptions are mostly caused by poor programming, for example NullPointerException when invoking a method on an object reference without making sure that it’s not null.
What is difference between throw and throws keyword in Java?
throws keyword is used with method signature to declare the exceptions that the method might throw
throw keyword is used to disrupt the flow of program and handing over the exception object to runtime to handle it.
What is OutOfMemoryError in Java?
OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run the java application through java options.
What are different scenarios causing “Exception in thread main”?
Some of the common main thread exception scenarios are:
Exception in thread main java.lang.UnsupportedClassVersionError: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.
Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.
Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn’t have main method.
Exception in thread “main” java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.
What is difference between final, finally and finalize in Java?
final and finally are keywords in java whereas finalize is a method.
final keyword can be used with class variables so that they can’t be reassigned, with class to avoid extending by classes and with methods to avoid overriding by subclasses.
finally keyword is used with try-catch block to provide statements that will always gets executed even if some exception arises, usually finally is used to close resources.
finalize() method is executed by Garbage Collector before the object is destroyed, it’s great way to make sure all the global resources are closed.
Out of the three, only finally is related to java exception handling.
What happens when exception is thrown by main method?
When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.
Can we have an empty catch block?
We can have an empty catch block but it’s the example of worst programming. We should never have empty catch block because if the exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.
What is difference between Error and Exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)
What is difference between ClassNotFoundException and NoClassDefFoundError?
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.
Can we write only try block without catch and finally blocks?
No, It shows compilation error. The try block must be followed by either catch or finally block. You can remove either catch block or finally block but not both.
There are three statements in a try block – statement1, statement2 and statement3. After that there is a catch block to catch the exceptions occurred in the try block. Assume that exception has occurred in statement2. Does statement3 get executed or not?
No. Once a try block throws an exception, remaining statements will not be executed. control comes directly to catch block.
What is unreachable catch block error?
When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e sub classes of Exception must come first and super classes later. If you keep super classes first and sub classes later, compiler will show unreachable catch block error.
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
}
catch(Exception ex)
{
System.out.println("This block handles all exception types");
}
catch(NumberFormatException ex)
{
//Compile time error
//This block becomes unreachable as
//exception is already caught by above catch block
}
}
}
Does finally block get executed If either try or catch blocks are returning the control?
Yes, finally block will be always executed no matter whether try or catch blocks are returning the control or not.
Can we throw an exception manually?
Yes, we can throw an exception manually using throw keyword. Syntax for throwing an exception manually is
throw InstanceOfThrowableType;
Below example shows how to use throw keyword to throw an exception manually.
try
{
NumberFormatException ex = new NumberFormatException(); //Creating an object to NumberFormatException explicitly
throw ex; //throwing NumberFormatException object explicitly using throw keyword
}
catch(NumberFormatException ex)
{
System.out.println("explicitly thrown NumberFormatException object will be caught here");
}
What is Re-throwing an exception in java?
Exceptions raised in the try block are handled in the catch block. If it is unable to handle that exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.
try
{
String s = null;
System.out.println(s.length()); //This statement throws NullPointerException
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException is caught here");
throw ex; //Re-throwing NullPointerException
}
Which class is the super class for all types of errors and exceptions in java?
java.lang.Throwable is the super class for all types of errors and exceptions in java.
What is the use of printStackTrace() method?
printStackTrace() method is used to print the detailed information about the exception occurred.
Give some examples to checked exceptions?
ClassNotFoundException, SQLException, IOException
Give some examples to unchecked exceptions?
NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException
What are chained exception?
In an application, one exception throws many exceptions. i.e one exception causes another exception and that exception causes another exception thus forming chain of exceptions. It is better to know where the actual cause of the exception lies. This is possible with chained exceptions feature of the Java.
Chained exceptions are introduced from JDK 1.4. To implement chained exceptions in java, two new constructors and two new methods are added in the Throwable class. They are,
Constructors Of Throwable class Which support chained exceptions in java :
1) Throwable(Throwable cause) —> where cause is the exception that causes the current exception.
2) Throwable(String msg, Throwable cause) —> where msg is the exception message and cause is the exception that causes the current exception.
What is StackOverflowError?
StackOverflowError error is thrown by JVM when it encounters that there is no memory left in the stack to store variables . Parameters and local variables are allocated on the stack . The common cause for a stack overflow is a bad recursive call. Typically this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself for ever.
What does 'Ducking' the exception mean?
If a method does not handle the exception but simply declares it using throws , the method is said to be ducking the exception.
What is the concept of multi-catch block ?
In multi-catch block , we can catch multiple exceptions in a single catch block.
Benefits : This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Example :
Without multi catch
catch (IOException ex){
logger.log(ex);
throw ex;
}
catch (SQLException ex){
logger.log(ex);
throw ex;
}
With multi catch
catch(SQLException | SQLException ex)
{
logger.log(ex);
throw ex;
}
Can we have the try block without catch or finally block?
NO . try block must have a catch or finally associated with it.
In case, there is a return at the end of try block, will execute finally block?
Yes, the finally block will be executed even after writing return statement at the end of try block.
It returns after executing finally block.
What is the difference between exception and error?
An error is an irrecoverable condition occurring at runtime like out of memory error. These kind of jvm errors cannot be handled at runtime.
Exceptions are because of condition failures, which can be handled easily at runtime.
Can we define a class without main method?
No, you can’t run java class without main method.
Before Java 7, you can run java class by using static initializers. But, from Java 7 it is not possible.
Can main() method take an argument other than string array?
No, argument of main() method must be string array.
But, from the introduction of var args you can pass var args of string type as an argument to main() method. Again, var args are nothing but the arrays.
package com.instanceofjava;
public class MainMethod
{
public static void main(String args[])
{
}
}
Can we change return type of main() method?
No, the return type of main() method must be void only. Any other type is not acceptable.
package com.instanceofjava;
public class A
{
public static int main(String[] args)
{
return 1; //run time error : No main method found
}
}
Why main() method must be static?
main() method must be static.
If main() is allowed to be non-static, then while calling the main method JVM has to instantiate it’s class.
While instantiating it has to call constructor of that class. There will be an ambiguity if constructor of that class takes an argument.
For example, In the below program what argument JVM has to pass while instantiating class “A”?.
package com.instanceofjava;
public class A
{
public A(int i)
{
//Constructor taking one argument
}
public void main(String[] args)
{
//main method as non-static
}
Can We Declare main() Method As Non-Static?
No, main() method must be declared as static so that JVM can call main() method without instantiating it’s class.
If you remove ‘static’ from main() method signature, compilation will be successful but program fails at run time.
package com.instanceofjava;
public class A
{
public void main(String[] args)
{
System.out.println("indhu"); //Run time error
}
}
Can We Overload main() method?
Yes, We can overload main() method. A Java class can have any number of main() methods. But to run the java class, class should have main()
method with signature as “public static void main(String[] args)”. If you do any modification to this signature, compilation will be successful.
But, you can’t run the java program. You will get run time error as main method not found.
package com.instanceofjava;
public class A
{
public static void main(String[] args)
{
System.out.println("Indhu");
}
void main(int args)
{
System.out.println("Sindhu");
}
long main(int i, long d)
{
System.out.println("Saidesh");
return d;
}
}
Can we declare main() method as private or protected or with no access modifier?
No, main() method must be public. You can’t define main() method as private or protected or with no access modifier.
This is because to make the main() method accessible to JVM. If you define main() method other than public, compilation will be successful but you will get run time error as no main method found.
package com.instanceofjava;
public class A
{
private static void main(String[] args)
{
//Run time error
}
}
Can we override main in Java ?
No you cannot override main method in Java, Why because main is static method and in Java static method is bonded during compile time and you cannot override static method in Java.
Can we make main final in Java?
You can make main method final in Java. JVM has no issue with that. Unlike any final method you can not override main in Java.
Can we make main synchronized in Java?
Yes, main can be synchronized in Java, synchronized modifier is allowed in main signature and you can make your main method synchronized in Java.
What is the use of final keyword in java?
By using final keyword we can make
Final class
Final method
Final variables
If we declare any class as final we can not extend that class
If we declare any method as final it can not be overridden in sub class
If we declare any variable as final its value unchangeable once assigned.
What is the main difference between abstract method and final method?
Abstract methods must be overridden in sub class whereas final methods cannot be overridden in sub class
What is the actual use of final class in java?
If a class needs some security and it should not participate in inheritance in this scenario we need to use final class.
We cannot extend final class.
What will happen if we try to extend final class in java?
Compile time error will come.
package com.finalkeywordintweviewprograms;
public final Class SuperDemo{
int a,b;
public void show() {
System.out.println(a);
System.out.println(b);
}
}
package com.finalkeywordintweviewprograms;
public Class Sample extends SuperDemo{ //The type Sample cannot subclass the final class
SuperDemo
}
Can we declare interface as final?
No We can not declare interface as final because interface should be implemented by some class so its not possible to declare interface as final.
Is it possible to declare final variables without initialization?
No. Its not possible to declare a final variable without initial value assigned.
While declaring itself we need to initialize some value and that value cannot be change at any time.
package com.finalkeywordintweviewprograms;
public final Class Sample{
final int x=12,y=13;
public void Method() {
x=25;// compile time error:The final field Super.x cannot be assigned
y=33;// compile time error: The final field Super.y cannot be assigned
}
}
Can we declare constructor as final?
No . Constructors can not be final.
What will happen if we try to override final methods in sub classes?
Compile time error will come :Cannot override the final method from Super class
Can we create object for final class?
Yes we can create object for final class.
What is the most common predefined final class object you used in your code?
String
What is Super in Java?
The functionality of super keyword is only to point the immediate super class object of the current object.
super keyword is applicable only in the non static methods and super keyword not applicable in the static methods.
super keyword used to access the members of the super class object.
super.member;
It is used to store super class non static members memory reference through current sub class object for separating super class members from subclass members.
We can call super class constructor in sub class using super() call.
We can access super class methods and variables in sub class using super.variable_name, super.method();
What are the usage of Super Keyword?
Uses of super :
1. By using super keyword we can access super class variables in sub class.
Using super keyword we can access super class variables from sub class.
super.variable_name.
package com.superkeywordinjava;
public Class SuperDemo{
int a,b;
}
package com.superkeywordinjava;
public Class Subdemo extends SuperDemo{
int a,b;
void disply(){
System.out.println(a);
System.out.println(b);
super.a=10;
super.b=20;
System.out.println(super.a);
System.out.println(super.b);
}
public static void main (String args[]) {
Subdemo obj= new Subdemo();
obj.a=1;
obj.b=2;
obj.disply();
}
}
Output:
1
2
10
20
2. By using super keyword we can access super class methods in sub class.
Using super keyword we can call super class methods from sub class.
super.method();.
package com.instanceofjavaforus;
public Class SuperDemo{
int a,b;
public void show() {
System.out.println(a);
System.out.println(b);
}
}
package com.instanceofjavaforus;
public Class Subdemo extends SuperDemo{
int a,b;
void disply(){
System.out.println(a);
System.out.println(b);
super.a=10;
super.b=20;
super.show();
}
public static void main (String args[]) {
Subdemo obj= new Subdemo();
obj.a=1;
obj.b=2;
obj.disply();
}
}
Output:
1
2
10
20
3. We can call super class constructor from class constructor:
By using super keyword we can able to call super class constructor from sub class constructor.
Using super();
For the super(); call must be first statement in sub class constructor.
package com.superinterviewprograms;
public Class SuperDemo{
int a,b;
SuperDemo(int x, int y){
a=x;
b=y
System.out.println("Super class constructor called ");
}
}
package com.superinterviewprograms;
public Class Subdemo extends SuperDemo{
int a,b;
SubDemo(int x, int y){
super(10,20);
a=x;
b=y
System.out.println("Sub class constructor called ");
}
public static void main (String args[]) {
Subdemo obj= new Subdemo(1,2);
}
}
Output:
Super class constructor called
Sub class constructor called
key points:
Super(); call must be first statement inside constructor.
By default in every class constructor JVM adds super(); call inside the constructor as first statement which calls default constructor of super class, if we are not calling it.
If we want to call explicitly we can call at that time default call won’t be there.
What will happen if we are calling super() in constructor but our class does not extending any class?
If our class not extending any class Yes still we can use super(); call in our class
Because in java every class will extend Object class by default this will be added by JVM.
But make sure we are using only super(); default call we can not place parameterized super call because Object class does not have any parameterized constructor.
package com.superinterviewprograms;
public Class Sample{
Sample(){
super();
System.out.println("Sample class constructor called ");
}
public static void main (String args[]) {
Sample obj= new Sample();
}
}
Output:
Sample class constructor called
5.What if there is a chain of extended classes and 'super' keyword is used
package com.superinterviewprograms;
public Class A{
A(){
System.out.println("A class constructor called ");
}
}
package com.superinterviewprograms;
public Class B extends A{
B(){
System.out.println("B class constructor called ");
}
}
package com.superinterviewprograms;
public Class C extends B{
C(){
System.out.println("C class constructor called ");
}
public static void main (String args[]) {
C obj= new C();
}
}
Output:
A class constructor called
B class constructor called
C class constructor called
Can we call super class methods from static methods of sub class?
No we cannot use super in static methods of sub class Because super belongs to object level so we cannot use super in static methods.
If we try to use in sub class static methods compile time error will come.
Is a constructor is static or non-static? How can a static main method allows constructors to create objects?
Constructors are non-static, java allows to create object from main method is because of new keyword anything with new key word always invokes constructor internally.
main() is static still how can it access non static methods and variables?
In order to call a non-static method, you will need an instance of an object. You can call the non-static method using the dot operator on the object. There is no restriction on static methods to call non-static methods provided you have the object.
The reason the main method is static is because you don't need an object to call it. If the main method were not static, then you would have needed an object to call the main method. Since the execution of your program starts (not entirely correct this statement) from the main method, you don't have any object with you that will help you call the main method.
How is the reference variable used to access the instance variable non-statically from the parent class??
class parent{int i=2;}
class child extends parent{int i=3;}
public class test{
public static void main(){
parent obj=new child();
System.out.print (obj.i);
}
}
the output is 2 .. why and how??
Output will be 2 because, i is private non-virtual variable for each of parent and child class.
However in java all public methods are virtual by default so you can do something like this
class parent{
int i=2;
public int getI()
{
return i;
}
}
class child extends parent{
int i=3;
@Override
public int getI(){
return i;
}
}
class test{
public static void main(String[] args){
parent obj=new child();
System.out.println (obj.i); //prints 2
System.out.println (((child)obj).i); //prints 3
System.out.println (obj.getI()); //again prints 3, because getI is //virtual by default. to make it non-virtual add final keyword.
}
}
The concept to understand here is virtual in OOPS
In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature.
Wrapper class in Java
Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below:
Primitive Type
|
Wrapper class
|
boolean
|
Boolean
|
char
|
Character
|
byte
|
Byte
|
short
|
Short
|
int
|
Integer
|
long
|
Long
|
float
|
Float
|
double
|
Double
|
Utility methods in Wrapper class :
Wrapper class Example: Primitive to Wrapper
1. public class WrapperExample1{
2. public static void main(String args[]){
3. //Converting int into Integer
4. int a=20;
5. Integer i=Integer.valueOf(a);//converting int into Integer
6. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}
Output:
20 20 20
Wrapper class Example: Wrapper to Primitive
1. public class WrapperExample2{
2. public static void main(String args[]){
3. //Converting Integer to int
4. Integer a=new Integer(3);
5. int i=a.intValue();//converting Integer to int
6. int j=a;//unboxing, now compiler will write a.intValue() internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}
Output:
3 3 3
What is Auto Boxing?
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, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Integer ten = new Integer(10);
ten++;//allowed. Java does had work behind the screen for us
Boxing and new instances
Auto Boxing helps in saving memory by reusing already created Wrapper objects. However wrapper classes created using new are not reused.
Two wrapper objects created using new are not same object.
Integer nineA = new Integer(9);
Integer nineB = new Integer(9);
System.out.println(nineA == nineB);//false
System.out.println(nineA.equals(nineB));//true
Two wrapper objects created using boxing are same object.
Integer nineC = 9;
Integer nineD = 9;
System.out.println(nineC == nineD);//true
System.out.println(nineC.equals(nineD));//true
Collections in java is a framework that provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
Iterator : Iterator interface provides the facility of iterating the elements in forward direction only.
There are only three methods in the Iterator interface. They are:
public boolean hasNext() it returns true if iterator has more elements.
public object next() it returns the element and moves the cursor pointer to the next element.
public void remove() it removes the last elements returned by the iterator. It is rarely used.
Java ArrayList class
1. Java ArrayList class uses a dynamic array for storing the elements .It extends AbstractList class and implements List interface.
2. Java ArrayList class can contain duplicate elements.
3. Java ArrayList class maintains insertion order.
4. Java ArrayList class is non synchronized.
5. Java ArrayList allows random access because array works at the index basis.
6. In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list
Java Non-generic Vs Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.
Let's see the old non-generic example of creating java collection.
ArrayList al=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces.
Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error.
Two ways to iterate the elements of collection in java
Ø By Iterator interface.
Ø By for-each loop.
Java LinkedList class
1. Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.
2. Java LinkedList class can contain duplicate elements.
3. Java LinkedList class maintains insertion order.
4. Java LinkedList class is non synchronized.
5. In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
6. Java LinkedList class can be used as list, stack or queue.
Difference between ArrayList and LinkedList :-
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
1. ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.
2. Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
3. ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4. ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.
Java List Interface
List Interface is the subinterface of Collection.It contains methods to insert and delete elements in index basis.It is a factory of ListIterator interface.
ListIterator Interface is used to traverse the element in backward and forward direction.
Commonly used methods of ListIterator Interface:
Ø public boolean hasNext();
Ø public Object next();
Ø public boolean hasPrevious();
Ø public Object previous();
Java HashSet class
uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
contains unique elements only.
Difference between List and Set:
List can contain duplicate elements whereas Set contains unique elements only.
Java Queue Interface
The Queue interface basically orders the element in FIFO(First In First Out)manner.
Methods of Queue Interface :
Ø public boolean add(object);
Ø public boolean offer(object);
Ø public remove();
Ø public poll();
Ø public element();
Ø public peek()
PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not order the elements in FIFO manner.
Java Map Interface
A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys.
Map is useful if you have to search, update or delete elements on the basis of key.
Entry Interface
Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It provides methods to get key and value.
Methods of Map.Entry interface
public Object getKey(): is used to obtain key.
public Object getValue():is used to obtain value.
Java HashMap class
A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
Ø It contains only unique elements.
Ø It may have one null key and multiple null values.
Ø It maintains no order.
What is difference between HashSet and HashMap?
HashSet contains only values whereas HashMap contains entry(key and value).
Java LinkedHashMap class
A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
Ø It contains only unique elements.
Ø It may have one null key and multiple null values.
Ø It is same as HashMap instead maintains insertion order.
Java Hashtable class
A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.
Ø It contains only unique elements.
Ø It may have not have any null key or value.
Ø It is synchronized.
Sorting in Collection
We can sort the elements of:
Ø String objects
Ø Wrapper class objects
Ø User-defined class objects
Collections class provides static methods for sorting the elements of collection. If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List.List elements must be of Comparable type.
Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Properties class in Java
The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods to get data from properties file and store data into properties file. Moreover, it can be used to get properties of system.
Advantage of properties file
Recompilation is not required, if information is changed from properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently.
What is the difference between Enumeration and Iterator?
The functionality of Enumeration and the Iterator are same. You can get remove()
from Iterator to remove an element, while while Enumeration does not have remove()
method. Using Enumeration you can only traverse and fetch the objects, whereas using
Iterator we can also add and remove the objects. So Iterator can be useful if you want
to manipulate the list and Enumeration is for read-only access.
What are different ways to iterate over a list?
We can iterate over a list in two different ways – using iterator and using for-each loop.
List<String> strList = new ArrayList<>();
//using for-each loop
for(String obj : strList){
System.out.println(obj);
}
//using iterator
Iterator<String> it = strList.iterator();
while(it.hasNext()){
String obj = it.next();
System.out.println(obj);
}
Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.
Why Iterator don’t have a method to get next element directly without moving the cursor?
It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.
How HashMap works in Java?
HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods.
When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.
When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. Below image will explain these detail clearly.
The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 16 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.
What is the importance of hashCode() and equals() methods?
HashMap uses Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.
Similarly all the collection classes that doesn’t store duplicate data use hashCode() and equals() to find duplicates, so it’s very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.
If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.
What are different Collection views provided by Map interface?
Map interface provides three collection views:
Set keySet() : Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
Collection values() : Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
Set<Map.Entry<K, V>> entrySet() : Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
What are similarities and difference between ArrayList and Vector?
ArrayList and Vector are similar classes in many ways.
Ø Both are index based and backed up by an array internally.
Ø Both maintains the order of insertion and we can get the elements in the order of insertion.
Ø The iterator implementations of ArrayList and Vector both are fail-fast by design.
Ø ArrayList and Vector both allows null values and random access to element using index number.
These are the differences between ArrayList and Vector.
Ø Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList.
Ø ArrayList is faster than Vector because it doesn’t have any overhead because of synchronization.
Ø ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class.
What is difference between Array and ArrayList? When will you use Array over ArrayList?
Ø Arrays can contain primitive or Objects whereas ArrayList can contain only Objects.
Ø Arrays are fixed size whereas ArrayList size is dynamic.
Ø Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iterator etc.
Ø Although ArrayList is the obvious choice when we work on list, there are few times when array are good to use.
Ø If the size of list is fixed and mostly used to store and traverse them.
Ø For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types.
Ø If you are working on fixed multi-dimensional situation, using [][] is far more easier than List<List<>>
Which collection classes provide random access of it’s elements?
ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements. Download java collections pdf for more information.
What is EnumSet?
java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s).
What is Queue and Stack, list their differences?
Both Queue and Stack are used to store data before processing them. java.util.Queue is an interface whose implementation classes are present in java concurrent package. Queue allows retrieval of element in First-In-First-Out (FIFO) order but it’s not always the case. There is also Deque interface that allows elements to be retrieved from both end of the queue.
Stack is similar to queue except that it allows elements to be retrieved in Last-In-First-Out (LIFO) order.
Stack is a class that extends Vector whereas Queue is an interface.
What is Comparable and Comparator interface?
Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.
But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Comparator interface because Comparable.compareTo(Object o) method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.
Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.
How can we sort a list of Objects?
If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).
Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take some time to convert list to array.
What is Big-O notation? Give some examples?
The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure. Since Collection classes are actually data structures, we usually tend to use Big-O notation to chose the collection implementation to use based on time, memory and performance.
Example 1: ArrayList get(index i) is a constant-time operation and doesn’t depend on the number of elements in the list. So it’s performance in Big-O notation is O(1).
Example 2: A linear search on array or list performance is O(n) because we need to search through entire list of elements to find the element.
Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?
Generics doesn’t support sub-typing because it will cause issues in achieving type safety. That’s why List<T> is not considered as a subtype of List<S> where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.
List<Long> listLong = new ArrayList<Long>();
listLong.add(Long.valueOf(10));
List<Number> listNumbers = listLong; // compiler error
listNumbers.add(Double.valueOf(1.23));
As you can see from above code that IF generics would have been supporting sub-typing, we could have easily add a Double to the list of Long that would have caused ClassCastException at runtime while traversing the list of Long.
Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];
We are not allowed to create generic arrays because array carry type information of it’s elements at runtime. This information is used at runtime to throw ArrayStoreException if elements type doesn’t match to the defined type. Since generics type information gets erased at runtime by Type Erasure, the array store check would have been passed where it should have failed. Let’s understand this with a simple example code.
List<Integer>[] intList = new List<Integer>[5]; // compile error
Object[] objArray = intList;
List<Double> doubleList = new ArrayList<Double>();
doubleList.add(Double.valueOf(1.23));
objArray[0] = doubleList; // this should fail but it would pass because at runtime intList and doubleList both are just List.
Arrays are covariant by nature i.e S[] is a subtype of T[] whenever S is a subtype of T but generics doesn’t support covariance or sub-typing as we saw in last question. So if we would have been allowed to create generic arrays, because of type erasure we would not get array store exception even though both types are not related.
What is Composition in Java? Java Composition Example
Composition is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition for code reuse.
Java composition is achieved by using instance variables that refers to other objects. For example, a Person has a Job. Let’s see this with a simple code.
package com.journaldev.composition;
public class Job {
private String role;
private long salary;
private int id;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.journaldev.composition;
public class Person {
//composition has-a relationship
private Job job;
public Person(){
this.job=new Job();
job.setSalary(1000L);
}
public long getSalary() {
return job.getSalary();
}
}
Here is a test class that uses person object and get it’s salary.
package com.journaldev.composition;
public class TestPerson {
public static void main(String[] args) {
Person person = new Person();
long salary = person.getSalary();
}
}
Notice that above test program is not affected by any change in the Job object. If you are looking for code reuse and the relationship between two classes is has-a then you should use composition rather than inheritance.
Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.
Also if there is any change in the other class implementation, for example getSalary returning String, we need to change Person class to accomodate it but client classes doesn’t need to change.
Composition allows creation of back-end class when it’s needed, for example we can change Person getSalary method to initialize the Job object.
Composition Vs Inheritance:
One of the best practices of java programming is to “favor composition over inheritance”. We will look into some of the aspects favoring this approach.
Suppose we have a superclass and subclass as follows:
ClassC.java
package com.journaldev.inheritance;
public class ClassC{
public void methodC(){
}
}
ClassD.java
package com.journaldev.inheritance;
public class ClassD extends ClassC{
public int test(){
return 0;
}
}
The above code compiles and works fine but what if ClassC implementation is changed like below:
ClassC.java
package com.journaldev.inheritance;
public class ClassC{
public void methodC(){
}
public void test(){
}
}
Notice that test() method already exists in the subclass but the return type is different. Now the ClassD won’t compile and if you are using any IDE, it will suggest you to change the return type in either superclass or subclass.
Now imagine the situation where we have multiple level of class inheritance and superclass is not controlled by us. We will have no choice but to change our subclass method signature or it’s name to remove the compilation error. Also we will have to make change in all the places where our subclass method was getting invoked, so inheritance makes our code fragile.
The above problem will never occur with composition and that makes it more favorable over inheritance.
Another problem with inheritance is that we are exposing all the superclass methods to the client and if our superclass is not properly designed and there are security holes, then even though we take complete care in implementing our class, we get affected by the poor implementation of superclass.
Composition helps us in providing controlled access to the superclass methods whereas inheritance doesn’t provide any control of the superclass methods, this is also one of the major advantage of composition over inheritance.
Another benefit with composition is that it provides flexibility in invocation of methods. Our above implementation of ClassC is not optimal and provides compile time binding with the method that will be invoked, with minimal change we can make the method invocation flexible and make it dynamic.
ClassC.java
package com.journaldev.inheritance;
public class ClassC{
SuperClass obj = null;
public ClassC(SuperClass o){
this.obj = o;
}
public void test(){
obj.doSomething();
}
public static void main(String args[]){
ClassC obj1 = new ClassC(new ClassA());
ClassC obj2 = new ClassC(new ClassB());
obj1.test();
obj2.test();
}
}
Output of above program is:
doSomething implementation of A
doSomething implementation of B
This flexibility in method invocation is not available in inheritance and boosts the best practice to favor composition over inheritance.
Unit testing is easy in composition because we know what all methods we are using from superclass and we can mock it up for testing whereas in inheritance we depend heavily on superclass and don’t know what all methods of superclass will be used, so we need to test all the methods of superclass, that is an extra work and we need to do it unnecessarily because of inheritance.
Reflection :
Java Reflection provides ability to inspect and modify the runtime behavior of application. Reflection in Java is one of the advance topic of core java. Using java reflection we can inspect a class, interface, enum, get their structure, methods and fields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values.
Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Methods in Object class :-
Ø public final Class getClass(): - returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
Ø public int hashCode():- returns the hashcode number for this object.
Ø public boolean equals(Object obj):- compares the given object to this object.
Ø public String toString() :- returns the string representation of this object.
Ø public final void notify() :- wakes up single thread, waiting on this object's monitor.
Ø public final void notifyAll() :- wakes up all the threads, waiting on this object's monitor.
Ø public final void wait()throws InterruptedException :-causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
Ø protected void finalize() :- throws Throwable
Object Cloning in Java
constructor in java The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class.
Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
Why use clone() method ?
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.
Advantage of Object cloning
Less processing task.
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Array in java :-
There are two types of array.
Ø Single Dimensional Array
Ø Multidimensional Array
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.
Java Strictfp Keyword
Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic.
The strictfp keyword can be applied on methods, classes and interfaces.
strictfp class A{}//strictfp applied on class
strictfp interface M{}//strictfp applied on interface
class A{
strictfp void m(){}//strictfp applied on method
}
Java Command Line Arguments
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
1.Abstraction solves the problem at design level while encapsulation solves the problem at implementation level
2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.
4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.
What are the features of encapsulation ?
Combine the data of our application and its manipulation at one place.
Encapsulation Allow the state of an object to be accessed and modified through behaviors.
Reduce the coupling of modules and increase the cohesion inside them.
Which of the following Java feature promotes access protection or Hiding ?
a. Inheritance
b. Encapsulation
c. Abstraction
d. Composition
Ans. Encapsulation
What is accessor and mutator in Java?
One of the ways we can enforce data encapsulation is through the use of accessors and mutators. The role of accessors and mutators are to return and set the values of an object's state.
Why Use Accessors and Mutators?
It's easy to come to the conclusion that we could just change the private fields of the class definition to be public and achieve the same results. It's important to remember that we want to hide the data of the object as much as possible. The extra buffer provided by these methods allows us to:
change how the data is handled behind the scenes
impose validation on the values that the fields are being set to.
Accessor Methods
An accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word "get" to the start of the method name.
Mutator Methods
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word "set" to the start of the method name.
Accessor methods only let you look at data--they don't change it. Think of them as read-only.
Mutator methods let you change data. To put this a different way, they're read-write capable.
No comments:
Post a Comment