Skip to main content

Posts

Showing posts from April, 2020

Questions on Inheritance in Java

Here are some objective question on Inheritance and interfaces  in Java. Which of the following statements are true about an abstract class? An abstract class can be instantiated  An abstract class can be subclassed An abstract class can not have a concrete method All of the above Which of the following is the correct declaration of an interface? interface Test { public void print(){}}      interface Test { public void print(); } interface Test {   int a; void print(){}} All of the above Which of the following statements are true? A final class can not be extended An abstract class can not be instantiated An interface can not be instantiated All of the above   What is the correct way of defining a class ABC which uses an interface DEF? class ABC extends DEF class DEF extends ABC  class ABC implements DEF None of the above   Method overriding is used to implement ------ Inheritance Polymorphism Abstraction None of the above   A

Find nth node from end of list

Question : Write a program to find nth node from end of the list. A simple solution would be - traverse the list and find its length. And then go to length-n th node. But a better and more efficient solution is  (I got the idea- solution from geeksforgeeks website) Take two nodes nd1 and nd2 Move nd1 to nth node from beginning of list Set nd2 to first node Move nd1 and nd2 one node at a time in a loop until nd1 is last node (nd1.next is null) Now nd2 is the nth node from end of list  Here is complete code in Java. import java.util.Scanner ; class LinkedList { class Node { int num ; Node next ; public Node ( int n ){ num = n ; } Node getNext (){ return next ; } int getNum (){ return num ; } } public LinkedList (){ createList (); } public void createList () { int n ; Scanner scanner = new Scanner ( Syst

Linked List in Java

Let us write a linked list program in Java. You certainly ask me why don't you use List class - either ArrayList or LinkedList class in Collections? Because your interviewer will not ask you about library classes. He wants you to write your own code. OK, the basic premise of linked list is that - it has a node and it is linked to next node with a pointer - or a reference in Java. So we can define a Node class as follows class Node{     int num;     Node next; } The data of the node can be integer or some complex structure. But we must have a reference to next node - which is the second field in the class. First node has reference of second node. Second node has reference of third node and so on. What about last node? What will be next of the last node? Last node will have next field as null. null indicates the termination of list.  Now the list also needs the reference of first node - head, first or you call it by any name. It makes your program easier if you