20 Java Programs to clear Java Interview

How to create a custom exception in Java


Why we need custom Exception ?
How to create a custom exception ?
Write code to create a Custom Exception

All these are questions usually asked in a Java interview .So my today's post on how to create a custom exception in java .

As we know There are two types of Exception :
1. Checked Exception
2. Unchecked Exception

Both these exceptions have a common parent class Exception .So ,in same order if we have to create a custom exception ,we need to extend Exception class.

Ok , let me explain the process step by step .

1. Any custom exception should extend Exception Class .

2. There should be a proper name given to the Exception ,For example if there is an exception related to Invalid age name can be given as InvalidAgeException


public class InvalidAgeException extends Exception {}


public class InvalidAgeException extends Exception {
private int age;

public InvalidAgeException ()
{
super();
}
public InvalidAgeException (String message, int age)

{
   super(message);

   this.age = age;


}

In the above way we can define two constructors of InvalidAgeException with message and without message

Usage of custom Exception:

Below is the program with usage of custom exception.

public class CustomExceptionDemo 



private static final Map<Integer, String> employee = new HashMap<>(); 

static

 {
   employee.put(100"Mahesh");
  employee.put(101"Suresh");

   employee.put(102"Bran");

   employee.put(103"Troy"); }

 public static void main(String args[])
 { 

     CustomExceptionDemo t = new CustomExceptionDemo();

    t.getAge(1000); } 

public String getAge(int age)

 { 

     if (employee.get(age) == null)


   throw new InvalidAgeException ("No such employee exists", age);

return employee.get(name);

}

}







Hybris Interview Questions -items.xml

Q.1 What is the location of items.xml in Hybris?

Ans : Items.xml is extension specific . Every Extension has resources folder in which you can find items.xml file which perfix the extension name . The syntax is extensioname-items.xml.  For Example : core-items.xml or cockpit-items.xml.

Q .2 What is the basic structure of an Items.xml ?
Ans : The basic sturcture of an items.xml is

    xsi:noNamespaceSchemaLocation="items.xsd">
    <atomictypes>
    ...
    </atomictypes>
    <collectiontypes>
    ...
    </collectiontypes>
    <enumtypes>
    ...
    </enumtypes>
    <maptypes>
    ...
    </maptypes>
    <relations>
    ...
    </relations>
    <itemtypes>
    ...
    </itemtypes>
</items>

Q3. Can the order of the defined itemtypes vary in item.xml?
Ans : No , all the itemtypes defined should be in the order defined above otherwise it ll lead to a build error.

Q4 . How can you define a new item type in items.xml?
Ans : A new item type can be defined using the <itemtypes> tag which should include the code and description attributes of the defined item type.eg:
<itemtype code="NewType"
    extends="Product"
    autocreate="true"
    generate="true" >
</itemtype>

Q5. What is the meaning of various attributes used in defining a new itemtype?
Ans :

1. code: code is the name of the itemtype you defined . For eg. in above mentioned example NewType is the name of the itemtype I have created.

2. extends : extends attribute represents the parent of the new itemtype defined as in the above example Product item the parent of the NewType item defined.

3.autocreate : autocreate attrbiute can take only boolean value such as true and false. Setting autocreate element to true, which lets the hybris Commerce Suite create a new database entry for this type at initialization/update process. Setting the autocreate modifier to false causes a build failure if we are defining a new subtype if you are just adding an attribute the already defined item then autocreate can be set to false as it already has a database entry.

4. generate : This attribute allows the creation of a new Model (Java class) for the new itemtype defined .Setting it to false will lead to non creation of the model class due to which there wont be any build error but you wont be able to use the getter /setters of the attributes defined.

Q6. How an items.xml is verified or validated?
Ans : In your extension's directory /resources folder an item.xsd file exists  using which Hybris commerce Suite validated the items.xml against items.xsd. Any discrepancy caused between two files lead to build failure.

Q7. After creating a new itemtype which layers are effected and how many new classes are created?
Ans :
1. JaloLayer: under gensrc directory of that Extension ->Generated*.java  and gensrc directory is refreshed.
2. Service Layer: Generate model classes as *Model.java under bootstrap/gensrc directory in service layer .
3. *DTO .java and *resources.java :Webservice-related classes which are created to support CRUD logic via RESTful URIs. These classes are only generated when the optional extension platformwebservices is included in your configuration.
4. *java : In JaloLayer which extends the *Generated.java class.

SO in Total 5 new Java classes are created .


                                             Model service create method vs new operator - Hybris Interview question


Q.8 How to make cronjob run on some servers(in case of load balancer or cluster ) and  but not on others?

Ans : Read Here 

Q.9 How can you add values to a collection type attribute and Map from Impex in Hybris ?

Ans : Read Here

Q.10 Difference between ant all and ant clean all in hybris .

Ans .  Read Here .


Q.11 When to use modelService.refresh() method?

Ans . Read Here


How to run 2 hybris servers on same machine ?

How to run multiple hybris instances on same machine?

Flexible Search Query with JOIN Hybris Example

Hybris Composite Cron Job

How to remove duplicate elements from a String in Java

