-->

Software AG Interview Solution– Set 1

Posted by Admin on









Round 1 

1. Interface i = 20 Abstract class i = 10
subclass uses i,what will be the value??
Ans:-It will give an ambiguity error.
Because subclass will have two  i and it get confused which i should be used .

See the following:
abstract class X{
    int i=20;
}
interface Y
{
        int i=10;
}
public class A extends X implements Y{
        public static void main(String args[])
        {
                System.out.println(i);//ambiguity error
        }
}
Q2. new String(“str”); how many objects will be created?
There are two ways of creating String objects in java .
1. By string literal
2 By new keyword .

To understand the concept of above question first we will have to understand about the string literal .
String literal is created by double quote.For Example:
String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:
String s1="Hello";

String s2="Hello";//no new object will be created

In the above example only one object will be created.First time JVM will find no string object with the name "Hello" in string constant pool,so it will create a new object.Second time it will find the string with the name "Hello" in string constant pool,so it will not create new object whether will return the reference to the same instance.

Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.

Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

 By new keyword:

String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).
See the figure given below :
So in the above question two objects will be created .

Q3. wait(); notify(); Explain?
  • wait() method causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.notify() method is used to unblock one waiting thread . 
  • wait() and notify() both are synchronized method and both are defined in the Object class.
Why wait() and notify() are defined in the object class ?
As we know both wait and notify are synchronized method and synchronizes method are used for mutual exclusion and ensuring thread safety of java class. Hence to provide thread safety during thread communication synchronized method should be available at every class . And object class is super class of all the class . In this way by defining wait and notify method in Object class we make sure they are present in every class taking part in communication . Hence preventing race condition.  

Q4. When will a thread go in a waiting state?
There can be many reason for a thread to go in waiting state :
1. when we apply sleep method on a thread.
2.Input output interruption.
3. waiting for a lock .

 Q5. Can we have a static & final method?
Yes, we can make static and final method . Final is used with method to prevent it from overriding . As we know static method does n't belong to an object or class . So final can be used with a static method.

Q6. Can we have an abstract & final method?  
No, because abstract  method are always inherited and defined in the subclass and final keyword is used to prevent a method from overriding . Hence we cant use final with the abstract method.

Q7. What are the implications of declaring a constructor private?
•We can make constructor as private. So that We can not create an object outside of the class.
•This property is useful to create singleton class in java.
•Singleton pattern helps us to keep only one instance of a class at any time.
•The purpose of singleton is to control object creation by keeping private constructor.

package com.myjava.constructors;
 
public class MySingleTon {
     
    private static MySingleTon myObj;
    /**
     * Create private constructor
     */
    private MySingleTon(){
         
    }
    /**
     * Create a static method to get instance.
     */
    public static MySingleTon getInstance(){
        if(myObj == null){
            myObj = new MySingleTon();
        }
        return myObj;
    }
     
    public void getSomeThing(){
        // do something here
        System.out.println("I am here....");
    }
     
    public static void main(String a[]){
        MySingleTon st = MySingleTon.getInstance();
        st.getSomeThing();
    }
}


Q8. Can there be a private/constructor in an abstract class?
Yes,Abstract class can have a private constructor. But that class cannot be extended by another class. Instead add a static inner class inside the abstact class and extend that abstract class.
abstract class  Base{
public abstract void set();
 
private Base(){
System.out.println("Private Constructor!");
}
static class Derived extends Base{
public void set(){
System.out.println("set() method implemented!");
}
}
public static void main(String[] args){
new Base.Derived().set();
}
}

Round -2

Q1. Do all lists retain the insertion order?
Yes all the list retain the insertion order.

Q2. How to add an object in a sorrted arraylist at its sorted place?
Answer is very simple . here m  providing  just hint.
1. Use comparable interface .
2. find the position of the element to be added .
3. add the element at the place and displace rest of the element by one.

Q3. How to sort keys in a hashmap?
There are three ways of sorting keys in a Hashmap:
1. By putting in the tree map and the printing the object.
2.By using Collection.sort() method .
3. By putting the keys in an array then sorting the array and then retrieving the data from the Hashmap using keys .
Below is an implementation of first two method :
import java.util.*;
import java.lang.*;
 
class Main
{
        public static void main (String[] args) throws java.lang.Exception
        {
        Map<Integer,String> Name = new HashMap<Integer, String>();
        Name.put(3,"ishant");
        Name.put( 1,"rahul");
        Name.put( 2,"aditya");
        Name.put( 4,"gautam");
                    
        //Sorting Map in Java by keys using TreeMap
        Map<Integer,String> sortedMapByKeys = new TreeMap<Integer,String>();
        sortedMapByKeys.putAll(Name);
        System.out.println("Sorted Map in Java by key using TreeMap : " + sortedMapByKeys);
       //sorting Map e.g. HashMap, Hashtable by keys in Java
        Map<Integer,String> sorted = sortByKeys(Name);
        System.out.println("Sorted Map in Java by key: " + sorted); 
 
        }
    
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys);
      
        //LinkedHashMap will keep the keys in the order they are inserted
        //which is currently sorted on natural ordering
        Map<K,V> sortedMap = new LinkedHashMap<K,V>();
        for(K key: keys){
            sortedMap.put(key, map.get(key));
        }
      
        return sortedMap;
    }
 
}


Q4. How to sort values in hashmap?

import java.util.*;
import java.util.Map.Entry;
import java.lang.*;
 
class Main
{
        public static void main (String[] args) throws java.lang.Exception
        {
        Map<Integer,String> Name = new HashMap<Integer, String>();
        Name.put(3,"ishant");
        Name.put( 1,"rahul");
        Name.put( 2,"aditya");
        Name.put( 4,"gautam");
        
            
    //sorting Map like Hashtable and HashMap by values in Java
        Map<Integer,String> sorted = sortByValues(Name);
        System.out.println("Sorted Map in Java by values: " + sorted);
    }
    
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
  List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());
      
        Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
 
            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
      
        //LinkedHashMap will keep the keys in the order they are inserted
        //which is currently sorted on natural ordering
        Map<K,V> sortedMap = new LinkedHashMap<K,V>();
      
        for(Map.Entry<K,V> entry: entries){
            sortedMap.put(entry.getKey(), entry.getValue());
        }
      
        return sortedMap;
    }
}

Q5. Can a constructor be final?
NO,Final keyword is used to protect the method to be overridden as we know  constructor are not inherited hence there is no meaning of making constructor final.

Q6. How can u stop a class from being subclassed? except final?
Yes we can stop a class from being subclassed by making the constructor private . See Q:8 of round 1.

Q7. How will u create your class immutable?
First we will see the what is the property of  immutable class :
State of immutable object can not be modified after construction, any modification should result in new immutable object.
Hence to make an immutable class we will have to do the following :
1. we have to make class final so that it can't be subclassed and its instance cannot be modified.
2.we have to make all the date member final so that their value cant be changed .
See the below program :
public final class Contacts {
       private final String name;
    private final String mobile;
       public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
    public String getName(){
        return name;    }
  
    public String getMobile(){
        return mobile;
    }
}

Round 3:

Q1. What will be the data structure of the n-ary tree?
Ans: N-ary tree are those tree in which every node can have 0 to N children . the best data structure to represent the n-ary tree would be Graph .

Q2. Implement a stack in java?
Ans: To see the Implementation of stack see this .

Please comment if you find any mistake or better answer for any question .





5 comments: