Thursday, December 21, 2017

Interview Questions


Q: What is the library you used in spring to connect to database?
Spring JDBC template.

Q: What and all involved in fetching the data from database in spring project like what are all the layers included,
Ans:  Call from UI to controller -> Service - layer -- Dao layer -- accessing the entity using SpringDATA JPA -> and spring JDBC template to access the actual Database table..
Q: What is Flux?
Ans: It is an architecture, one way data flow, It places focus on creating explicit and understandable update paths to the application.

 users: tracing changes during development simpler.
           bugs easier to track down and fix.

A simple flux flow.
In typical MVC architecture, an event on view triggers code in controller, controller knows how to coordinate changes to one or more models by calling methods on the models. When the model change, they notify one or more views, which in turn read the new data from the models and update
themselves.

Store : contains business logic.
The action dispatches from the Dispatcher to Store tell only "What happened" but do not describe how the application state changes.

Question: What is the disadvantage of MVC, why we need single flow of data?
Ans:
As MVC application grows controllers and models and views added, the dependencies become more complex. A user interaction will trigger updates which in turn trigger additional updates, resulting error-prone and difficult to debug, some times overlapping paths etc..

What is Reducer?
A pure function that takes the previous state and an action, and returns the next state. function(state,action) => newState

A reducer should follow these
1) No side effects, no api calls, no mutations, calling non-pure functions.(Date.now() or Math.random()).
how to stop mutating the data? use Object.assign () or Object spread (...) operator..

A simple flux flow:
   
Q) What is Dumb and Smart components?
A dumb component also called presentational components, their own responsibility is to present something to DOM. These components only have render method, and they do not have state to manage, they do not know how to change the data they are presenting.

Smart component also called container components, has state associated with them and pass the data down to the presentational components as props, they are class based components and have their own state defined in their constructor functions.

class App extends Component {
constructor(props) {
super(props);
this.state = {pictures : []};
}
}
The root component off an app is an smart component.
Question: why we need SASS?
Ans:
Writing CSS on complex large web applications is tough, SASS can help you on this aspect.
It allows you to use variable, functions, mixins, loops, mathematical operations and imports.
SASS - syntactically awesome style sheets that allows you to use the above features, to make CSS much powerful. SASS is a css - preprocessor

SASS - compiler  - css file.

Features:
a variable can be declared by using $ and it can be used through out SASS files.

mixins :
if you have block of code repeating more than once in stylesheet, you can use mixins in that case.
mixins are like functions in programming language, they can take parameters and can include default values.
Smaple mixin:

@mixin set-font( $family: 'Ubuntu' , $weight: 400 , $style: normal ) {
  font-family: $family , 'Arial', 'Helvetica', sans-serif;
  font-style: $style;
  font-weight: $weight;
}
usage of above mixin from css:
h1 {
  @include set-font;
  color: $blue;
}

@import feature:
@import feature allows you to modularize you css by importing smaller SASS files.
this @import is different from import with CSS, since @import at SASS combine all @import's will be merged into a single CSS file and make only one HTTP call to get imported into the file.

the  multiple imports for css file on a traditional css file will make multiple HTTP calls.



@import "source/font-awesome";           
@import "source/slick";                         
@import "framework/bootstrap";  
@import "my-custom-theme";   
Question : what are the different syntax files available with SASS
a) *.sass and *.scss
scss - sassy css - is a css file enhanced with sass features and it is new way of using sass features.
sass - is bit old way writing sass file, like it uses intendation rather then brackets to indicate nesting and newlines rather semicolon to separate properties.

Q) what is the difference between @include and @import?
@include only for including mixins and @import is for importing the whole file.
Some of the Java8 features?
Ans:
1) lambda Expressions
2) Method references
3) Optional
4) Functional Interfaces
5) Default Methods
6) Stream API.

Method References:
1) A method reference is the shorthand syntax for a lambda expression that executes just one method.

Syntax : Object :: methodName.

Turns the below lambda expression into method reference.
Consumer c = s->System.out.println(s);
Consumer c = System.out::println;

Method references are useful to replace the a single method lambda expression.

types of method reference:
It can refer to a static method, to instance method of an object of particular type, instance of existing object and to a constructor.
Syntax to call instance method of an object of particular type:

ObjectType:instanceMethod.

In general, we don't have to pass the arguments to method references.

Jasmine framework vs Mocha Test runner.

1) Jasmine(framework) has assertion library. Mocha(test runner) does not have it , we've to use Chai for this.
2) test doubles .. Jasmine has default SPY to mock the actual functions from the code. Spied functions does not call the original functions
by default, if you want to call, you have to call it explicitly by doing through spyOn(user,'isValid').andCallThrough().

   In Mocha we have to use third party test double library called Sinon to mock the original functions from the code, it comes with three flavours 1. SPIES 2. STUBS 3. MOCKS
 
A SPY on Mocha Sinon calles the original method in contrast to SPY in Jasmine where it does not calls.
Stub from the Sinon from Mocha exactly similar to SPY from the jasmine, original method not called.
A SPY on jasmine we need to call done() explicitly, but this is not the case with SPY from Mocha.

Additionally Sinon can be used for Fake server, which is not with the Jasmine.
Fake server allows to fake the responses to the AJAX requests.


Sinon fake server similar to $httpBackend in angular mocks.

Q: How to setup a spring project to use Queueing solutions?

1) add two dependencies to your project 1. Spring-jms(4.3.9) and javax.jms(2.0.1)

We need a JMSTemplate class to create producer and consumer resource. In order this producer and consumer send and receive the messages
they need a connection factory. There are two implementations of the connectionFactory interface a) SingleConnectionFactory
b) CachingConnectionFactory. Difference between these is CachingConnectionFactory extends SingleConnectionFactory and adds extra
functionality to cache sessions along with singleconnection property from the SingleConnectionFactory.
By default only one session will be cached, if you want you can configure it.

While Creating the any of the implementations of the connectionFactory, we can tell what type of connection we need Queue or topic.
these types are included the javax.jms those are QueueConnectionFactory or TopicConnectionFactory.


JavaScript API integration testing?

White box testing is the one where the mock data is used as response.
Black Box testing is the one where the actual call happen and real data gets back as response.

IN JASMINE:

When you want to test the REST API through white box testing the best option is to use sinon and rewire.

When you want to test the REST API by making actual call to the REST API in jasmine you can use frisby npm module.

IN MOCHA:

When you want to test the REST API through white box testing the best option is to use sinon.

When you want to test the REST API by making actual call to the REST API you can "supertest-as-promised" npm module.

Because this module gives a promise so that you can call then or catch to get the response.

What is the difference between MOCK and SPY?

Mock is more friendly for unit testing where it replace the mocked class entirely and return the recorded or default
values.

SPY: takes existing object/class and replace only some methods useful with big classes/objects.
When you spy real methods will methods will get called if you do not stub them.


Some of the ES6 features;
1) Arrows these are similar to functions expect the same lexical this as their surrounding code.
example:
  var Katie = {
     _name : "Katie",
_friends: [],
printFriends.forEach(f=>
console.log(this._name + "knows" + f));
}
}
where this._name can access the name "Katie" means this under the arrow function has lexically bounded to the surrounding code.

2) Template Strings:
var name = "Katie";
console.log('Hi',${name}) // prints Hi Kati

3)Promise

4)Classes

5) Modules

6) let and const statement:

Ans: let statements are block scoped.
example :
 function f() {
           //first block begins here
   let firstBlock = "firstBlock";
   {
    //second block starts here
let secondBlock = "second Block"
}
let firstBlock = "firstBlock defining and  assigning again"; // throws error
         }
Error:
VM287:8 Uncaught SyntaxError: Identifier 'firstBlock' has already been declared
    at :1:1

1) How to order the messages in active MQ.
  Issue: user would like to consume messages from the queue in the same order the messages have been placed there by a producer.

  If only single producer writes to the given queue and only single consumer reads from the queue, then ACTIVEMQ will preserve the order in which the messages arrived to the broker.  No configuration are required in this scenario.

  If you would like to preserve the message ordering with multiple consumers reading from the same queue, consider using Exclusive Consumer or JMS message Groups.


queue = new ActiveMQQueue("TEST.QUEUE?consumer.exclusive=true");

consumer = session.createConsumer(queue);

In the above scenario, the broker will pick up a singleMessageConsumer for a queue to get all the messages in order, if that consumer dies, the broker will get failover and choose another consumer.

2) If you do not follow the JMS transactions what would be consequences.

3) What is the JMS transactions and XA Transactions.
Ans:  Reliable JMS with transactions
A Reliable messaging with JMS means, a message never lost and only delivered once, that is called Exactly_once delivery guarantee.

Reliable messaging depends on the following two parameters.
a)  Whether or not messages are stored on the JMS server.
b)  Which acknowledge mode used by the receiver.

Acknowledgement of a message from the receiver leads to deletion of the message from the JMS server.

Different types of Acknowledgment modes:
1) Automatic_acknowledge mode 2) Explicit acknowledge mode 3) Transactional acknowledgment.
Automatic: acknowledgement done as soon as the receiver receives the message.
Explicit: acknowledgment has to be done explicitly, from the receiver through programmatically.
Transactional: if the receiver receives message within the scope of JTA, then acknowledgment done,
if and only if that transaction commits.

for a reliable messaging, we need both the persistence and transaction ack mode.

4) what is the configuration parameter for Active MQ for ordering the messages in queue.

5) What is build agent in Jenkins?

6) Mention some parameters in ACTIVEMQ in detail?
Ans:


What are the disadvantages of the React.JS?
1) Poor Documentation
2) High pace of development.
3) Component re-usability.


What is React is so special about it?
React a Declarative way of doing the things, it is like saying to your application "It should look like this".
In Contrast to Imperative programming saying to application that "This is what you should do".

The declarative way separates concerns..

What is JSX?
A statically typed , Object Oriented programming.
Faster:
It do optimization while compiling the source code to JavaScript.
Safer:
The Quality is higher since most of the errors caught during the compilation process.

Write a Promise ?
const wait = time => new Promise((resolve) => setTimeout(resolve,time));
wait(3000).then(()=> console.log('hii'));

A promise is settled means it is either resolved or rejected. Once settled the promise cannot be resettled again.
That's the immutability of the promise. A settled promise must have a value even 'undefined', but that value
must not change.