Hello coders, as you can see that from the past poster writing  about only the coding example of Java program it is because we are now focusing make a proper list of Java program which will help   you're the readers to crack Java interview questions. so the next post is about most popular question  which  is asked  in the JAVA interviews , Is how to remove duplicate elements from a String  in Java.If you have not gone through the previous Java programs and also find  them here.


So in this program which is am about to write we are dealing only with the string that contains alphabets not  number .  We have a string  as ”pdbertasd”  the output should be as “pdbertas”.
While Giving interview interviewer can ask to use any third party library or third party API to code these kind of questions ,  so we have design the answer accordingly.





public class JavaInHouseRemoveDuplicate{


String toRemove="myteststring";

public static void main(String[] args) {


String finalString=JavaInHouseRemoveDuplicate(toRemove);
System.out.println("Final String is : " + finalString);

public static String JavaInHouseRemoveDuplicate(String str) {
    char[] tempStringString = str.toCharArray();
    int length = tempString.length;
    for (int i = 0; i < length; i++) {
        for (int j = i + 1; j < length; j++) {
            if (tempString[i] == tempString[j]) {
                int test = j;
                for (int k = j + 1; k < length; k++) {
                    tempString[test] = tempString[k];
                    test++;
                }
                length--;
                j--;
            }
        }
    }
    return String.copyValueOf(tempString).substring(0, length);
}

}
}


OutPut is :

Final String is :mytesring




if you have any questions or suggestions please comment below.

HashMap Internal Working - Java

Hashmap working in java

   Hashmap class is equivalent to hashmap besides two things that they are unsynchronized any permits null value.

So what is hashing ?

Hashing means that you use a function or method or algorithm to represent an object with an integer value which makes finding that element quite easy in a storage that can be hashtable ,hashmap or anything that is using hash technique.

Hashmap

Hash map is a collection in which the elements are stored as key-value pair and each element stored is known as an Entry object .
Entry object is an object of  a class named as Entry class which contains :
1.key
2.value.
3.next
4.hash

Now we will look how actually hashmap works and how values are stored in hashmap and retrieved from it?
There are main  methods used for storing and retereiving values from hash map

1.    put() method à to put /store values in hashmap
2.    get() methodàto retrieve data/values from hasmap

Values above means objects not the actual value .
Besides these two methods two more methods plays a vital role in working of hasmap

hashcode()

equals()

Both these methods are defined in Object class only .
Now let us assume we have a map and we put some elements inside it

 HashMap<string,string> countryCapitalMap=new HashMap<string,string>();

        countryCapitalMap.put(india,"Delhi");

        countryCapitalMap.put(japan,"Tokyo");

       countryCapitalMap.put(france,"Paris");

        countryCapitalMap.put(russia,"Moscow");


So in the above example we have 4 entry objects with 4 key –value pair.

Now we are using put () method to add these objects to a hashmap name countryCapitalmap.
Let look inside code of put() method

 public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
 
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }


First ,hashcode method calculates hashcode of key .
This hashcode actually indicates the index of array which stores entry objects.
The objects are stored in a single link list corresponding to each index which is also konwn as bucket
If two keys have same hashcode that means they will stored on the same index but in the same bucket or linked list .

Let us assume that we have four values in our hashmap.




        countryCapitalMap.put(india,"Delhi");

        countryCapitalMap.put(japan,"Tokyo");

       countryCapitalMap.put(france,"Paris");

        countryCapitalMap.put(russia,"Moscow");



And assume that hascode calculated on each key comes as
                                           India ->0
                                           Japan ->0
                                           France->1
                                           Russia ->2
                                           China->2



hashmap Internal working
Hashmap Internal working


By default the size of hashmap is 16 that means there will be 16 buckets and 16 indexes .Here I have shown only 5.
Each node of a link list stores an Entry object which conatins following things




Key
Value
Next
hash










Above for illustration purposes I have shown only key.


So as india’s hashcode comes as 0and japan’s also 0 ,so the entry object corresponding to india will be stored in first node of linked list at 0 index and as entry object corresponding to japan also have same hashcode so it will stored in the next node to india and next pointer of india will point to japan’s entry object.


You will be confused that when hashcode of both keys is same then the value of india entry object should be replaced no but when hashcode of two entry objects Is same at that time equals() method comes into play .when we have to store key with same hashcode then first equals method checks whether the key for which value is to be stored and the key which is already present in hashmap is same ,if both are same then the value in entry object  is replaced by new value otherwise a new node is created and the new entry object( japan in our case) is stored.

Working of Get method in hashmap

Get method in hashmap is used to retrieve value from hashmap corresponding to a key.


Code of method get () of HashMap:

public V get(Object key) {

20
  if (key == null)

21
   return getForNullKey();

22
  int hash = hash(key.hashCode());

23
  for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e =     e.next) {

24
   Object k;

25
   if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

26
    return e.value;

27
  }

28
  return null;

29
 }

First, same as put method , hashcode of key is calculated .
Then according to hashcode the index in array means index of bucket in which value/entry object is stored.
If there is only one node in the bucket/link list then the value is retrieved from that node.
If there are more than one node in the linklist then  equals() method comes into play .equals( ) methods traverse the list and compare value of each key present in bucket with the one for which we have to retrieve value  and retrieves value from entry object .


Author : Himanshu Bector