Monday, 5 February 2018

Quetions


Below are some of the questions they asked when I attended at 3+ years of experience.
1. Explain your Application architecture
2. Find Length of string without using length()
3. What is a Serializable interface?
4. What is a Transient variable?
5. Sample program for linked list implementation. Which is preferred arraylist or linkedlist? 
6. Program to find the number of occurrences of a character in a file.
7. Why do we go for jpa and ejb? Can we use any other framework?
8. Which is the package you are familiar with?
9. How to find number of active user sessions?
10. How to lock a class? What are the ways to achieve synchronization?
11. What are inner classes and what are the types?
12. What is a singleton pattern and explain its real time usage.
13. Why you are looking for a job change?
14. Where the configuration files are stored in your application?
15. Rate yourself in java out of 10.
16. How do you map entity and table?
17. Explain sample architecture for retrieving employee details from table.
18. How quickly you could adapt if you have been put in spring and hibernate?



1)Explain your Application architecture


applications architecture describes the behavior of applications used in a business, focused on how they interact with each other and with users. It is focused on the data consumed and produced by applications rather than their internal structure

n the basis of business and functional requirements

involves defining the interaction between application packages, databases,

2. Find Length of string without using length()

String blah = "HellO";
int count = 0;
for (char c : blah.toCharArray()) {
    count++;
}
System.out.println("blah's length: " + count);


str.lastIndexOf("")


  public static int getLengthOfString(String str)
  {
    int i=0;
  try{
   for(i=0;;i++)
   {
    str.charAt(i);
   }
  
  }
  catch(Exception e)
  {
  
  }
  return i;
}




----------
3. What is a Serializable interface?

https://www.javatpoint.com/serialization-in-java

Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization.

It is mainly used to travel object's state on the network 

used when there is need to send your data over network or to store in files. By data I mean objects and not text.

Deserialization is the process of reconstructing the object from the serialized state

  1. import java.io.Serializable;  
  2. public class Student implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  public Student(int id, String name) {  
  6.   this.id = id;  
  7.   this.name = name;  
  8.  }  
  9. }
-----

  1. import java.io.*;  
  2. class Persist{  
  3.  public static void main(String args[])throws Exception{  
  4.   Student s1 =new Student(211,"ravi");  
  5.   
  6.   FileOutputStream fout=new FileOutputStream("f.txt");  
  7.   ObjectOutputStream out=new ObjectOutputStream(fout);  
  8.   
  9.   out.writeObject(s1);  
  10.   out.flush();  
  11.   System.out.println("success");  
  12.  }  
  13. }  

Can you Serialize static variables?

Answer :
No,you can’t.As you know static variable are at class level not at object level and you serialize a object so you can’t serialize static variables.
-----
--------
5. Sample program for linked list implementation. Which is preferred arraylist or linkedlist? 

https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist

LinkedList and ArrayList are two different implementations of the List interface. LinkedListimplements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

  • get(int index) is O(n/4) average
  • add(E element) is O(1)
  • add(int index, E element) is O(n/4) average
         but O(1) when index = 0 <--- main benefit of LinkedList<E>
  • remove(int index) is O(n/4) average
  • Iterator.remove() is O(1) <--- main benefit of LinkedList<E>
  • ListIterator.add(E element) is O(1) <--- main benefit of LinkedList<E>
Note: O(n/4) is average, O(1) best case (e.g. index = 0), O(n/2) worst case (middle of list)
  • get(int index) is O(1) <--- main benefit of ArrayList<E>
  • add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
  • add(int index, E element) is O(n/2) average
  • remove(int index) is O(n/2) average
  • Iterator.remove() is O(n/2) average
  • ListIterator.add(E element) is O(n/2) average


ArrayList is what you want

Why LinkedList sucks:
  • Getting good performance is tricky.
  • Any indexed operation requires a traversal,

It uses lots of small memory objects
ArrayLists are good for write-once-read-many or appenders, but bad at add/remove from the front or middle.
---------

http://sampleprogramz.com/java/linkedlist.php

nkedList_Ex1.java

import java.util.LinkedList;
import java.util.Scanner;
 
public class LinkedList_Ex1 {
 
 Scanner scan;
 LinkedList<String> list;
 
 int n;
 
 void getVal() {
  
  scan = new Scanner(System.in);
  list = new LinkedList<String>();
  
  System.out.println("Linked List - Create & Insert");
  
  System.out.println("\nEnter 'n' value");
  n = scan.nextInt();
  
  System.out.println("Enter the data");
 
  for(int i=0; i<n; i++) {
   
   list.add(scan.next());
  }
 }
 
 void display() {
  
  System.out.println("\nThe Linked List");
 
  for(int i=0; i<list.size(); i++) {
   
   System.out.println(list.get(i));
  }
 }
}
 
class MainClass {
 
 public static void main(String args[]) {
  
  LinkedList_Ex1 obj = new LinkedList_Ex1();
  
  obj.getVal();
  obj.display();
 }
}

void AddFirst() {
  
  System.out.println("\nAdd First");
  System.out.println("Enter the data");
  String item = scan.next();
  
  list.addFirst(item);
  
  display();
 }
 
 void RemoveFirst() {
  
  System.out.println("\nRemove First");
  
  list.removeFirst();
  
  display();
 }
----------

6. Program to find the number of occurrences of a character in a file.

int count = 0;
02        String str = "abbaaaesaiejsaieas";
03        char ch = 'b';
04         
05        for (int i = 0; i < str.length();i++)
06            if (str.charAt(i) == ch)
07                count++;
08         
09        System.out.println(count);

-----
https://codereview.stackexchange.com/questions/47704/counting-characters-in-a-text-file