Explain about the closure?
Ans: Example of Closure:
A closure is "a function having access to the parent scope, even after the parent function is closed".
1) Is a mechanism to declare "private" variables in JavaScript.

  a) in the below example privateCounter is a private variable and changeBy is a private function.
  these must be accessed directly from the three public functions that are returned from the anonymous wrapper.

  Using closures below way is known as modular pattern.

var counter = (function() {
 var privateCounter = 0;

  function changeBy(val) {
privateCounter += val;
  }

  return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();

A closure in equivalent arrow function:

var counter = (() => {
 var privateCounter = 0;

  function changeBy(val) {
privateCounter += val;
  }

  return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();

b) A closure has access to outer function variables by reference.

c) A closure has access to outer function's variables even after the outer function returns.
Example:

What are the problems with Closures:

Ans: Creating closures in loops.

use let keyword by ES6/ES2015 to avoid this problem.

? What are the different approached to make suer Zero Down time micro service deployment?
Ans: Approach 1: make exact similar environment to production deploy the new micro services init and route the requests.
Approach 2: Segregate the requests into 2 groups based on the client number or client region.
slowly remove the clients from one of the group and routed those requests to the new service.

?Reasons to hate the JavaScript
typeof operator because typeof NAN is a number and typeof null is a object.
changing the syntax every day almost.
closures in loops and heavy callback functions.

?

? Docker commands in brief
ADD : The ADD instruction will copy new files from and add them to the container's filesystem at path .

CMD: provides defaults for an executing container.(Not: only one CMD for a dockerfile if multiple only
the last CMD will work).

EXPOSE: container listens on the specified network ports at runtime.

COPY: The COPY instruction will copy new files from and add them to the container's filesystem at path

Difference between COPY and ADD?
ADD can be a URL or Archive(Zip) file .

ENV : sets the ENV variable 

FROM: initializes a new build stage and sets the BASE IMAGE for subsequent instructions.

?What is the difference between  mock and spy in Mockito?
Ans: both can be used to mock methods or fields, in mock your are creating complete mock or fake object, while in spy there is a real object and your are just spying or stubbing specific methods on it.

while using mock objects, the default behaviour of the method not doing anything, if you are not stubbing that, simply it is a void method.

While in spying, since it is real method, the real method behaviour method will get called, if you are not stubbing the method.

? What is Capture in Mockito?

? What happens if you have a class with two objects and does not override equals and hashcode methods
and those objects used as keys in hashmap.

? what happens to the 6th tasks if you have 5 threads from the fixed thread pool and submitted the 6 tasks through executor service.
 The 6th task will get executed, as soon as a threads from pool will be running in infinite loop and watching the queue for more tasks.

? Tell me what are the annotations used in many to many relationship with JPA?

@join_table

? How will you debug the JPA queries ?

 basic log level for all messages
log4j.logger.org.hibernate=info

# SQL statements and parameters
log4j.logger.org.hibernate.SQL=debug
log4j.logger.org.hibernate.type.descriptor.sql=trace

? What is the use of Dead letter Queue?

he dead-letter queue (or undelivered-message queue) is the queue to which messages are sent if they cannot be routed to their correct destination. Each queue manager typically has a dead-letter queue.

A dead-letter queue (DLQ), sometimes referred to as an undelivered-message queue, is a holding queue for messages that cannot be
 delivered to their destination queues, for example because the queue does not exist, or because it is full.
 Dead-letter queues are also used at the sending end of a channel, for data-conversion errors..
 Every queue manager in a network typically has a local queue to be used as a dead-letter queue so
 that messages that cannot be delivered to their correct destination can be stored for later retrieval.

Messages can be put on the DLQ by queue managers, message channel agents (MCAs), and applications. All messages on the DLQ must be prefixed with a dead-letter header structure, MQDLH. The Reason field of the MQDLH structure contains a reason code that identifies why the message is on the DLQ.

You should typically define a dead-letter queue for each queue manager. If you do not, and the MCA is unable to put a message, it is left on the transmission queue and the channel is stopped. Also, if fast, non-persistent messages (see Fast, nonpersistent messages ) cannot be delivered, and no dead-letter queue exists on the target system, these messages are discarded.

However, using dead-letter queues can affect the sequence in which messages are delivered, and so you might choose not to use them.

? Can we add payload(body) to the Get Request ?
YES.however You will likely encounter problems if you ever try to take advantage of caching. Proxies are not going to look in the GET body to see
if the parameters have an impact on the response.

? Why SOAP not Rest?

? What is optimistic locking in jPA

? what is mapped entity

The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

In particular, for the code in the question the correct annotations would look like this:

@Entity
public class Company {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
    private List branches;
}

@Entity
public class Branch {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "companyId")
    private Company company;
}

? Which garbage collector java8 uses?
 Parallel GC.
  • Java 7 - Parallel GC
  • Java 8 - Parallel GC
  • Java 9 - G1 GC
  • Java 10 - G1 GC

? What are the advantages of modularisation or micro services?
Ans: Independent, easy and frequent deployment.
Independent Scalability.
High testability due to independence and well defined contract between the services.
Independent technology stacks can be used.
Independence in case of failure. Defective services do not crash the whole application.
Independent and parallel development.

? What are the disadvantages of modularisation or micro services?
    Increased effort for operations, deployment and monitoring
a) A delivery work-flow has to be automated
b) Additional infrastructure necessary for ELK-Stack for distributed logging

Organisational changes to achieve the independence of micro service(technical decisions, conceptions and implementations).

Increased configuration management, for each service we need to create a dedicated build and delivery pipeline.

unsafe distributed communication or HTTP request or response lost due to micro service down.

Performance hit due to HTTP, (de )serialisation  (and network) overhead. Instead of programmatic API calls(in-process)
you have to make HTTP calls(over the wire).

Transaction safety.

Service discovery necessary.

Refactoring cab be hard.Especially when moving code between services you have to change all dependent services.

Keep dependent services compatible when updating the single service is tricky.

best blog to read : https://blog.philipphauer.de/microservices-nutshell-pros-cons/

Q:What is Common Closure Principle(CCP)?
Ans: Classes that change for the same reason should be in the same package.
Services must conform to the Common Closure Principle - things that change together should be packaged together - to ensure that each change affect only one service
http://microservices.io/patterns/decomposition/decompose-by-business-capability.html

Q: Implement a Stack on javascript with the below functions init?
 a) push(item) // item should be pushed
 b) pop();// top item should be popped
 c) inc 4 7 // increment the bottom 4 elements by 7

given function accepts operations which is an array contains the operations // ["push 4", "pop", "push 5", "inc 3 4", "pop"];

solution :
function superStack(operations) {
  //Array is used to implement stack.
    this.items = [];
    let i=0;
    operations.forEach(function(operation,index,array){
var noOfElementsToModify = "";
var numberToAdd  = "";
var itemToPush = "";
        var opr = operation.split(" ")[0];     
        if(operation.split(" ").length > 2){
             noOfElementsToModify = operation.split(" ")[1];
             numberToAdd = operation.split(" ")[2];
        }else if(operation.split(" ").length > 1){
            itemToPush = operation.split(" ")[1];
        }
        switch(opr){
            case 'push': 
                this.items.push(parseInt(itemToPush));
                break;
            case 'pop':
                if(this.items.length == 0)
                    return "Underflow";
                console.log(this.items.pop());
                break;
            case 'inc':
                while(noOfElementsToModify > 0){
                    var elementToModify = this.items[this.items.length - noOfElementsToModify];
this.items[this.items.length - noOfElementsToModify] = parseInt(elementToModify) + parseInt(numberToAdd);
                    noOfElementsToModify = noOfElementsToModify - 1;
                }
                break;
        }
    });
}

What is @media queries in CSS?
Ans: @media CSS at-rule used to apply styles based on the result of one or more media queries.
A media query simply test a device's type, specific characteristic's and environment.

Example : @media screen and (min-width: 900px) {
           article {
      display: flex;
  }
}

Explain a bit about the content negotiation in REST:

1) Content-Type: application/json header element used by the client saying to server that I'm sending payload of type
defined in the Content-Type header element.
If the server not able to understand the content-type it can send 415 status code saying Unsupported media type.

2) Accept:application/json in the HTTP request header by the client saying to server that I'm gonna accept the type
of data specified in the Accept header element.
If the server not able to send the response back in the format specified in the Accept header, it can send back 406
status code saying that "Not Acceptable".


What is the difference between 401 & 403 REST HTTP codes?
401(Unauthorized) --- Client provided wrong credentials or none at all.
403(Forbidden):  Client provided correct credentials but he does not have the permissions for the resource.
Means his role is not sufficient to operate on the resource.

What are the drawbacks for REST?
Ans: The point is that REST seems simple but it isn’t – it requires a shift in thinking
(e.g. identifying resources, externalizing the state transitions etc.)

WS-Security & WS-SecureConversation is routable unlike SSL/TLS which is only security mechanism in REST.
WS-SEC* messages can also be partially encrypted, this is not possible with REST.
SSL is point to point cannot be inspected by proxies and violates RESTian principles.

What is HTTP?
Synchronous and request/response protocol.
javascript.txt
Displaying javascript.txt.

Question: What is the difference between TreeMap and LinkedHashMap interms of Performance?

Question: Explain in details about the CountDownLatch?

Question: How the sticy feature at Load Balancer Helps to Horizontal Scaling?

Question: What is FlatMap and how it is Useful in java 8?
we need flatmap because intermediate operations like map and filter cannot work on the nested data,
flatmap useful in removing the nesting on data and make it available for stream operations.
Question: What is common across the Intermediate operations on streams and what are all the terminate operations of the streams?

Question: How will you make thread of your implementation HashMap class where there are more number of Read operations then Write operations.

Question: Explain in details about the Concurrent HashMap?

Question: Explain in detail about the Singleton Design pattern with double check ?

Question: Explain in details about the Strategy pattern?

Question: Which specification of JPA used?
Ans: Hibernate

Question: Which integration used in Spring?
Ans: Active MQ.

Question: What does volatile variable do?
Ans:
1) what are 6 groups of integration design patterns
Ans:
 1) Integration style patterns
 2) Channel Patterns
 3) Message Construction patterns
 4) Routing patterns
 5) Endpoint patterns
 6) Transformation patterns.

