July 30, 2017
July 28, 2017
July 27, 2017
Some Basic Core Java Interview Questions
Confusing Overloading and Overriding Questions
1). We have a Father and Son class, Son is extending Father. Father class has two methods m1() and m2(), Son has a single method m3().
What is going to happen if I do this?
Son s=new Father();
s.m1();
This will throw a compile time error 'cannot convert from Father to Son'.
Let's say the method m1() is declared as protected in Father class, I am overriding it in Son without writing protected key word. What will happen?
It will throw a compile time error, 'Cannot reduce the visibility of the inherited method from Father'.
If Father's m1() is default , can I override it in Son and make it protected? Yes.
NOTE: Overriding method must not have more restrictive access modifier. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.
Father's m1() is throwing FileNotFoundException, can I throw IOException from overridden m1()? No, because we cannot throw a newer or boarder exception.
If the Father's m1() is throwing IOException, we can throw FileNotFoundException Son's m1(), because FileNotFoundException extends IOException.
NOTE: Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.
2). What will happen if I overload foo method in below manner?
void foo(){}
int foo(){}
String foo(){}
We will get a compile time error 'Duplicate method foo()'.
NOTE: Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.
3). If MyClass has below methods:
void foo(String s){}
void foo(Object o){}
Now if I call foo by passing null, which method will be called?
myclassObj.foo(null);
It will call the foo method which takes String.
Now, lets say I add another method:
void foo(int s) {}
What will happen if I call myclassObj.foo(null);? Again It will call the foo method which takes String.
Now, lets say I add another method:
void foo(Integer s) {}
What will happen if I call myclassObj.foo(null);? You will get a compile time error 'The method foo(String) is ambiguous', because the compiler is not able to decide whther to call method which takes String or Integer?
4). Can I override a static method?
private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
Static methods belong to the class and not the objects. Since they belong to the class and hence doesn't fit properly for the polymorphic behavior.
Static methods are resolved at compile time rather than runtime. Though you can declare and define static method of same name and signature in the child class, this will hide the static method from parent class, that's why it is also known as method hiding in Java.
Suppose you have declared a Father class, which is extended by Son. Both the classes have method 'static void sayHello()'.
Father f=new Son();
f.sayHello();
This will always call sayHello() method from Father class. (if sayHello() was not declared static then, sayHello() from Son will be called).
5). Let's say you have a Father class, another class Son is extending Father.
Inside my test class, have declared below methods:
static void foo(Father f) {
System.out.println("Father's foo");
}
static void foo(Son s) {
System.out.println("Son's foo");
}
Which method will be called when I pass null in foo: foo(null) will call the method which takes Son as input.
Now let's say I have added another class Grandson which is extending Son. After this I added another method in our test class:
static void foo(GrandSon gs) {
System.out.println("GrandSon's foo");
}
In this case foo(null) will call the method which takes GrandSon as input.
If both Son and GrandSon extends Father class, and we declared three foo methods each taking Father, Son and GrandSon as an input. And we call foo by passing a null, we will get a compilation error "The method foo(Father) is ambiguous."
6). If the Son is extending Father class, and which line/ lines in the below code will result in compilation/ runtime error?
Father f=new Son();
Son s=new Father();//compilation error 'cannot convert from Father to Son'
Set < Father > fatherset=new HashSet < > ();
fatherset.add(new Father());//works fine
fatherset.add(new Son());//works fine
fatherset.add(f);//works fine
Set < Son > sonset=new HashSet > ();
sonset.add(new Father());//compilation error Set is not applicable for the arguments (Father)
sonset.add(new Son());//works fine
sonset.add(f);//compilation error Set is not applicable for the arguments (Father)
7). Father class has m1() and m2() methods, Son class is extending Father and is overriding method m1(), along with this it has another method m3(). Which of the lines will throw complication error?
Father f1=new Father();
f1.m3();//compilation error method m3() is undefined for the type Father
Father f2=new Son();
f2.m3();//compilation error method m3() is undefined for the type Father
Father s2=new Son();
s2.m1();//overridden method from Son is called
Father s3=new Father();
s3.m1();//Father's m1() will be called.
Try, catch, finally block.
1). Can I write a try block without catch and finally? No.
2). Can I write a try block without catch and with finally? Yes.
3). What will be the output of below method:
int foo() {
try {
return 0;
}
catch(Exception e) {
return 1;
}
finally {
return 2;
}
}
It will return 2. Finally block will execute, but you will get a warning 'finally block does not complete normally'.
4). What will be the output of below method?
int foo() {
try {
return 0;
}
catch(Exception e) {
return 1;
}
finally {
System.out.println("This is Finally block");
}
}
It will print 'his is Finally block' and return 0.
5). What if I mention System.exit(0) in try block, will finally block is going to execute?
System.exit() statement behaves differently than return statement. Unlike return statement whenever System.exit() gets called in try block then Finally block doesn’t execute.
System.exit(0) gets called without any exception then finally won’t execute. However if any exception occurs while calling System.exit(0) then finally block will be executed.
6). What is the output of below code:
public static void main(String args[]) {
try {
System.out.println("First statement of try block");
int num = 45 / 0;
System.out.println(num);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occurred.");
}
finally {
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
It will print:
First statement of try block
Exception in thread "main" finally block
java.lang.ArithmeticException: / by zero
at com.Test.main(Test.java:20)
If ArithmeticException is catched instead of ArrayIndexOutOfBoundsException, output would be:
First statement of try block
Exception occurred.
finally block
Out of try-catch-finally block
-K Himaanshu Shuklaa..
1). We have a Father and Son class, Son is extending Father. Father class has two methods m1() and m2(), Son has a single method m3().
What is going to happen if I do this?
Son s=new Father();
s.m1();
This will throw a compile time error 'cannot convert from Father to Son'.
Let's say the method m1() is declared as protected in Father class, I am overriding it in Son without writing protected key word. What will happen?
It will throw a compile time error, 'Cannot reduce the visibility of the inherited method from Father'.
If Father's m1() is default , can I override it in Son and make it protected? Yes.
NOTE: Overriding method must not have more restrictive access modifier. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.
Father's m1() is throwing FileNotFoundException, can I throw IOException from overridden m1()? No, because we cannot throw a newer or boarder exception.
If the Father's m1() is throwing IOException, we can throw FileNotFoundException Son's m1(), because FileNotFoundException extends IOException.
NOTE: Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.
2). What will happen if I overload foo method in below manner?
void foo(){}
int foo(){}
String foo(){}
We will get a compile time error 'Duplicate method foo()'.
NOTE: Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.
3). If MyClass has below methods:
void foo(String s){}
void foo(Object o){}
Now if I call foo by passing null, which method will be called?
myclassObj.foo(null);
It will call the foo method which takes String.
Now, lets say I add another method:
void foo(int s) {}
What will happen if I call myclassObj.foo(null);? Again It will call the foo method which takes String.
Now, lets say I add another method:
void foo(Integer s) {}
What will happen if I call myclassObj.foo(null);? You will get a compile time error 'The method foo(String) is ambiguous', because the compiler is not able to decide whther to call method which takes String or Integer?
4). Can I override a static method?
private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
Static methods belong to the class and not the objects. Since they belong to the class and hence doesn't fit properly for the polymorphic behavior.
Static methods are resolved at compile time rather than runtime. Though you can declare and define static method of same name and signature in the child class, this will hide the static method from parent class, that's why it is also known as method hiding in Java.
Suppose you have declared a Father class, which is extended by Son. Both the classes have method 'static void sayHello()'.
Father f=new Son();
f.sayHello();
This will always call sayHello() method from Father class. (if sayHello() was not declared static then, sayHello() from Son will be called).
5). Let's say you have a Father class, another class Son is extending Father.
Inside my test class, have declared below methods:
static void foo(Father f) {
System.out.println("Father's foo");
}
static void foo(Son s) {
System.out.println("Son's foo");
}
Which method will be called when I pass null in foo: foo(null) will call the method which takes Son as input.
Now let's say I have added another class Grandson which is extending Son. After this I added another method in our test class:
static void foo(GrandSon gs) {
System.out.println("GrandSon's foo");
}
In this case foo(null) will call the method which takes GrandSon as input.
If both Son and GrandSon extends Father class, and we declared three foo methods each taking Father, Son and GrandSon as an input. And we call foo by passing a null, we will get a compilation error "The method foo(Father) is ambiguous."
6). If the Son is extending Father class, and which line/ lines in the below code will result in compilation/ runtime error?
Father f=new Son();
Son s=new Father();//compilation error 'cannot convert from Father to Son'
Set < Father > fatherset=new HashSet < > ();
fatherset.add(new Father());//works fine
fatherset.add(new Son());//works fine
fatherset.add(f);//works fine
Set < Son > sonset=new HashSet > ();
sonset.add(new Father());//compilation error Set
sonset.add(new Son());//works fine
sonset.add(f);//compilation error Set
7). Father class has m1() and m2() methods, Son class is extending Father and is overriding method m1(), along with this it has another method m3(). Which of the lines will throw complication error?
Father f1=new Father();
f1.m3();//compilation error method m3() is undefined for the type Father
Father f2=new Son();
f2.m3();//compilation error method m3() is undefined for the type Father
Father s2=new Son();
s2.m1();//overridden method from Son is called
Father s3=new Father();
s3.m1();//Father's m1() will be called.
Try, catch, finally block.
1). Can I write a try block without catch and finally? No.
2). Can I write a try block without catch and with finally? Yes.
3). What will be the output of below method:
int foo() {
try {
return 0;
}
catch(Exception e) {
return 1;
}
finally {
return 2;
}
}
It will return 2. Finally block will execute, but you will get a warning 'finally block does not complete normally'.
4). What will be the output of below method?
int foo() {
try {
return 0;
}
catch(Exception e) {
return 1;
}
finally {
System.out.println("This is Finally block");
}
}
It will print 'his is Finally block' and return 0.
5). What if I mention System.exit(0) in try block, will finally block is going to execute?
System.exit() statement behaves differently than return statement. Unlike return statement whenever System.exit() gets called in try block then Finally block doesn’t execute.
System.exit(0) gets called without any exception then finally won’t execute. However if any exception occurs while calling System.exit(0) then finally block will be executed.
6). What is the output of below code:
public static void main(String args[]) {
try {
System.out.println("First statement of try block");
int num = 45 / 0;
System.out.println(num);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occurred.");
}
finally {
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
It will print:
First statement of try block
Exception in thread "main" finally block
java.lang.ArithmeticException: / by zero
at com.Test.main(Test.java:20)
If ArithmeticException is catched instead of ArrayIndexOutOfBoundsException, output would be:
First statement of try block
Exception occurred.
finally block
Out of try-catch-finally block
-K Himaanshu Shuklaa..
Magician Amey Sarang launched trailer of his 12 short films..
The Third Generation illusionist, Amey Shraddha Sarang, made a mark in the world of Magic through his 16 world and national records. He is attempting another such record by preparing a series of 12 short films within 12 days. Each of these short films will be based on various themes, including a tribute to mothers and social awareness issues also. It will also incorporate magic and magicians in the storyline. The talent of magicians is usually restricted to social gatherings but Sarang would like to give magic on grander scale on international level as well as create bigger platform for passionate talents from all kind of arts other than magic.
July 22, 2017
Akash Gill to play an effeminate in 'Rishton Ka Chakravyuh'..
Akash Gill, who played the negative role in 'Gangaa' will be back in action soon with Rolling Pictures and Taurus Media's upcoming show 'Rishton Ka Chakravyuh' on Star Plus. Informs a source associated with the project, "Akash will be seen playing Baldev (Ajay Chaudhary) and Sudha's (Sangeeta Ghosh) son Narottam. As he is Sudha's step son, and she doesn't want him to become legal heir, that's why she raised him as a girl. As a kid, he was forced to wear, ghagra under shirt and behave like a girl. Because of his upbringing, Narottam is effeminate."
July 21, 2017
July 20, 2017
Ankit Tiwari, Babul Supriyo, Javed Ali & Leslie Louis performed to raise funds for the needy artists
'Rehmatein' as the name suggests was initiated to offer financial aid in difficult times for yesteryear noted musicians and established artists going through a rough phase.
This charitable music concert in its first year, raised funds for the legendary composer Khayyam & artist Rajendra Mehta. In the 2nd year, over 40 insurance policies were gifted to musicians & artists in need. Now, in its 3rd year, the concert, Rehmatein 3 brought bollywood melodious singers Ankit Tiwari, Babul Supriyo & Javed Ali alongwith Leslie Louis on one platform. The event was also graced by music maestro Bappi Lahiri who felicitated and awarded the recipients this year. The theme for this year was Bollywood and audience thoroughly enjoyed the evergreen hits of the artists.
This charitable music concert in its first year, raised funds for the legendary composer Khayyam & artist Rajendra Mehta. In the 2nd year, over 40 insurance policies were gifted to musicians & artists in need. Now, in its 3rd year, the concert, Rehmatein 3 brought bollywood melodious singers Ankit Tiwari, Babul Supriyo & Javed Ali alongwith Leslie Louis on one platform. The event was also graced by music maestro Bappi Lahiri who felicitated and awarded the recipients this year. The theme for this year was Bollywood and audience thoroughly enjoyed the evergreen hits of the artists.
I was obsessed with Ranbir, says 'Qaidi Band' actor Aadar Jain
He
is the newest kid from the Kapoor khandaan to make a foray into films.
Son of Reema Jain and grandson of Raj Kapoor, Aadar Jain is all set to
make his debut in the film Qaidi Band.
Even before the film hits the theatres, the youngster is making news.
After all, he was introduced by none other than cousin Ranbir Kapoor as
the new talent of YRF, the banner, which is launching him. His
promotional campaign, however, got targeted by the Twitterati as reeking
of nepotism. Here, the newbie talks about his debut film, cousin Ranbir
and takes head-on the charges of nepotism..
July 18, 2017
Part 3: LinkedList Related Algorithm Interview Questions(Union and Intersection)
Create a Union and Intersection of two Linked Lists.
Solution 1: Using Merge Sort.
In this approach you need to sort both the lists,this will take O(mLogm) and O(nLogn) time.
Now we will iterate both the sorted lists to get the union and intersection, it will take O(m + n) time
Time complexity of this method is O(mLogm + nLogn).
Solution 2:Use Hashing
We can use HashTable to find the Union and Intersection of two Linked Lists. Here we are assuming that there are no duplicates in each list. Time Complexity would be O(m+n).
For Union:
1). Create the result list, initialize it with NULL and create an empty hash table.
2). Start traversing the givens lists one by one. During iteration, look the element in the hash table. If the element is not present, then insert the element to the result list and in the hash table as well. Else if the element is present, then ignore it.
For Intersection:
1). Create the result list, initialize it with NULL and create an empty hash table.
2). Start traversing the first list, and insert each element in the hash table.
3). Now traverse the second list. During iteration, look the element in the hash table. If the element is not present, then insert the element to the result list and in the hash table as well. Else if the element is present, then ignore it.
Write a function to get the intersection point of two Linked Lists.
Solution 1: Nested Loop
1). We will use 2 nested loops. In the outer loop will be for each node of the 1st list and inner loop will be for 2nd list.
2). In the inner loop, we will check if any of nodes of the 2nd list is same as the current node of the first linked list.
The time complexity of this approach will be O(M * N), where m and n are the numbers of nodes in two lists.
Solution 2: Node count difference.
1). We will get the count of the nodes in the both the lists, lets say c1 and c2 are the number of nodes on 1st and 2nd list.
2). Now we will get the difference of node counts, d = abs(c1 – c2).
3). We will start traversing the bigger list from the first node till dth node. From here onwards both the lists have equal no of nodes.
4). Now we can traverse both the lists in parallel till we come across a common node.
-K Himaanshu Shuklaa..
Part 2: LinkedList Related Algorithm Interview Questions(Reverse)
How to reverse a linked list using recursion and iteration?
In the iteration approach we reverse linked list using 3 pointers in O(n) time, This is done by creating a new list by reversing direction, and subsequently inserting the element at the start of the list.
We can also reverse a singly linked list by using recursion. We will traverse the linked list until we find the tail, this tail would be the new head for reversed linked list.
-K Himaanshu Shuklaa..
In the iteration approach we reverse linked list using 3 pointers in O(n) time, This is done by creating a new list by reversing direction, and subsequently inserting the element at the start of the list.
We can also reverse a singly linked list by using recursion. We will traverse the linked list until we find the tail, this tail would be the new head for reversed linked list.
-K Himaanshu Shuklaa..
Part 1: LinkedList Related Algorithm Interview Questions(find kth element from end, check if list has loop)
How to find middle element of linked list in one pass?
LinkedList data structure contains a collection of the node and has head and tail. To find the middle element in one pass we can use two-pointer approach.
LinkedList data structure contains a collection of the node and has head and tail. To find the middle element in one pass we can use two-pointer approach.
July 17, 2017
Interview Questions of Nearby Technologies
1). You have a function f() returns Random number 1-6 with equal probability,
Write a function g which using function f which returns random number 1-12 with equal probability.
Solution
Write a function g which using function f which returns random number 1-12 with equal probability.
Solution
July 14, 2017
System Design Interview: How to implement TinyURL?
TinyURL shortens the long URL. URL shortening will have below benefits:
- Save space when displayed, printed or messaged.
- Consume less space when tweeted.
- Users are less likely to mistype the shorter URL's.
Why that's the wrong answer? because the person who is taking the interview us not looking for a simple solution where you take a longer url and convert it into a shorter one, store it in a map and returning the long url from the map whenever required.
The interviewer is interested ti test your knowledge on durability and scalability. The above diagram is correct, but sadly its neither durable nor scalable.
July 13, 2017
July 12, 2017
Ranveer Shaves off Beard to a Heavy Stubble, Becomes Young Khilji
Ranveer Singh is always known to give his 100 percent for every film and part. To become the one of his kind super villain Alauddin Khilji in Padmavati, Ranveer grew a thick beard, which he has sported at recent public appearances too. He also underwent rigorous physical training to bulk up and look like a menacing, ruthless warrior and conqueror, every bit the committed actor. His bearded look also set fashion trends.
July 10, 2017
July 09, 2017
July 06, 2017
What is the difference between SLF4J, Logback and LOG4J?
Logically these are entirely two different things.
SLF4J (Simple Logging Facade For Java) is not a logging component and it does not do the actual logging. It is only an abstraction layer to an underlying logging component. Where as Log4j is a logging component and it does the logging instructed to do.
SLF4J (Simple Logging Facade For Java) is not a logging component and it does not do the actual logging. It is only an abstraction layer to an underlying logging component. Where as Log4j is a logging component and it does the logging instructed to do.
July 04, 2017
OMG! Pankit and Praachi Thakker end their 17-year long marriage!
It appears that there are rocky roads ahead for Pankit and Praachi Thakker's love boat. The tight knit couple seem to be experience turbulence in their relationship since 2015. Rumor has it that the couple has been living in separate homes for nearly two years now and are heading for a divorce in the near future.
In a recent social media post, Pankit vented his feeling stating, "Never blame the other person for your personal choices; you are still the one who must live out the consequences of your choices."
In a recent social media post, Pankit vented his feeling stating, "Never blame the other person for your personal choices; you are still the one who must live out the consequences of your choices."
July 03, 2017
J2EE Patterns
J2EE Design Patterns
MVC is abbreviation of Model-View-Controller. Models are basically POJO's, which are used as blueprints/models for all of the objects that will be used in the application. Views represent the presentational aspect of the data and information located in the models. And the Controllers controls both of these.
Controller serve as a connection between the Model and View. It instantiate, update and delete models, populate them with information, and then send the data to the views to present to the end-user.
Front Controller Pattern
Upon sending a request, the Front Controller is the first controller it reaches. Based on the request, it decides which controller is the most adequate to handle it, after which it passes the request to the chosen controller. The Front Controller is most often used in Web Applications in the form of a Dispatcher Servlet.
Business Delegate Pattern
This pattern is used to decouple the presentation layer from the business layer. It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. In business tier we have following entities.
Composite Entity Pattern
A Composite entity is an EJB entity bean which represents a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean. Following are the participants in Composite Entity Bean.
Service Locator Pattern
A pattern often seen in Web Applications, the Service Locator pattern is used to decouple the Service Consumers and the concrete classes like DAO implementations.
The pattern looks for the adequate service, saves it in cache storage to reduce the number of requests and therefore the strain on the server and provides the application with their instances.
-K Himaanshu Shuklaa..
- MVC Pattern
- Business Delegate Pattern
- Composite Entity Pattern
- Data Access Object Pattern
- Front Controller Pattern
- Intercepting Filter Pattern
- Service Locator Pattern
- Transfer Object Pattern
MVC is abbreviation of Model-View-Controller. Models are basically POJO's, which are used as blueprints/models for all of the objects that will be used in the application. Views represent the presentational aspect of the data and information located in the models. And the Controllers controls both of these.
Controller serve as a connection between the Model and View. It instantiate, update and delete models, populate them with information, and then send the data to the views to present to the end-user.
Front Controller Pattern
Upon sending a request, the Front Controller is the first controller it reaches. Based on the request, it decides which controller is the most adequate to handle it, after which it passes the request to the chosen controller. The Front Controller is most often used in Web Applications in the form of a Dispatcher Servlet.
Business Delegate Pattern
This pattern is used to decouple the presentation layer from the business layer. It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. In business tier we have following entities.
- Business Service: Business Service interface. Concrete classes implement this business service to provide actual business implementation logic.
- LookUp Service: Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object.
- Business Delegate: A single entry point class for client entities to provide access to Business Service methods.
- Client: Presentation tier code may be JSP, servlet or UI java code.
Composite Entity Pattern
A Composite entity is an EJB entity bean which represents a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean. Following are the participants in Composite Entity Bean.
- Dependent Object: Dependent object is an object which depends on coarse grained object for its persistence lifecycle.
- Coarse-Grained Object: This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects.
- Composite Entity: It is primary entity bean. It can be coarse grained or can contain a coarse grained object to be used for persistence purpose.
- Strategies: Strategies represents how to implement a Composite Entity.
Service Locator Pattern
A pattern often seen in Web Applications, the Service Locator pattern is used to decouple the Service Consumers and the concrete classes like DAO implementations.
The pattern looks for the adequate service, saves it in cache storage to reduce the number of requests and therefore the strain on the server and provides the application with their instances.
-K Himaanshu Shuklaa..
July 01, 2017
Correlated Subqueries
A correlated subquery is a subquery that uses the values of the outer query, i.e it depends on the outer query for its values. Because of this dependency, a correlated subquery cannot be executed independently as a simple subquery.
Subscribe to:
Posts (Atom)