ublic class CountLetters {
    // Throwing Exception is too general, you should throw IOException
    public static void main(String[] args) throws Exception {
        // It is better practice to define Map, instead of TreeMap
        // The name of variable hashMap could be better, for example characterMap or characters
        TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();
        File file = new File("C:/text.txt");
        Scanner scanner = new Scanner(file,"utf-8");

        while (scanner.hasNext()) {
            char[] chars = scanner.nextLine().toLowerCase().toCharArray();
            for (Character c : chars) {
                if(!Character.isLetter(c)){
                    // 'continue' is unnecessary as last statement in a loop
                    // It is better to put following 'else if' and 'else' here and to remove negation in condition
                    // like this: if(Character.isLetter(c)){ if ( ... ) { ... } else { ... } }
                    continue;
                }
                else if (hashMap.containsKey(c)) {
                    hashMap.put(c, hashMap.get(c) + 1);
                } else {
                    hashMap.put(c, 1);
                }
            }
        }

        // You should call scanner.close() here

        // I would wrap this into if (!hashMap.isEmpty()) { ... }, but it is not really needed
        for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
--------
class GFG
{
    // Method that return count of the given
    // character in the string
    public static int count(String s, char c)
    {
        int res = 0;
 
        for (int i=0; i<s.length(); i++)
        {
            // checking character in string
            if (s.charAt(i) == c)
            res++;
        }
        return res;
    }
     
    // Driver method
    public static void main(String args[])
    {
        String str= "geeksforgeeks";
        char c = 'e';
        System.out.println(count(str, c));
    }
}


---------

8. Which is the package you are familiar with?

String,StringBuffer and StringBuilder : for string processing can use them efficiently.
System: In and out streams
Exception: Exception handling
Thread: Multi threading
ArrayList: Dynamic array
HashMap: Key-Value pair
Date,SimpleDateFormat: Date and time processing


----------
9. How to find number of active user sessions?

http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html

package com.hubberspot.javaee.listener;
 
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
@WebListener
public class OnlineUsersCounter implements HttpSessionListener {
 
 private static int numberOfUsersOnline;
  
 public OnlineUsersCounter() {
  numberOfUsersOnline = 0;
 }
  
 public static int getNumberOfUsersOnline() {
  return numberOfUsersOnline;
 }
  
    public void sessionCreated(HttpSessionEvent event) {
 
     System.out.println("Session created by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline++;
  }
      
    }
 
    public void sessionDestroyed(HttpSessionEvent event) {
      
     System.out.println("Session destroyed by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline--;
  }
 
    }
  
}
-----

10. How to lock a class? What are the ways to achieve synchronization?

https://howtodoinjava.com/core-java/multi-threading/thread-synchronization-object-level-locking-and-class-level-locking/


Object level locking

Object level locking is mechanism when you want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on given instance of the class.

public class DemoClass
{
    public void demoMethod(){
        synchronized (this)
        {
            //other thread safe code
        }
    }
}

Class level locking

Class level locking prevents multiple threads to enter in synchronized block in any of all available instances on runtime. This means if in runtime there are 100 instances of  DemoClass, then only one thread will be able to execute demoMethod() in any one of instance at a time, and all other instances will be locked for other threads. T

public class DemoClass
{
    public void demoMethod(){
        synchronized (DemoClass.class)
        {
            //other thread safe code
        }
    }
}
 
--------

  1. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.
  2. synchronized keyword can be used only with methods and code blocks. These methods or blocks can be static or non-static both.
  3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves 

---------
11. What are inner classes and what are the types?

https://www.programcreek.com/2009/02/4-inner-classes-tutorial-examples/

1. Static Nested Classes
2. Member Inner Class
Method-Local Inner Classes
Anonymous Inner Classes
----------

12. What is a singleton pattern and explain its real time usage.

Typically singletons are used for global configuration. 

he simplest example would be LogManager


Singletons are useful only when you need one instance of a class and it is undesirable to have more than one instance of a class. 

Singleton usually means having a class of which only one instance can exist. 

https://www.javatpoint.com/q/5299/how-to-use-singleton-class-in-realtime-?

// File Name: Singleton.java 
public class Singleton { 

private static Singleton singleton = new Singleton( ); 

/* A private Constructor prevents any other 
* class from instantiating. 
*/ 
private Singleton(){ } 

/* Static 'instance' method */ 
public static Singleton getInstance( ) { 
return singleton; 

/* Other methods protected by singleton-ness */ 
protected static void demoMethod( ) { 
System.out.println("demoMethod for singleton"); 


Here is the main program file where we will create singleton object: 

// File Name: SingletonDemo.java 
public class SingletonDemo { 
public static void main(String[] args) { 
Singleton tmp = Singleton.getInstance( ); 
tmp.demoMethod( ); 


This would produce the following result: 

demoMethod for singleton
-----

14. Where the configuration files are stored in your application?

WEB-INF is a good place to put your config file.
Putting it in WEB-INF will hide the XML file from users who try to access it directly through a URL
--------

16. How do you map entity and table?

17. Explain sample architecture for retrieving employee details from table.

https://www.upwork.com/i/interview-questions/sql/
---------
----------
1

9. What is WSDL? What is the advantage of webservices?



1) SOAP was designed for a distributed computing environment where as REST was designed for a point to point environment.

he Web Services Description Language (WSDL /ˈwɪz dəl/) is an XML-based interface definition language that is used for describing the functionality offered by a web service.



Web services allow various applications to talk to each other and share data and services among themselves.

Standardized Protocol

Web services use standardized industry standard protocol

Low Cost Communication

Web services use SOAP over HTTP protocol,
-----
--------
---------
----------
-----
--------
---------
----------
-----
--------
---------
----------
-----
--------
---------
----------
-----
--------
---------
----------
-----
--------
---------







No comments:

Post a Comment