2) What are the safe methods in REST?
Ans: Safe methods are HTTP methods which does not change the resource.
GET and HEAD are the safe methods.These methods can be cached and pre-fetched.
No Matter how times you call the below method, it does not modify the resource.
Example : GET /order/123 HTTP/1.1

2.1) What is idempotent?
Ans:  Idempotent methods change the resource in server everytime you call them,
but does returns the end result always same.
Example:  int value = 56;
No matter, how many times you execute the above statement, everytime it changes the value to 56 and the end result will always be 56.

3) What are the elements in XSLT?
a)
   apply-imports,
  apply-templates,
  attribute,
  attribute-set,
  choose,
  if,
  import,
  include,
  message,
  otherwise,
  sort,
  when
  when-param.

4) What are main 4 elements in SOAP?
Ans:
 1) soap-envelope :This element defines the XML document as SOAP message.
 2) soap-header: is Optional and contains the information like Authentication & payment etc.
 3) soap-body: The Mandatory element contains the actual soap message.
 4) soap-fault: An Optional element used to indicate the error message.

5) 4 characteristics of REST?
 1) uniform-interface: Individual resources are identified in requests using URI's
     as resource identifiers. Separates the client from server.
2)  Stateless: Necessary state to handle the request contained in the request itself.
3)  Cacheable: Clients can catch the response.
4)  Client-server:
5) Layered System: Client may not be connected directly to the server.

Question: Difference between resource and state?
Ans: Application state could be data that could vary by client and per request.
Resource state : is constant across every client.

6) What are the minimum things you need to know to develop a API integration framework.

7)  difference between  idempotent and safe?

8) Step by step WSO2 media sequences?
9) what are all the methods of HTTP?
10) What are the optional and mandatory elements of SOAP?
11) java 8 features?

1) What are the different Bean scopes in Spring.
Ans:
  1.      Singleton
  2.      prototype
  3.      request 
  4.      session.

2) what is meant by dependency injection
Ans:
     A class should not be configure itself but should be configured from outside. A design based on the independent classes / components increases re-usability and possibility to test the software.

3) How @Autowire works in Spring
Ans:
    Autowiring happens by placing the instance of one bean into the desired field in an instance of
another bean. All these beans are managed and they live inside a container called application context.

4) Suppose in the below scenario how will you specify which implementation of interface should be      Autowire for your class.

Scenario:

public class Customer {

 @Autowired
 private Person person;
 //...
}
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">



 <bean id="customer" class="com.bbc.common.Customer" />

 <bean id="john" class="com.bbc.common.Person" >
  <property name="name" value="kent" />
 </bean>

 <bean id="smith" class="com.bbc.common.Person" >
  <property name="name" value="gibbs" />
 </bean>
 </beans>  
Ans:
  You need @Qualifier to tell the spring about which bean should autowired.

public class Customer {

 @Autowired
 @Qualifier("smith")
 private Person person;
 //...
}
Question : How will you your object as key in Hashmap ?
Ans:
      Apart from implementing the equals and Hashcode method, make this class as immutable so
that properties of the instance not gonna change for ever once created.

Question: Where are the local variables in java stored ?
Ans:
       Stack.

Question: When the collision occurs in HashMap how the HashMap behaves
 Ans:
      Hashmap creates Linkedlist to store all the key value pairs upon collision.

8)  What is the difference between the Docker image and Docker container?
Ans:
  1.        Simply, A docker image is like a class in java, whereas a docker         
  2.       A Docker container is like a instance(object) in java. 
  3.       A docker container is a run time instance of an image.
  4.       A docker image is a immutable.
  5.       A docker container is active in state when running or not active when it is  not, simply it             has state associted with it.
  6.       An image can be created from container by passing the container id.
  7.       Changes made to the image when it  running inside container cannot be 
  8.       preserved, in order to get those changes you need to create a new        
  9.       image out of the container.
  10.      A docker container is like a process where it can be started or restarted. 
Question: what is Docker File?
Ans:  A Docker image is built up from a series of layers. Each layer represents an instruction in the image's Docker file. The last layer from the Docker file should contains the Read only command.

Sample Docker file:
line 1: FROM ubuntu:15.04 // starts out creating a new layer from ubuntu i'age.
line 2:  COPY . /app //add some file from the Docker clients current directory.
line 3:  RUN make /app //builds your application using the make command.
line 4: CMD python /app/python.py //Tell what command to run within container.

Q:  How the TDD way of developing process works.

  Q: How will you specify VM arguments to Docker?
Ans:  docker run ... tomcat sh -c 'export JAVA_OPTS="$JAVA_OPTS --

Q: What is box model in CSS?
Ans: All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.

Q: Which Jenkins plugin used to analyse the code coverage?
Ans: Jacoco

Q: Suppose you are reviewing the code, if you see lot of imports on java Class, what you are going to recommend to the developer in order to make if efficient?

Ans: My answer, lot of imports in class means it is doing lot of work, clearly violating Single Responsibility principle in Java


2) What is the difference between collections.synchronizemap and concurrentHashmap. Scenario's where you prefer to use other?
Synchronized HashMap
  1. Each method is synchronized using an object level lock. So the get and put methods on synchMap acquire a lock.
  2. Locking the entire collection is a performance overhead. While one thread holds on to the lock, no other thread can use the collection.
ConcurrentHashMap was introduced in JDK 5.
  1. There is no locking at the object level,The locking is at a much finer granularity. For a ConcurrentHashMap, the locks may be at a hashmap bucket level.
  2. The effect of lower level locking is that you can have concurrent readers and writers which is not possible for synchronized collections. This leads to much more scalability.
  3. ConcurrentHashMap does not throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.

3) Can we mock private methods ? if yes, how to mock.
With Mockito it is not possible to mock the private methods but with powermock we can mock the private methods. Because the stand point testing of private methods does not exists.
It requires hacking of classloaders and those are never bullet proof.
finally always think in terms of Objects not in terms of methods.
4) Can we mock private objects ?if yes, how?
5) What is the difference between hibernate get and load methods?
6) What is race condition? is volatile keywords avoid race conditions if yes, how?
7) What is maven dependency management and maven dependency tree?
Ans: Dependency defined under a parent pom using tag can be used in 
        child project without specifying the version details.

Example : a parent pom...

  
    
      junit
junit 3.8 a child pom
 
    
      junit
junit So, in short Dependency management allows to consolidate and centralize the management of dependency versions which can be used by all child projects.

The Maven dependency:tree is useful plugin where it shows where all those jars are coming up in our maven projects.
8) what is race condition?
         A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
9) Criteria to make a monolithic webapp to micro-services?
10) Why Ejb 3.0 is useful, in terms how you use this to access the dao layer pojos.
11) What would happen when you return String from a method whose return type is ModelAndview.
12) What is npm?
Ans: Node package manager
13) What are the different types of CDN exists?
Ans:  p2p and private/peer CDN's
example of p2p is bittorrent where a file will get downloaded from different computers. No security on this.
private CDN's: like Akamai, they works with the peers which they have complete control on the peers.
14) What are the advantages of AWS.
Ans:

What is this function called?
Q1: (function(){ var a = b = 3;});
console.log('a is defined:"+typeof a == 'undefined');
console.log('b is defined:"+typeof b == 'undefined');

Ans: Immediately invoked function expression(IIFE).
Ans: false, true.

What is function hoisting?
Ans: a variable or functions can be used before they do not even exist. but a function which is assigned to a variable is eligible for hoisting.

Mention the two paradigms in Javascript.
Ans:  Object oriented and functional

What are the pros and cons of functional programming?
Ans:  state does not exist:
functions does not change and data is immutable.
Cons:
Functional programming requires lot of memory, because always create new objects .

Q: Explain about the prototype in Javascript.
Ans: A prototype is an object, every java script Object has a prototype.
Object.prototype is top on this prototype chain.
Suppose an object created with new operator or literal then it gets the object.prototype has his prototype.
Suppose an Object created with new Date() will get the Date.prototype.

Q:What is the difference between Class and prototype inheritance?
So, each and every java script has a link to prototype object and this continues till the end of Object.prototype
example object has properties a and b and got the other two properties c and d from some other object and they place in prototype of the object c.
call c.c checks first in own properties of object c, not found then check in prototype of the object c.
here the prototype object of object c has that property, so it get returned. if not, it calls c.prototype.prototype.prototype till it reaches the null.

Suppose take a function act as constructor to create person object.
// Person object constructor
var Person = function(name, age, city, state, country){
    this.name = name;
    this.age = age;
    this.city = city;
    this.state = state;
    this.country = country;
    this.salutation = function(){
        return "Hi! My name is " + this.name + " and I am " + this.age + " years old.";
    }
}
So, every time you create a new object for person, we are going to get a copy of the object with all the properties and methods copied, though it does not matter weather you use it or not, those will be copied.
if you are more concern about the memory and do not want unnecessary copy of the properties or methods, then remove those things from the constructor and put in prototype.

in this case, I am going to remove salutation method out from the constructor and put it in prototype to save some sort of memory.Now the constructor looks like this.
// Person object constructor
var Person = function(name, age, city, state, country){
    this.name = name;
    this.age = age;
    this.city = city;
    this.state = state;
    this.country = country;
    
}  
Person.prototype.salutation = function(){
    return 'Hi! My name is ' + this.name + ' and I am ' + this.age + ' years old.';
};
using prototype keeps only one copy of the method salutation and that can be called by any person object using the prototype chaining, in this way it saves memory.

So, the only difference between classical vs prototype inheritance is Memory consumption.

Does ES6 allows inheritance?
Ans: Yes, using extends keyword.

Does javascript compiles? No, it's interpreted.

What is the difference between Mocha and jasmine?
Ans:
Jasmine is complete framework contains spies, stubs, assertion library, istanbul coverage reporter, mocks everything required for complete testing framework.

Mocha, does not have assertion library or spies but we can have Chai for it.
We can use sinon as a spy framework.
Istanbul coverage support mocha as well now.

Problem with Jasmine. if you observe the below test
this.spy = spyOn(countryDB, 'isValidCountry').andCallThrough();
it('should have been called', function(done){
  expect(this.spy.callCount).toEqual(0);
  done();
})



we need to call done() explicity on each and every test on jasmine,but if you have a promise, when this promise is has failure then it's(promise) then block is not called, then test done() is not called, so it leads to test failure with generic "Timeout exceeded" message.
In order to come over this, we need to call test's done()  on finally block. Bit annoying.

So, with mocha sinon the test changes like this and note there is no done(), if promises fail's test fail's but not with generic message. Happy coding.
sinon.spy(countryDB, 'isValidCountry');
it('should have been called', function(){
  expect(countryDB.isValidCountry.notCalled);
})



compare  less and sass?
Ans: 

Sass                                                                   Less                                                      

  1. Ruby Based                                                     Constructed in Ruby but ported to Javascript.
  2. $ uses to assign variables                               @ uses to assign variables.
  3. Compass available for mixins                          Preboot.less 
  4. Poor error messages                                       Clear error messages
  5. Poor documentation                                         Good Documentation.

Q: What is bi-directional and uni directional in Javascript?
Ans:
bi-directionally works in this way in MVC.

  1. User types into view input.
  2. MVC framework binds onchange() to update a model.
  3. Ajax request brings in new model data.
  4. MVC framework updates View input's value to match model.


In Flux, it is uni-directional.
  1. The UI would only fire an independent action with type and associated data to a dispatcher.
  2. Dispather would then update the model, the same way any background ajax method would update the model.

Q:  What would be following tags means in CSS Selectors.
Ans: 
div > p : Selects all p elements whose immediate parent is a div element


div + p :   selects all p elements which come right after you close a div tag

    
div ~ p :  Selects all p elements whose one of the previous siblings is a div elements. This implies that all the tags you place after you close a div, so long as they are not enclosed in any other tags, they are selected.

    
please follow this link for better understanding. http://jsfiddle.net/zopeqznc/2/

1) What is the  difference between LinkedList and ArrayList?

2) Does ConcurrentHashMap accepts the null values?

3) Difference between HashMap and ConcurrentHashMap?

4) How can we wait on a Thread to trigger another thread Execution?

5) Can we create a object for Abstract class in java?

6) Some of the important points of Abstract class in Java?
  1. abstract keyword is used to create an abstract class in java.
  2. Abstract class in java can’t be instantiated.
  3. We can use abstract keyword to create an abstract method, an abstract method doesn’t have body.
  4. If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
  5. It’s not necessary to have abstract class to have abstract method. We can mark a class as abstract even if it doesn’t declare any abstract methods.
  6. If abstract class doesn’t have any method implementation, its better to use interface because java doesn’t support multiple class inheritance.
  7. The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.
  8. All the methods in an interface are implicitly abstract unless the interface methods are static or default. Static methods and default methods in interfaces are added in Java 8, for more details read Java 8 interface changes.
  9. Java Abstract class can implement interfaces without even providing the implementation of interface methods.
  10. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.
  11. We can run abstract class in java like any other class if it has main() method.
7) Difference between Abstract class and Interface?

8) What is thread Pool?

9) How will you conclude the optimal ThreadPool size?

10) How many ways of Synchronization possible in java?

11)  What is the difference between traditional databases and NoSQL?

12) Can we create dynamic indexes in manogoDB using java?

13)  What is the path and query parameter in REST?

14)  Difference between set and List?

16) What is functional Interface?

17) what is the multithread framework you come across recently?

18) What are the classes implements the collection framework?

19) What are all the primitive types of java

20) Difference between string buffer and String builder?

21) can we provide default implementation in interface?

22) In the below which one is best to implement the Database collection pool?
a) Concurrent HashMap b) Array  Blocking Queue

23) What is Count Down latch?

Question) What will happen when we execute a java class file.
                a. Static blocks and main() method priorities
                b. What are all the JVM Class loaders
                c. How will you load a class into memory explicitly, have you come across any such situation
                d. JDBC drivers class and ClassForName() method
Ans :  Class Loaders works on the principals called
  a) delegation
  b) Visibility
  c) Uniquiness
Delegation:Delegates the class loading request to parent, if parent not able to find the load the class only.

Visibility : Child can see what and all the classes loaded by the 
parent.Where parent cant see the classes loaded by Child.

Uniquiness : Load class exactly once.

Class loader is a Class in Java.

There are 3 default class loaders in java
1) Bootstrap class Loader : Parent class loader and loads class from the JDK Jar , rt.jar
2) Extension Class loader : Loads classes from the location
jre/lib/ext.
3) Application class loader : loads classes from the Classpath.

Explicitly loading a Class if it already loaded by parent class loader throws an exception called : ClassNotFoundException

Example:
public static void main(String[] args) {   System.out.println("MY Class Loader "+ClassLoaderTest.class.getClassLoader());  try{  Class.forName("com.learning.material.classLoader",true,ClassLoaderTest.class.getClassLoader().getParent());  }catch(ClassNotFoundException cle){   System.out.println("DDD "+cle);  }}
Hierarchy of  of class loading calling
--> Java.lang.Classloader calls the method loadClass() method.
and it internally calls the findClass() and this method find the class then it calls defineClass()

When a Class will be loaded ?
A Class will be loaded as and when then there is a static initializtion.

How class will be intialized?
1) When trying to create a object with new 
2) Class.forName()
3) a static method is called
4) A static Field is initialized 

Q:What are eligibility for the objects to be stored on HashSet?
Ans:  The objects should override the equals and HashCode methods.

Q: which method used to add element in HASHSET?
A: public boolean add() method.

Note : The Keys of Treemap should be able to compare each other,
So, if u use the Custom objects make sure the class implements the Comparator/Comparable interface and Compare/Compare to methods.

Q: How to define good key for a Map?
A: The key should be immutable, means it should change once we kept in HashMap and capable enough to get the Value back from this Key.

Q:How HasCode useful?
A: HashCode is used to get the bucket location.

Q: What is the default  no of segments in Concurrent hashMap?
A: 16 

Q: What is the hashcode for null
A: Zero 

Q: What are the Rules of Object Clone ?
A: cloneObject != originalObject // means both are not referring the same memory location ----> Should be true.
ii) cloneObject.equal(originalObject) // Not a required but good to have
iii) cloneObject.getClass == originalClass.getClass() // Not Required but good to have 

Q: What is volatile in Java?
A: A Volatile keyword in java is an indication to Java Compiler
saying that thread should not cache the value of this variable 
instead it should reads from Main memory.

After Java5 writes to volatile variables happens before any read happens.

Volatile variable cannot be added to method or block in java.

Used mostly while creating the SingleTon Object.

Q: What is happens-before relationship in java?
A: happens-before relationship ensures that content of memory will be communicated to all threads

Q: Can we sychronize on null Object ?
A: NO

Q: Can a volatile variable is null?
A: Yes

Title: How to stop running thread in java?

Ans:

package com.learning;



public class HowToStopRunningThread implements Runnable{



/**

 * How to stop running thread in java

 */

public static volatile boolean blinker;


public static void main(String[] args) {

Thread t = new Thread(new HowToStopRunningThread());

t.start();

HowToStopRunningThread obj =  new HowToStopRunningThread();

obj.stop();

}


public  void stop(){

try{

Thread.sleep(100);

blinker = true;

}catch(InterruptedException ie){

ie.getMessage();
}
}

@Override
public void run() {
while(!blinker){
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
ie.getMessage();
}
}
}
}

Q: Immutable Class in java
A;
package com.learning;

import java.util.Date;

public final class ImmutableClass {

/**
 *  Option 1) Make your class final (Strong immutable)
 *                      (OR) make all the methods of your class as final(Weak Immutable)
 *  Option 2) Make your varibles as private and (do not provide any setters)
 *                (OR) make all fields as final, and you cannot provide the setters for final fields
 */

private String firstName;
private  String secondName;
private  Date dob;

public ImmutableClass(String firstName,String secondName,Date dob){
this.firstName=firstName;
this.secondName=secondName;
this.dob=new Date(dob.getTime());
}

public String getFirstName() {
return firstName;
}

public String getSecondName() {
return secondName;
}

public Date getDob() {
return new Date(dob.getDate());
}

public static void main(String[] args) {
// TODO Auto-generated method stub



}

@Override
public String toString() {
return "ImmutableClass [firstName=" + firstName + ", secondName="
+ secondName + ", dob=" + dob + "]";
}

}
Question : Write a program that should synchronize the threads , thread A and thread B. where thread A should print 5 even numbers and thread B should print 5 odd numbers.?
Ans :
package MyThread;


public class EvenOdd {

 /**
  * @param args
  */
 public static void main(String[] args) {
  EvenOdd EvenOddObject = new EvenOdd();
  ThreadB tb = new ThreadB(EvenOddObject);
  ThreadA ta = new ThreadA(EvenOddObject);
  ta.start();
  tb.start();   
 }
}

class ThreadB extends Thread{
 EvenOdd EvenOddObject;
 ThreadB(EvenOdd obj){
  EvenOddObject = obj;
 }
 public void run(){
  int counter = 1;
  synchronized(EvenOddObject){
  for(int i = 1; i<50; i++){
   if(i%2 != 0){
    System.out.println(" ODD : "+i);
    counter++;
   }if(counter == 5){
    try {
     counter = 1;
     EvenOddObject.wait();
     EvenOddObject.notify();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 }
}
class ThreadA extends Thread
{ 
 EvenOdd EvenOddObject;
 ThreadA(EvenOdd obj){
  EvenOddObject = obj;
 }
 public void run(){
  int counter = 1;
  synchronized(EvenOddObject){
  for(int i = 1; i<50; i++){
   if(i%2 == 0){
    System.out.println(" EVEN : "+i);
    counter++;
   }if(counter == 5){
    try {
     counter = 1;
     EvenOddObject.notify();
     EvenOddObject.wait();
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
  }
 }
}

Question 1 :What is actual use of serialization in Java?
Ans:

Question 2 : Among 4 wine bottles ,one bottle contains Poison, with 2 rats how 
will u find out the poison bottle, the effect of poison takes 1/2 hr.
Ans :
   let the name of the bottles as .. 00 .. 01 .. 10 .. 11
  name of the rates as : 0 , 1 
  Theme : a rat will take the drink the wine if and only if , if it's bit set in the bottle.
 Step 1 : Both the rates will go to first bottle ..( 00 ) no rat will drink that wine,bcz 
 rat 0 bit is 0 only and rat 1 bit is 0 only.. [ only there bit set to '1' then only that rat
will drink that wine ] 

Step2 : Rat 1 will take the drink because it bit set to 1 in the bottle [  01 ]

Step3 : Rat 0 will take the drink because it bit set to 1 in the bottle [  10 ]

Step 4 :  Rat 0 and Rat 1 will both drink those bottle.

Let wait 1/2 hr .. now both rats died, then bottle [ 11 ] contains wine.
if both are alive : no bottle contains poison.
if Rat 0 dies then bottle [ 10 ] contains poison.
if Rat 1 dies then bottle [ 0 1 ] contains poison.

Hope u got it..

Question 3 : we have number of strings , each string contains 
"Name and length of the name" suppose : example strings are : Sachin6,Amazon20,
Cricket21. Here the length for the string amazon and cricket shows wrongly,
it should  be 6 and 7.so, with you program how will u catch these strings
(string with wrong length).

Question 4 : If a super class has a method " m1()"  and it throws an exception 
of type Exception. And in the subclass over-riden method throws IOException , 
is it possible in Java?

Ans : It is not possible in Java. Because if the overriden function has thrown the 
any checked exception. Then you are not allowed to throw any new Checked Exception 
from sub class.
so here in this case your super class overriden method m1() throws the Exception  
as Exception . Because Exception is the super class of all Exceptions it contains both
Checked and UnChecked Exception .so you are not allowed to through any more 
new Checked Exception(IOException ) in this case.

Question 5 : Same as above. but here the Subclass throws exception of type Exception.
and super class throws Exception of type IOException. Does it allowed in Java?

Ans : Same reason as above if the super class method throws the Exception as
IOException then u'r sub class not allowed to throw any new checked exception. 
so this case is also not possible in java.

Question 6 :  Is it possible to have, try -- finally -- finally ?
Ans: No, can have try - frinally or try - catch ..

Question 6 -1 : Is it possible to throw an Exception from catch Block?
Ans: No

Question 7 : Is it possible to have try -- finally -- catch ? if not then y?
Ans: Catch will be unreachable.

Question 8 : Is it possible to write an try catch in constructor ?
Ans: you are free to go..

Question 9:  Can a Constructor throws and Exception in java?
Ans : yes, It can throw an Exception

Question 10 : Is it possible to catch Error in java? if so how we can do that?
Ans : we can like catch(throwable t) , but it is not good.

Question What will happen if you written 'System.exit(1)' in the try block, will 
finally get Called?
Ans: No.

public class First {
public static void main(String[] args) {
try{
System.out.println(" In Try Block, calling System.exit(1)");
System.exit(1);
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println(" Finally Executing Now..");
}
}
O/p: 
         In Try Block, calling System.exit(1)



Question : If the Singleton Design Pattern not allowed to create the object of the class
 more than once, then if you de-serialize the object, it is gonna create a new Object of the Class, then in this case, How will you Preserve the Singleton Pattern of that Class?

Ans :

Question Observe the below code and tell me which method will get called ?

public Bird{
}
public Parrot extends Bird{
}
public TestMe{

public static void main(String[] args){
            Bird b = new Parrot();
            fun(b);
}

fun(Bird b){
       System.out.println("Bird Fun");
}
fun(Parrot p){
       System.out.println("Parrot Fun");
}
}
O/p :
     Bird Fun...

Question: What is the use of SerialVersionId in Serialization Process?
Ans : Read this article :
                                       http://www.javablogging.com/what-is-serialversionuid/


Note of Good Questions in java:
http://extreme-java.blogspot.com/2011/02/25-servlet-interview-questions.html

Question : A Programming Question on Static and Dynamic Polymorphism?
Ans :
       public class Bird {
public static void main(String[] args) {
}

public void fly(){
System.out.println(" A Bird Can Fly");
}
public static void color(){
System.out.println(" Each Bird Will Have a Unique Color");
}
}
-------------------------------------------------------------------------------

public class Parrot extends Bird{

public static void main(String[] args) {
}
public void fly(){
System.out.println(" A Parrot Flies Larger Distances");
}
public static void color(){
System.out.println(" I am a Parrot having Green Color :");
}
}
----------------------------------------------------------------------------------
public class TestClass {
public static void main(String[] args) {
Bird b = new Parrot();  /* Up Casting */
b.fly();
b.color();
}
}


Output :

 Parrot Flies Larger Distances
 Each Bird Will Have a Unique Color

Question : How will you make sure that keys stored in HashMap or not case sensitive?
Ans : Storing keys in HashMap are in case-sensitive in General.

In order to make your case-insensitive keys in HashMap. you need to extends the
HashMap and Overrides the put and get methods.
Below is the case-insensitive HashMap.

import java.util.HashMap;
@SuppressWarnings("serial")
public class HashMapUniqueKey extends HashMap
private static HashMapUniqueKey myMap = new HashMapUniqueKey();
public static void main(String[] args) {
myMap.put("Sekhar","Airvana");
myMap.put("SEKHAR","Airvana Networks ");
System.out.println("   GET Value for Key 'Sekhar' :"+myMap.get("Sekhar"));
System.out.println("   GET Value for Key 'SEKHAR' :"+myMap.get("SEKHAR"));
}
public Object put(String key,Object value){
String key1 = ((String) key).toLowerCase();
System.out.println(" Key1 >> "+key1);
return super.put(key.toLowerCase(), value);  
}
public Object get(String key){
return super.get(key.toLowerCase());
}
}

O/p: 
***************************************************
***   GET Value for Key 'Sekhar' :Airvana Networks 
*** GET Value for Key 'SEKHAR' :Airvana Networks 

***************************************************



                          JAVA Script Object Oriented Concepts

How to create objects in java script

Ans: Objects in java script can be created in two ways
1) using constructor functions:
ex: function Parent()
2) using object literal
Ex: var object1 = {};

All object members are public by default in java script, there is no flexibility to define the private,
protected & package private in java script:

Ex:
   var myObj  =  {
                myProp : 1 ,
                getProp : function () {
                         return this.myProp;
                 }
   };

Ex: The same is true when you create objects with constructor functions
       function Car () {
           this.model =  'Benz' ;
           this.getModel = function () {
                      return this.model;
           };
}

Creating object of the car
var carObject = new Car();
console.log(carObject.model) //  model is public
console.log(carObject.getModel()) // getModel() is public

How to define the private members in an java script object
Ans :
       function Car () {
       //Private variable
         var model = 'Benx';
        this.getName = function () {
           return model;
   };
}

var carObject = new Car();
console.log(carObject.model) // undefined

One DrawBack of the private members when used with constructors is that they are re-created every time the constructor is invoked to create a new object. This is problem with the any members prepended with this keyword on object
example : this.model

In order to eliminate the above problem

you can add common properties and methods to the prototype property of the constructor.

Example : function Car() {
           //private variable
            var model = 'Benz';
          //public function
           this.getModel  = function () {
                  return name;
         };
       }
  Car.prototype = ( function () {
          // private member
          var owner = 'sekhar';
         return {
                 getOwner : function () {
                 return owner;
}};
}());

var myCar = new Car();
console.log(myCar.getModel());
console.log(myCar.getOwner());


Q:  How to create Deadlock between the threads in java?
A:
package com.learning;

public class DeadLockBetweenThreads {

/**
 * @param args
 */
String objectA = new String("OBJECTA");

String objectB = new String("OBJECTB");

Thread thread1 = new Thread("First Thread"){
public void run(){
while(true){
synchronized(objectA){
synchronized(objectB){
System.out.println(objectA+"====="+objectB);
}
}
}
}
};

Thread thread2 = new Thread("Second Thread"){
public void run(){
while(true){
synchronized (objectB) {
synchronized(objectA){
System.out.println(objectB+"******"+objectA);
}

}
}
}
};

public static void main(String[] args) {
DeadLockBetweenThreads obj = new DeadLockBetweenThreads();
obj.thread1.start();
obj.thread2.start();

}



}

Interview with Yatra.com

Hi Friends,
                  Recently I attended an interview with yatra.com, Hyderabad. Here are the some
 questions along with answers I would like tp share with you guys.

Q:  Reverse an Linked list?
A:  Will update soon

Q: How to print level order traversal of a binary tree where each level elements should be on the same line

Ex: Tree
                     5
                /      \
               4         7
            /    \        /  \
            1   2      6   9

O/p should be  :
                  5
               4  7
          1 2 6 9
Ans: Here I am writing this code on java, feel free to post an query/suggestion on this one.

Program:
public void printLevelByLevelBinaryTree(BinaryTreeNode root){
int currentLevelCounter=1;
int nextLevelCounter=0;
BinaryTreeNode node = null;
if(root == null) return;
if(queue.push(root)){
while(!queue.isEmpty()){
node = queue.pop();
currentLevelCounter--;
if(node.left!=null){
queue.push(node.left);nextLevelCounter++;
}
if(node.right!=null){
queue.push(node.right);nextLevelCounter++;
}
System.out.print(node.data+"  ");
if(currentLevelCounter==0){
System.out.println();
currentLevelCounter=nextLevelCounter;
nextLevelCounter=0;
}
}
}
}

Question No : 3 .
            Given a node n and a distance k, print all the node's which are having 
            distance K from this node n.

Ans: will update soon.
Define ThreadLocal?
Ans :  Thread Local can be considered as scope of access like a Thread Scope, request scope and session scope.

What is ThreadLocal?
Ans: Any Object which is set in the Thread local is global and local to the thread which is accessing that thread.

Global access:
                     Value or Object stored in the Thread Local is global to the thread, that means if this thread
calls several methods in several classes. All these methods can see the Thread local variable or object which set by the other methods. We do not need to pass this variables or object between these methods.

Local access:
                  Value or

Why Should we ThreadLocal?

Advantages of ThreadLocal?

Disadvantages of ThreadLocal?

Question : What is Dynamic Binding?
Answer: 
  public Class SuperClass1 {
                public void showDetails(){
               System.out.println("I am in Super Class ");
      }
  }

  public Class subClass1{
               public void showDetails(){
               System.out.println("I am in Sub Class");
    }
 }

Now See this two Calls:
SuperClass1 sp1 = new SuperClass1();

SuperClass1 sb1 = new SubClass1();

Output :
                 I am in Super Class
                 I am in SubClass.

Note: Even though both variable reference of type SuperClass1, but actual Call
take place based on the Object type not on the reference type.
This is called DYNAMIC BINDING.

Static Binding:
Static Methods calls are Static Binding, that's y we cannot override the Static methods.
Similary, access to all member variables allows Static Binding in java

Example : class SuperClass{
                          public String someVariable = "Some Variable in SuperClass";
                   }


class SubClass extends SuperClass{
                   public String someVariable = "Some Variable in SubClass";
              }


SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();

System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);




Output:-
Some Variable in SuperClass
Some Variable in SuperClass

NoteCall to Private Methods resolved at Compile Time Only.
Note: Binding for fields in Java is always static, hence it's based on the declared 
type of the Object Reference Only.

PolyMorphisam:
Polymorphism in Java , has the Capability of Down-casting the Objects Automatically.


Class Animal{
                 public void eat(){
                          System.out.println(" I Eat only Meat");
                     }
                }

Class Dog extends Animal {

                passObject(new Dog());
               passObject(new Animal());

               public void eat(){
              System.out.println(" I Eat Rice Only.");
          }

       }
public void passObject(Animal a){
                 System.out.println(" Eating "+a.eat());
}

OutPut : 
                        I Eat meat only.
                       I Eat Rice Only.

Java Polymorphisam Concept has the Automatic DownCasting....

Hi Friends,
       Today I would like to show up how to create GIT local repository

 Setting up a central repository on your windows machine
1) open command prompt type the below commands:
First of all I would like to add my current eclipse project to git central repository, for that I need a central repository, which is generally located in a server. But I would like to configure that central
repository in my local system it self. Below are the steps which are help me to create a local(central)
repository.

Command 1:  Go to the eclipse project path, which you would like to add to GIT central respository
Command  in command prompt :
command : C:\Users\sekhark\workspace\gitSampleProject>
gitSampleProject is the project I would like to add to the Central repository.

Below command used to create the local central respository

Command :> pushd \\RRR.TT.YY.XXX\Users\sekhark\gitrepo

RRR.TT.YY.XXX : is the ipv4 address of my system-- got it through ipconfig command from cmd.

Above command maps a network drive at some drive.

in my case it is mapped to the directory Y:\sekhark\gitrepo

so this Y:\sekhark\gitrepo serves as local central repository



Question 1 : Explain the hierarchal of Collections in Java?
Answer : Collection [ interface ]
               |
             List [ interface ]  -----------  Set [ interface ]
              |                                            |
            ArrayList | LinkedList            SortedSet [ interface ]
                                                          |
                                               LinkedHashset,HashSet,TreeSet,AbstractSet.
Question : What is AbstractSet class in Java ?
Answer :

Question2 : Write a Sample program Where Volatile variable is useful?

Question 3 :  Tell me what are the methods in Object Class?
Ans : 1) wait()
         2) wait(long timeout)
         3) wait(long timeout, int nanos)
         4) notify()
         5) notifyAll()
         6) hashcode()
         7) getClass()
         8) finalize()
         9)toString()
        10)clone()
        11) equals()

Question 4 : what is the signature of clone method in Object Class?
Ans : protected Object clone() throws CloneNotSupportedException

Question 5 : What is the signature of hashcode method in Object Class?

Ans : public int hashCode().

Question 6 : I have a Class which implements the Clonable interface, but does not 
override the clone method, now if i try to create Object of the class, what will happen?

Answer : When u try to create Object of a class which does not override the clone() method.
then it  throws the checked Exception called " CloneNotSupportedException".
Explanation : 
When we try to clone the object of a class which is not implements the Cloneable 
(marker) interface, then java will assume that this class may through exception
"CloneNotSupportedException".Because any class which does not implement the
Cloneable Interface throws "CloneNotSupportedException".
                                   BUT
Even though a class implements the interface Cloneable but does not Override the
method clone(), then this class is of no use, means this class still throws the "CloneNotSupportedException". 
So, Once a Class implements the Cloneable Interface and Overrides the clone() 
method, it does not through any Exception.Because in Override clone() method
we are returning an Object of the Class by creating a new Object.
Below is the Code for Perfect class which implements Cloneable Interface.


package myPackage;
public class MyCloneNotSupportedException implements Cloneable{

public static void main(String[] args) {

MyCloneNotSupportedException myOb = new MyCloneNotSupportedException();
MyCloneNotSupportedException obj =  myOb.clone();
}
@Override
protected MyCloneNotSupportedException clone(){
return new MyCloneNotSupportedException();
}
}


Question 7 : What is the difference between Hashset and TreeSet?
Ans: HashSet : does not give any sorted order of the elements which we inserted.
       TreeSet  : will sort the elements which we inserted in TreeSet.
       LinkedHashSet : is used to get the elements in the order which we inserted.

Question : What is a final class?
Ans: 1)  A class is final, means we are not allowed to extend that class.
Example:
 String class and System class are final, so we are not allowed to extend that class.
2)  All the methods in the final Class are implicitly final, so we are not allowed to
Override.
3) We are allowed to create an Object of Final Class.

Question Explain about the final variables in Java?
Ans: 
point 1 : Class final variables must be assigned where it is declare.
Example : 
Wrong Statement 1 : public static final int amount;
Above statement gives an error " The blank final field may not have been initialized"
Correct Statement : public static final int amount = 500;
Note: We are not allowed to change value of the class final variable once it got initialized.

Point 2 : Instance final variable must be initialized in the constructor.
Example :
Wrong statement : public final String  myString;
Above statement gives an error " The blank final field may not have been initialized"
Correct Statement :

public final String  myString;
ExtendImmutableClass(String temp){
myString = temp;
}

Question can we have Static Constructors?
Ans: No , Only public,private,protected allowed for a constructor.

Question 8 : How can you make a class immutable ?
Ans : 1) Declare class as final : doen not allow to create an Object of that class.
         2) declare all Instance variables as , private, final variables.
         3) Dont provide any Setters for this Variables.

Q3) Immutable objects are automatically thread-safe –true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
Q4) Which classes in java are immutable?
Ans) All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Q5) What are the advantages of immutability?
Ans) The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
  4) The best use of the immutable objects is as the keys of a map.

Question 9 : Take a sample XML file write the Code to parse it in SAX as Well as DOM parser?

Question 10 : What is XSID ?

Question 11 : Does sax parser need to verify the scheme of the xml File ?
Ans: Yes

Question : What is JDOM Parser ?

Question 12 : Get me the third largest salary of an employee from the salary table ?

Question 13 : What is the difference between HTML and XML File ?

Question 14 : What is the new Features in GWT 2.1 ?

Question 15 : How can you change the Async calls to Sync Calls in GWT ?

Question 16 : What is session tracking in GWT ?

Question 17 : Given a String and Count, print the string count times without using Loop?

Question 18 : Write a program to implement you'r own LinkedList?

Question 19 : Remove given node from the single Linked List ?

Question 20 : Difference between Externalize and Serializable in JAva?

Question 21 : What is Strong,Weak and soft References ?
Strong Reference : StringBuffer myBuff = new StringBuffer();
here myBuff is the strong reference.
Problem with Strong Reference : Strong references remains in the memory, even though
the value it is pointing is no longer needed.
Example: HashMap.put(MyClassObject,"Raja");
suppose , here the value "Raja" is lo longer needed, but still we are maintaining the 
reference (strong) i.e., MyClassObject in memory. 
This is the OverHead with this Strong References.
Strong Reference is Strong enough to prevent the garbage collector to collect the Object.


WEAK References :
  Weak references leverage the garbage collector to collect the object.

WeakReference MyClasssObj= new WeakReference<
MyClass>
();
in Other words, Weak reference is not strong enough to prevent the Garbage
Collector,
WeakHashMap works exactly likeHashMap, except that the keys (not the values!) are
 referred to using weak references. 
An Object of type weak Referenced will be garbage collected in the next Garbage collection
Cycle.
Where as Soft References of type will stay little more longer than weak reference Object
in memory.
Question 22 : Difference between Comparator and Comparable interface in Java?


Question 23: What is the difference between Abstract class and interface in Java?

Question 24 : Create two threads and synchronize those threads with only wait() and notify()
Methods? Example , Thread 1 should print even numbers 4 times and thread 2 should print
even numbers 4 times and thread 1 again print another 4 even numbers and cycle continues?

Question 25: What is Marker interface?

Question 26 : Why we need Checked and unchecked Exceptions in Java?

Question 27 : Cases where classNotFound Exceptions occur ?

Question 28 : How will you make your application International Language support ?

Question 29 : What is null pointer exception ? Explain scenario ?


public class MyNullPointerException {
public static void main(String[] args){
MyNullPointerException myObj = new MyNullPointerException();
myObj.callMe();
}
public  void callMe(){
System.out.println(" Call me  ???");
MyNullPointerException h = null;
h.callMe();

}
}

Question 30 : InOrder and preOrder and post Order traversal of a BST?



Program


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MinimumAbsoluteDifference {


    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int _count;
        _count = Integer.parseInt(in.nextLine());
        int[] a = new int[_count];
        String line = in.nextLine();
        String[] el = line.split(" ");
        for (int r = 0; r < el.length; r++) {
            a[r] = Integer.parseInt(el[r]);
        }

        MinimumAbsoluteDifference mad = new MinimumAbsoluteDifference();
        int[] sortedArray = mad.sortInputArray(a);
        int minimumAbsoluteDifference = Integer.MAX_VALUE;
        List<Integer> outputPairs = new ArrayList<Integer>();

        for (int i = 1; i < sortedArray.length; i++) {
            int difference = Math.abs(sortedArray[i] - sortedArray[i - 1]);
            if (difference <= minimumAbsoluteDifference) {
                minimumAbsoluteDifference = difference;
                outputPairs.add(sortedArray[i - 1]);
                outputPairs.add(sortedArray[i]);
            }
        }

        //Remove pairs whose difference greater than minimumAbsoluteDifference
        List<Integer> output = new ArrayList<Integer>();
        for (int k = 1; k < outputPairs.size(); ) {
            if (Math.abs(outputPairs.get(k) - outputPairs.get(k - 1)) <= minimumAbsoluteDifference) {
                output.add(outputPairs.get(k - 1));
                output.add(outputPairs.get(k));
            }
            k = k + 2;
        }
        for (int p : output) {
            System.out.print(p + " ");
        }
    }

    //Sorts input array using the insertion sort
    public int[] sortInputArray(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int key = a[i];
            int j = i - 1;
            while (j >= 0 && key < a[j]) {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = key;
        }
        return a;
    }
}




Question 1 : What is the Difference between ArrayList and LinkedList?

ArrayList 
       -> Implements the RandomAccess Interface.
       -> ArrayList actually encapsulating the array an object[].
       -> ArrayList have fast Random Access . using ger(index) will
            access the underlying array.
       > Adding values might be slow : A lot of shifting is going to be
           done in the memory space when Arraylist manipulates it's inter-
           nal array.(Clearly the array will have to start moving all the 
           values one spot to right.)          

LinkedList :
           -> Implements the Queue Interface.
           -> LinkedList implemented by nodes connecting each other.
          -> Each node contains links to previous node, next node and data.
          ->Fast Manipulation : Inserting a new Node and removing a node 
              just requires only updation of surrounding nodes.
        -> No randomAccess : Even though it has get(index) but actually
             iterates entire list up to the specified index.

Question 2 : What is the Difference between Comparator and Comparable?

Comparable Interface Has to be implemented by class to make it comparable.

Comparator interface used to sort collection of objects based custom sorting.

When a third party Api's which does not implement the comparable interface,
then in that case we can use comparator interface.
Question 3 : What is index in MySQL?

Question 4 : How will you get the third largest salary from a emp table ?

Ans: Select * from Employee E1 Where (N - 1) = (Select COUNT(DISTINCT(E2.salary))
from Employee E2 Where E2.salary >  E1.salary);


Question 5 : how will you compare and sort  user defined objects in java?
Answer : implement the comparable interface , so that class objects can be  sorted.

Question 5If my class not implemented any comparable interface , how to sort
 objects of that class?
Answer use comparator interface.

Question 6 suppose we have class which comes from different package,and 
that class not implementing the comparator interface then how will  you sort it objects.
Answer : Use Comparator interface..

Question 7 : Why cannot you override the Static methods?
Answer : Static methods are not belong to any instances.Static methods calls are
 resolved at compile time itself hence we have static binding for static method calls. 
Static methods are class methods are class methods and hence they can be accessed
using the class name itself and therefore access to them is required to be resolved during compile time only. 
That's the reason why static methods  can not actually be overriden.

Since Method overriding is happens at Run time.

Question 8 : Is String is not mutable , then what is the below code snippets do?
           String s1 = "ABC";
                      s1 = "XYZ";
does string s1 got changed ? or s1 = "xyz" created a new Object?

Answer: No, Here the String reference Got Changed, donot confuse with references
and objects. in String s1 = "ABC" s1 is variable which holds the reference to the 
object ABC" in the second statement s1 = "XYZ" it creates a new String with content 
XYZ and assign it's reference to variable s1 . so first object ABC has no references and
can be garbage collected.

 Code snippet 2 : String s1 = "123";
                              s1 = "123" + "456";
same here , what System.out.println(s1) prints. are you able to
modify the s1 string ?

This is good blog Why String is immutable in Java?
http://sureshk37.wordpress.com/2007/12/18/why-string-is-immutable/

Answer : Same like above...

QuestionObserver the below Code :

  public class MySerializableClass {

public static void modifyString(String myString){
myString = "Bhargav";
}
public static void main(String[] args)
{

                String myString1 = "Sekhar";
modifyString(myString1);
System.out.println(" my String : "+myString1);

}
}

What is the output is that string got changed?
Answer: No.
output : is "sekhar" only.
Observation : Java has both passbyvalue and passbyReference.
Note : It is passbyvalue if you pass primitive types to another method.
It is passbyreference if you pass objects to another method.
But, eventhough string is also an object it wont changed because it is immutable.
but if u pass an object (suppose say, student with all the properties set like name,
college,roll no) . we can change those properties in caller method.

Question 9 : suppose ClassA has the method showMe() which is overriden by the 
                       derived class ClassB, 
 class A 
{
   public void showMe(){

System.out.println("I am in class A 'ShowMe()' Method");


}


}

ClassB extends ClassA
{
 public void showMe(){
System.out.println("I am in Class B 'ShowMe()' Method");
}
public static void main(String[] args) {

ClassA aObj = new ClassB();  /* Up Casting */
aObj.showMe();
}
What is the output of the above Program ?
Ans: o/p : "I am in ClassB 'ShowMe()' Method".

Observation :Calls to Overridden methods done at run time based on the object.
This is called Dynamic Ploymorphisam....

Question 10 : Explain SingleTon Design Pattern with an Example?

Question 11What is the difference between SAX parser and DOM parser?

SAX Parser       ------------------------------- DOM Parser
1) Event Driven                                                 1)  Access XML document as Tree.
2) you should have event Handlers.               2) Composed mostly elements nodes  
3) Fast and Light Weight                               3)  Heavy weight to load and store.
4) Document does not have to entirely         4) Load completely in memory.
    in memory.
5) Sequential Read Access Only.                   5)Can walk back and forth in tree.
6) Only one time Access.                               6) Can walk any no of times.
7)  Does not support modification of           7) Support modification of XML
  document.
8) Originally designed for Java API             8) Standard defined by the W3C like XML.

Question 12 : Suppose say an Abstract class having only the method declaration
then is it equal to interface ?

Question 13 : how will you make your objects immutable ?
define the properties of each object has final.
Examplesuppose the student object has rollNo, age property then make those
 variables as final.

Question 14 : what is the difference between the class and Object ?
Answer: A Class is a definition or a model of an Object Type.
A Class has set of things that are alike.
An instance of class i.e., object directly fulfills it own definition.
A Class Contains the Object Code.
From a Class of String we can create any Number of objects of different strings.

Question What is the job of Class loader ?
It makes the availability of static fields/methods to Java run time environment.

Question 15 : Example of Comparable interface ?
Answer : 

package newPackage;

public class MyComparable implements Comparable {

private int studentID;
private String studentName;
private int studentAge;

public static void main(String[] args) {

MyComparable obj1 = new MyComparable(53, "sekhar", 25);
MyComparable obj2 = new MyComparable(55, "Sachin", 38);

if(obj1.compareTo(obj2)  greater than 0){
System.out.println(" "+obj1.getName()+" Older then "+obj2.getName());
}else{
System.out.println(" "+obj1.getName()+" Elder then "+obj2.getName());
}
}
public String getName(){
return this.studentName;
}
public int getAge(){
return this.studentAge;
}
public MyComparable(int id,String name, int age) {
this.studentAge = age;
this.studentID = id;
this.studentName = name;
}
@override
public int compareTo(MyComparable otherObject) {

if( !(otherObject instanceof MyComparable) )
 throw new ClassCastException(" Invalid Object");

int age = ((MyComparable)otherObject).getAge();
if(this.getAge() > age){
return 1;
}else{
return 0;
}
}
}

Question : Example of Comparator interface ?
Answer : Comparator interface useful if a class does not implement the comparable
interface and still wants to compare the Objects.
Student class does not implement comparable interface, but still can be compared 
by using the class MyComparator which implements the interface Comparator.
Here is the Example : 
package newPackage;
import java.util.Arrays;
public class Student {

private int studentAge;
private String studentName;
Student(int age,String name){
this.studentAge = age;
this.studentName = name;
}
public int getAge(){
return this.studentAge;
}
public String getName()
{
 return this.studentName;
}
public static void main(String[] args) {
Student student[] = new Student[4];
 student[0] = new Student(20,"Sekhar");
 student[1] = new Student(30,"Bush");
 student[2] = new Student(10,"Ravi");
 student[3] = new Student(50,"Kiran");
 
 Arrays.sort(student,new MyComparator());  
 System.out.println(" Order of Students after sorting by Age :");  
 for(int i = 0; i lessthan totalStudent ; i++)
System.out.println(" Student Name:"+student[i].getName()+", Age: "
                                                                +student[i].getAge());
 }
}
}
--------------------MyComparator--------------------------------
package newPackage;
import java.util.Comparator;

public class MyComparator implements Comparator {

@Override
public int compare(Student student1, Student student2) {
if(student1.getAge() > student2.getAge()){
return 1;
}else{
  return 0;
}
}
}
------Output----- : 

 Order of Students after sorting by Age :
 Student Name:Ravi, Age: 10
 Student Name:Sekhar, Age: 20
 Student Name:Bush, Age: 30
 Student Name:Kiran, Age: 50

QuestionWhat is the difference between HashMap and linkedHashMap?
Answer Order is not Guaranteed in HashMap , where it is guranteed in Linked
HashMap.
Example :
                 HashMap myMap = new HashMap();
                  myMap.put("sekhar","2");
                  myMap.put("Ravi","3");
System.out.println(" HashMap order : "+myMap)
o/p:
Ravi ---- 3
Sekhar  --- 2. 

Here while retriving the order got changed, so in order get the same 
order which you inserted then use LinkedHashMap......

Question What is Map ?
Answer : Map is an Interface in Java.
Question What is the difference between the enumeration and iterator?
Answer :     1) Both are interfaces.
                 2) Enumeration is read only.
                 3) With iterator we can remove elements in a collection.
                 4) iterator is fail safe.
                 5) Enumerator is no fail safe.
                 6) Enumerator is fast and uses less memory.
                **7)Enumerator is not available for ArrayList it avails only for vector..
Question : What is fail safe?
Answer : once after creat iterator on a arraylist , if u try to add new elements to 
an arraylist it throws an exception and fail's quickly and safely..

Question : What is meant by Order of map?
Answer : Order of map is nothing but , order in which the Iterator on the map's
collection view's return their elements.

Note: In a Map we cannot define the Map as key itself in an Map.
Question : Example of usage of enumerator ?
Ans : 

Question What are the classes implements the Map Interface?
Answer 
                1) HashMap 
               2) LinkedHashMap.
               3) TreeMap.
               4) WeakHashMap.
               5) ConcurrentHashMap.

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html
http://leepoint.net/notes-java/data/collections/maps/map_interface.html

Question What is the difference between the linkedHashMap and HashMap?
Answer : http://www.xyzws.com/Javafaq/linkedhashmap-vs-hashmap/77

Question How will you sort the string objects in ArrayList?
Answer : Observe the below program :
    
   ArrayList myList = new ArrayList();
 myList.add("sekhar");
 myList.add("Meera");
 myList.add("Karri");
 System.out.print(" My List : "+myList);
 Collections.sort(myList);
 System.out.println(" My List : "+myList);
o/p-------------------:
 My Before Sort List >>>> [sekhar, Meera, Karri]
 My After Sort List >>>> [Karri, Meera, sekhar]
Good link : http://download.oracle.com/javase/tutorial/collections/interfaces/order.html
Question : How will you reverser sort the objects in ArrayList ?

Question : If i have user defines objects in an ArrayList , then How will you sort those ?
http://www.javadeveloper.co.in/java-example/java-comparable-example.html
Question : how to create an Iterator for an Arraylist ?
Question : If i created an iterator for an ArrayList and while iterating can i able to add a
new object in an ArrayList?
Answer : Once after the iterator is created for any Arraylist , you are not allowed 
to change the structure of the ArrayList, if you try to that it throws the 
"ConcurrentModificationException"
Observe the below program :

ArrayList myList = new ArrayList();
Iterator it = myList.iterator();
myList.add("sekhar");
myList.add("Kiran");
myList.add("Keka");
while(it.hasNext()){
    System.out.println(">>>>  "+it.next());
}
O/p : 
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
Question Does the above code throws any Exception ? if so what is that exception?

Question Can i create a thread with just call only the run method , without 
                      a start method ?
Answer : Without calling the start method we can not create the thread.
by calling start() method only we can create a stack for that thread.
and move the thread from new state to runnable state.
 but we can call run method on a thread without calling the start() method
but the run() method is just like another method...

Question can i call run method on a thread which already completed the
                      run() method?

Answer: Yes, you can call run() method on thread which already completed 
it's job that means it's already ran the run() method..
But we cannot call start() method on that thread..
Observe the below program :

public class Another extends Thread{
public void run(){
          System.out.println(" i am in Run Methoddddd ");
}
public static void main(String[] args){
Another myClass = new Another();
  myClass.start();
myClass.run();
//myClass.start();
}
}

O/p  :  
 i am in Run Methoddddd 
 i am in Run Methoddddd 
Observe the below program, if you call start() method again on that thread.
it troughs the Exception "java.lang.IllegalThreadStateException"

public class Another extends Thread{
public void run(){
          System.out.println(" i am in Run Methoddddd ");
}
public static void main(String[] args){
Another myClass = new Another();
  myClass.start();
myClass.run();
myClass.start();
}
}
o/p :  
i am in Run Methoddddd 

Exception in thread "main"
        java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at newPackage.Another.main(Another.java:13)
 i am in Run Methoddddd 

Question suppose say three threads and three synchronized blocks are there,
'threadA' is executing the synchronized block A , can thread B able to execute the synchronized block B?

Question : how will you the scheduling the Threads ?

Question how will you synchronize the an object ?

QuestionSuppose if a class implements the serializable , can i serialize the
 subclass object?
Answer Yes , we can serialize the object of the sub-class which extends
a super class which implements the Serializable interface..
Below is the Program :
This is  the super class implements the serializable interface.

package com;
import java.io.Serializable;
public class PersistSuperClass implements Serializable {   
    public static void main(String[] args) {
    }
}
This is the sub class extends the super class and serialize it's objects.
package com;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SubClass extends PersistSuperClass {
    public String myName;
    public int  myAge;
    public String nickName;
    public static void main(String[] args) {

SubClass myObj = new SubClass();
myObj.myName = "sekhar";
myObj.myAge = 25;
myObj.nickName = "Bujji";

try {
    FileOutputStream fos = new FileOutputStream("sample.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(myObj);     
    oos.flush();
    oos.close();     
} catch (Exception e) {
   System.out.println(" Exception During Serialization : ");
    e.printStackTrace();
}
try{
    FileInputStream fis = new FileInputStream("sample.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);
    SubClass original = (SubClass)ois.readObject();
    System.out.println("  Name : "+original.myName);
    System.out.println("  Age Name : "+original.myAge);
    System.out.println("  Nick Name : "+original.nickName);
}catch(Exception e){
    e.printStackTrace();
}
    }
}
O/p : Of the Above Program :
  Name : sekhar
  Age Name : 25
  Nick Name : Bujji

ObservationWe cannot Serialize "static " and "transient" variables.

Question What is Externalize Interface in Java?
Answer : Through the Externalize interface we can get control over the 
serialization Process in Java.
There may be special requirements for serialization process, Suppose you have 
some passwords which are parts of your object, where you do not want to send
across the network.In that places this interface is Useful.
You can control the serialization process by implementing the Externalize interface
without using the serialization interface.
Which extends the serialization interface and add methods readExternal() and 
WriteExternal().

These two methods will get called automatically when you serialize and 
deserialize the objects.

Question What is the difference between externalization and serialization ?
Ans: When you serialize an externalize Object, the default constructor will get 
called automatically only after the readExternal() will get Called.

Where as serializing the object using the serialization interface, it wont call the 
default constructor before calling the readObject() Method.

When you are Serializing an Object using the Externalize interface before the 
writeObject() method called it calls the writeExternal() Method.

and it calls the default constructor and then readExternal() method before calling
the readObject().


package newPackage;

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.imageio.stream.FileImageInputStream;

public class MySerializableClass implements Externalizable {
  int age;
  String name;
public MySerializableClass(){
System.out.println("In default Constructor ");
}

public MySerializableClass(int age,String name){
this.age = age;
this.name = name;
}
public static void main(String[] args) throws ClassNotFoundException, 
IOException  {


ObjectOutputStream myObjectStream = new ObjectOutputStream(new FileOutputStream("serializeData.txt"));
MySerializableClass myObject = new MySerializableClass(26,"Sekhar");
System.out.println(" Age : "+myObject.age);

myObjectStream.writeObject("SEKHAR Airvana Networks pvt Ltd");
myObjectStream.writeObject(myObject);


ObjectInputStream input = new ObjectInputStream(new FileInputStream("serializeData.txt"));

String myString = (String)input.readObject();
MySerializableClass dObject = (MySerializableClass)input.readObject();
System.out.println(" my stirng : "+myString);
System.out.println(" My Object Age "+dObject.age);
System.out.println(" name      :    " +dObject.name);

}

@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
String myString = (String)in.readObject();
System.out.println(" My String  In Read External "+myString);
int myAge = (Integer)in.readObject();

System.out.println(" Age in Read External : "+myAge);

}

@Override
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println(" I am in Write Externcal");
out.writeObject(name);
out.writeObject(age);

}

}


Output :
  Age : 26
  I am in Write Externcal
  In default Constructor 
 My String  In Read External Sekhar
 Age in Read External : 26
 my stirng : SEKHAR Airvana Networks pvt Ltd
 My Object Age 0
 name      :    null

Question : How to get control over Serialization?
Ans : Through the Implementing the interface Externalize we can serialize the 
"static" and "transient " variables of a Object.

Here is the Example :

Class Orange.java implements the Interface Externalize and define the methods
"readExternal" and "WriteExternal".


import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Orange implements Externalizable {   
    
    public String movieName;
    public String hero;
    public String heroine;
    public static String director;
    public transient String producer;
    public static transient String banner;
    
    public Orange(){
    }
    public Orange(String mName,String h,String hr,String dir, String pro,String ban){
this.movieName = mName;
this.hero = h;
this.heroine = hr;
Orange.director = dir;
this.producer = pro;
Orange.banner = ban;
    }
    @Override
    public void readExternal(ObjectInput in) throws IOException,
    ClassNotFoundException {

System.out.println(" i am in Read ExterNal ");
movieName = in.readUTF();
hero = in.readUTF();
heroine = in.readUTF();
director = in.readUTF();
producer = in.readUTF();
banner = in.readUTF();
    }
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
System.out.println(" i am in Write External ");
out.writeUTF(movieName);
out.writeUTF(hero);
out.writeUTF(heroine);
out.writeUTF(director);
out.writeUTF(producer);
out.writeUTF(banner);
    }
}


Question : Suppose i want to synchronize the object of a class, and in that 
object i want a particular variable should be encrypted , How will you do that?

Answer : we cant encrypt the particular variable in a object, but we can 
get some control over the serialization by using the Externalize interface.

Question In an Servlet, how come you know number of users currently 
viewing your website?

Question If suppose try to insert a duplicate key in an HashMap? is it possible?
Answer : It is simply overWrites the previous key ..

  HashMap hm = new HashMap();
 hm.put(1,2);
 hm.put(1,5);

 System.out.println(" >>>> "+hm.get(1));
 System.out.println(" Hash Map : "+hm);
-------------Output -----------------------------

>>>> 5
 Hash Map : {1=5}

Question : What is an Interface?
Answer An interface is nothing but a specification of methods prototypes,
 all methods are public  which allows third party vendors to access and abstract
 methods allows implementation left to third party vendors.

Question : Explain the scenarios where we can opt only for Abstract Class 
and Interface?
Ans: 
Note 1 : Interfaces support dynamic method resolution at run time.
Note 2 : Interfaces are like for communications.
Note 3 : Supports Pluggable architecture for your design.

Question : What is the importance of marker interface?
Answer :  To mark the respective class as specific to perform a respective job.
It tells to JVM that treat this class as specially, and those classes have 
special job.

Another One : for every marker interface , java has provided an hidden 
functionality which has been plugged into execution environment.

Question can we declare our own marker interface in java?
Answer : Marker interface is an interface with no methods, so we can 
declare our own interface without methods, but the every marker interface
have an hidden functionality which is injected into the execution environment.
which is not possible with your own marker interface. which may be 
hinderer to java platform independent. 

Question What is finalize() method in java?
Answer : Allows you to clean up the object by garbage collector by releasing
all resources hold by that object. but in Java it is not recommended because 
we cant ensure garbage collector will get invoked as soon as you call the 

finalize() method..

Question : Check Whether the given String is Palindrome or not ?
Answer : Here is the Code

package com;

public class Pallindrome {

    public static void main(String[] args) {
String input   = "RADAR";
String rString = "";

int sLen = input.length();
int i;
for(i = sLen-1; i >= 0; i-- ){
    System.out.println(" Char "+input.charAt(i));
    rString = rString+input.charAt(i);
}
System.out.println(" Reverse String : "+rString);
if(input.equals(rString)){
    System.out.println(" EQual : ");
}else{
    System.out.println(" Not Equal ");
}
    }
}

Question : Print Combinations of given String ,Example ;
  Example : GIFT
        gift, GIF,GIT,GFT, GT...

       IFT, IF , IT, IG, IGFT, 
















2 comments:

siva said...

This is a nice article here with some useful tips for those who are not used-to comment that frequently.
Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
Java training in Chennai
Java training in Bangalore
Java online training
Java training in Pune
Java training in Bangalore|best Java training in Bangalore

iteducationcentre said...

Thanks for the post.
also, check java course in Pune

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...