Wednesday, February 7, 2018

3.Java Interview Questions List For Experienced

How do I remove repeated elements from ArrayList?
The easiest way to remove repeated elements is to add the contents to a
Set (which will not allow duplicates) and then add the Set back to the ArrayList:

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);
Read More: https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist

 <a href="edit.jsp?userId=${user.id}" />
 request.getParameter("userId")
</form>
int userid = session.getAttribute("userId");

When to use Set and When to use List?
The usage is purely depends on the requirement:If the requirement is to have only unique values then Set is your best bet as any implementation of Set maintains unique values only.

If there is a need to maintain the insertion order irrespective of the duplicity then List is a best option. Both the implementations of List interface – ArrayList and LinkedList sorts the elements in their insertion order.

Difference between Singleton Pattern vs Static Class in Java?

When to use Singltone and static methods?

Read more: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html#ixzz55viwXhKK

A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance.

A singleton is used when you do want an actual object (with its own internal state and everything), and you want to limit your system to exactly one instance of that object.
Static class is a Java class, which only contains static methods, good examples of static class is java.lang.Math,which contains lots of utility methods for various maths function e.g. sqrt(). While Singleton classes are those, which has only one instance during application life cycle like java.lang.Runtime.

<span style="font-size:16px;"><span style="font-family:arial,helvetica,sans-serif;">    ClassPathResource resource = new ClassPathResource("beans.xml"); 
XmlBeanFactory factory = new XmlBeanFactory(resource);
// Here resource object is provided explicitly</span></span>

3. ApplicationContext supports internationalization but BeanFactory do not.
4. Annotation based dependency Injection is not supported by BeanFactory whereas
 ApplicationContext supports using annotation @PreDestroy, @Autowired.

Read More: http://www.oodlestechnologies.com/blogs/Difference-between-BeanFactory-and-ApplicationContext

Update and merge difference?
https://www.java4s.com/hibernate/difference-between-merge-and-update-methods-in-hibernate/

Let Us Take An Example
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();
s1.setMarks(97);
Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();
session2.merge(s1);
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();

Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();

s1.setMarks(97);

Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();

session2.merge(s1);
Explanation
See from line numbers 6 – 9, we just loaded one object s1 into session1 cache and closed session1 at line number 9,
 so now object s1 in the session1 cache will be destroyed as session1 cache will expires when ever we say session1.close()
Now s1 object will be in some RAM location, not in the session1 cache
here s1 is in detached state, and at line number 11 we modified that detached object s1,
 now if we call update() method then hibernate will throws an error, because we can update
the object in the session only
So we opened another session [session2] at line number 13,
and again loaded the same student object from the database, but with name s2
so in this session2, we called session2.merge(s1); now into s2 object s1 changes
will be merged and saved into the database
Hope you are clear…, actually update and merge methods will come into picture when ever we
loaded the same object again and again into the database, like above.

What is the difference between save and persist in Hibernate?

Here is the difference between save and persist method:

1. First difference between save and persist is there return type. The return type of persist method is void while return type of save method is Serializable object. But bot of them also INSERT records into database
2.Another difference between persist and save is that both methods make a transient object to persistent state. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.
3. Third difference between save and persist method in Hibernate is behavior on outside of transaction boundaries. persist() method will not execute an insert query if it is called outside of transaction boundaries. Because save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.
4.Fourth difference between save and persist method in Hibernate: persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
5. Read More: https://www.quora.com/What-is-the-difference-between-save-and-persist-in-Hibernate

What is maven-install and maven-deploy?
mvn:install copies your packaged Maven module to your local repository (by default, in ~/.m2/repository), to be accessed by other local Maven builds.

mvn:deploy uploads your packaged Maven module to another (usually remote) repository, to be accessed by other, not necessarily local, Maven builds.
https://stackoverflow.com/questions/7531115/whats-the-difference-between-mvndeploy-and-mvninstall-commands

Whats artifact-id and group-id in maven?
artifactId is the name of the jar without version. If you created
it then you can choose whatever name you want with lowercase letters and no
strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.
eg. maven, commons-math

groupId will identify your project uniquely across all projects, so we need to enforce a naming
 schema. It has to follow the package name rules, what means that has to be at least as a
domain name you control, and you can create as many subgroups as you want. Look at More
 information about package names. eg. org.apache.maven, org.apache.commons
@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
@Repository – annotate classes at persistence layer, which will act as database repository.
By using that annotation we do two things, first we declare that this class is a Spring bean and should be created and maintained by Spring ApplicationContext, but also we indicate that its a controller in MVC setup. This latter property is used by web-specific tools and functionalities.
For example, DispatcherServlet will look for @RequestMapping on classes which are annotated using @Controller but not with @Component.
This means @Component and @Controller are same with respect to bean creation and dependency injection but later is a specialized form of former. Even if you replace @Controller annotation with @Compoenent, Spring can automatically detect and register the controller class but it may not work as you expect with respect to request mapping.
By using a specialized annotation we hit two birds with one stone. First, they are treated as Spring bean and second you can put special behavior required by that layer.

Though for that you also need to declare org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor as Spring bean in your application context.This bean post processor adds an advisor to any bean that’s annotated with @Repository so that any platform-specific exceptions are caught and then rethrown as one of Spring’s unchecked data access exceptions.

How to Create an Immutable Class in Java?
Declare the class as final so it can’t be extended.
Make all fields private so that direct access is not allowed.
Don’t provide setter methods for variables
Make all mutable fields final so that it’s value can be assigned only once.
Initialize all the fields via a constructor performing deep copy.
Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
Read More:
https://www.journaldev.com/129/how-to-create-immutable-class-in-java
https://dzone.com/articles/how-to-create-an-immutable-class-in-java

Difference between like and ilike in hibernate criteria?
"ilike" is for case-sensitive,

Criteria cr = session.createCriteria(Employee.class);
"like" is for case-insensitive,
// To get records having fistName starting with zara
cr.add(Restrictions.like("firstName", "zara%"));

// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName", "zara%"));

What is Projection in Hibernate?
The projections concept is introduced in hibernate 3.0 and mainly we can do the following 2 operations using the projection.
We can load partial object from the database
We can find the Result of Aggregate functions

Projection is an Interface given in “org.hibernate.criterion” package, Projections is an class given in same package,  actually Projection is an interface, and Projections is an class and is a factory for producing projection objects.
Using criteria, if we want to load partial object from the database, then we need to create a projection object for property that is to be loaded from the database

Example:
Criteria crit = session.createCriteria(Products.class);
crit.setProjection(Projections.proparty("proName"));
List l=crit.list();
Iterator it=l.iterator();
while(it.hasNext())
{
String s = (String)it.next();
}

If we add multiple projections to criteria then the last projection added will be considered to execute see…
Example:
Criteria crit = session.createCriteria(Products.class);

Projection p1 = Projection.property("proName");
Projection p2 = Projection.property("price");

crit.setProjection(p1):
crit.setProjection(p2):
List l=crit.list();
Read More: https://www.java4s.com/hibernate/working-with-hibernate-projections-in-criteria/
HQL is to perform both select and non-select operations on the data,  but Criteria is only for selecting the data, we cannot perform non-select operations using criteria
HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
Criteria used to take more time to execute then HQL
With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.

Named queries in hibernate is a technique to group the HQL statements in single location, and lately refer them by some name whenever need to use them.
NamedQuery is the way you define your query by giving it a name.
They can be accessed and used from several places which increase re-usability.

Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client.
We can also write plain SQl queries in a similar manner as follows:
@NamedNativeQueries({
 @NamedNativeQuery(
 name = "findEmployeeByIdNativeSQL",
 query = "select * from Employee_details where emp_id = :passId",
 resultClass = Employee.class
 )
})
In native SQL, you have to declare the ‘resultClass‘ to let Hibernate know what is the return type, failed to do it will caused the exception. Also notice that we are using actual table and column name in DB here.
Read More:https://djcodes.wordpress.com/databases/hibernate-need-and-setup/hibernate-named-query-and-criteria/
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc.
Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.

Comparable affects the original class i.e. actual class is modified.
Comparator doesn't affect the original class i.e. actual class is not modified.

Comparable provides compareTo() method to sort elements.
Comparator provides compare() method to sort elements.

Comparable is found in java.lang package.
Comparator is found in java.util package.

We can sort the list elements of Comparable type by Collections.sort(List) method.
We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.

Read More: http://javarevisited.blogspot.in/2011/06/comparator-and-comparable-in-java.html
https://www.journaldev.com/780/comparable-and-comparator-in-java-example

Which is more secured session or cookies in jsp?
Sessions are server-side files that contain user information, while Cookies are client-side files that
contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.

"passing it in a URL (which poses a security risk)." actually both approach have security risks (different ones).

SLF4J vs LOG4J Which one to prefer?
SLF4J is basically an abstraction layer. It is not a logging implementation. It means that if you're writing a library and you use SLF4J, you can give that library to someone else to use and they can choose which logging implementation to use with SLF4J e.g. log4j or the Java logging API. It helps prevent projects from being dependent on lots of logging APIs just because they use libraries that are dependent on them.
So, to summarise: SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your library/app.
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.
Read More: https://www.slf4j.org/manual.html

Which annotation is used at time of startup to do something immediately after the bean’s initialization?
The @PostConstruct and @PreDestroy annotation are not belong to Spring, it’s located in the J2ee library – common-annotations.jar.

By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘<context:annotation-config />‘ in bean configuration file,

@PostConstruct annotation is same as "init-method" we configure in the bean.xml
@PreDestroy annotation is sam eas "destroy-method" we configure in the bean.xml

<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 class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
  <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
    <property name="message" value="i'm property message" />
  </bean>
</beans>

ReadMore: https://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/

JAVA8 New Features?

Stream API
lambda expressions
Functional interfaces
Interface Default and Static Methods
Method References : Reference to a Static Method, Reference to an Instance Method,  Reference to a Constructor.
Optional<T> class: Before Java 8 developers had to carefully validate values they referred to, because of a possibility of throwing the NullPointerException (NPE). All these checks demanded a pretty annoying and error-prone boilerplate code.
Java 8 Optional<T> class can help to handle situations where there is a possibility of getting the NPE. It works as a container for the object of type T. It can return a value of this object if this value is not a null. When the value inside this container is null it allows doing some predefined actions instead of throwing NPE.
Collectors class
Collection API improvements:
Some new methods added in Collection API are:Map replaceAll(), compute(), merge() methods.
forEach() method
Java Nashorn
Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code.
You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.
StringJoiner
Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc.
Miscellaneous Core API improvements
PermGen memory space has been removed.
Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order etc.
min(), max() and sum() methods in Integer, Long and Double wrapper classes.
logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
Several utility methods in Math class.
Read More: 
https://www.javatpoint.com/java-8-features
https://www.journaldev.com/2389/java-8-features-with-examples

What is Predicate in java8?
java.util.function.Predicate is a functional interface that can be used as assignment target for lambda expression. The Predicate interface represents an operation that takes a single input and returns a boolean value.
public class PredicateExample1 {
public static void main(String[] args) {

//Predicate String
Predicate<String> predicateString = s -> {
return s.equals("Hello");
};

System.out.println(predicateString.test("Hello"));
System.out.println(predicateString.test("Hello World"));

//Predicate integer
Predicate<Integer> predicateInt = i -> {
return i > 0;
};

System.out.println(predicateInt.test(5));
System.out.println(predicateInt.test(-5));
}
}
Output:
true
false
true
false
Read More: https://www.boraji.com/java-8-predicate-example

Java program to find the counts of each character in a String?
Solution :
1. First get the string.
2. Create one hashmap with key as ‘character’ and value as ‘integer’ .
 Count of each character will be stored as value with key as the character.
3. Scan the string character by character.
4. Check for each character : if no key equals to the character is available in the hashmap ,
 add one new key as the character and value as 1.
5. If key is available, increment the value by one.

Example:
for (int i=0; i<line.length(); i++){
            if(map.containsKey(line.charAt(i))){
                value = map.get(line.charAt(i));
                value ++;
                map.put(line.charAt(i),value);
            }else{
                map.put(line.charAt(i),1);
            }
        }
       
Read More: http://www.codevscolor.com/2017/08/java-count-character-string/

How set collection check element exist or not?
Adding elements to a Set:
The add()method returns true if the set does not contain the specified element, and returns false if the set already contains the specified element:

Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");

if (names.add("Peter")) {
    System.out.println("Peter is added to the set");
}

if (!names.add("Tom")) {
    System.out.println("Tom is already added to the set");
}


Search Algorithm to find particular element in an array.

https://www.geeksforgeeks.org/linear-search-vs-binary-search/
https://www.geeksforgeeks.org/binary-search-preferred-ternary-search/

Remove Duplicate value from array using array only/
https://www.javatpoint.com/java-program-to-remove-duplicate-element-in-an-array

What is the return type of HashmAp put method?
The method put has a return type same with the value:
@Override
    public V put(K key, V value) {
        return putImpl(key, value);
    }
It returns the previous value associated with key if key exist, or null if key does not exist and then it put the value into map .

How set uses the map internally?
In HashSet add(e) method, the return value of map.put(key,value) method will be checked with null value.
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

How rest Api convert the request an response and do the mapping?
@ResponseBody
In Spring MVC, @ResponseBody annotation on a AccoutnController method indicates to Spring that the return Account object of
 the method is serialized to JSON directly to the body of the HTTP Response. It uses “Accept” header to choose the appropriate
 Http Converter to marshall the object.
 header "Accept: application/json"

@RequestBody
In Spring MVC, @RequestBody annotation on the argument of a AccountController method create (@RequestBody Account account)
– it indicates to Spring that the body of the HTTP Request (either in JSON or XML) is deserialized to that Account Java Object.
 It uses “Content-Type” header specified by the REST Client will be used to determine the appropriate converter for this.
 Content-Type: application/json

Example:
@RequestMapping(method=RequestMethod.PUT, value="/foos/{id}")
public @ResponseBody void updateFoo(
  @RequestBody Foo foo, @PathVariable String id) {
    fooService.update(foo);
}
Read More: https://www.dineshonjava.com/customizing-httpmessageconverter-with-spring-mvc-in-rest/

The Default Message Converters
By default, the following HttpMessageConverters instances are pre-enabled:
ByteArrayHttpMessageConverter – converts byte arrays
StringHttpMessageConverter – converts Strings
ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
SourceHttpMessageConverter – converts javax.xml.transform.Source
FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.
Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)
MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)
MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)
AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)
RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)
Read More : http://www.baeldung.com/spring-httpmessageconverter-rest

Try/Catch example with return value?
Whenever try block executes successfully, then it can return value for this method from try block
Similarly, if any exception is raised then exception gets caught in the catch block & it can also return value (from catch block)
Since, we have finally block returning value therefore returning value from try or catch block will be overridden by return statement in the finally block
Because, on all cases finally block gets executed irrespective of exception is raised or NOT & it is handled or NOT inside catch block. Therefore, overriddes any return value from try-block or catch-block
This is called overridden case
Error: any statement after finally block in this example, will result in compile-time error stating “Unreachable code”

public static int myTestingFuncn(){
  try{
     ....
     return 5;
  }Catch{
  ...
  return 1;
  }
  finally {
     ....
     return 19;
   }
}

This program would return value 19 since the value returned by try/Catch has been overridden by finally.
Read More: http://www.benchresources.net/returning-value-from-method-having-try-catch-finally-blocks-in-java/

which method of preparedstatemrnt is used to store java object?
Ans: void setObject(int parameterIndex, Object x)
Sets the value of the designated parameter using the given object.

Which of the following methods will you use to find the maximum number of connection that a specific driver can obtain?
Database.getMaxConnection
Connection.getMaxConnection
DatabaseMetaData.getMaxConnection
ResultSetMetaData.getMaxConnection
Ans: DatabaseMetaData.getMaxConnection.

what is motivation behind command design pattern?
Motivation. "Sometimes it is necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request."

Registry services such as managing information about service providers, service implementations and service metadata is provided by

WSDL
UDDI
REST
SPARQL
Ans: UDDI

where @ignore  annotation is apply , so that code complies?
which of the following Database driver is used to connect javascript code to RDBMS?

What is a Slowly Changing Dimension?
A Slowly Changing Dimension (SCD) is a dimension that stores and manages both current and historical data over time in a data warehouse. It is considered and implemented as one of the most critical ETL tasks in tracking the history of dimension records.

Difference between "==" and "===" operator ?
is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn't allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type "===" return false, while "==" return true.
Read more: http://www.java67.com/2013/07/difference-between-equality-strict-vs-operator-in-JavaScript-Interview-Question.html#ixzz59by0nn1c

Object and class in java?
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.

‘Null’ in JavaScript
‘Null’ is a keyword in JavaScript that signifies ‘no value’ or nonexistence of any value. If you wish to shred a variable off its assigned value, you can simply assign ‘null’ to it. Besides this, like any other object, it is never implicitly assigned to a variable by JavaScript.
An example of explicit null assignment is –
var some_item= null;
console.log(some_item)
Upon execution, the code will print null.

‘Undefined’ in JavaScript
‘Undefined’ is a global variable that JavaScript creates at run time. This global variable is assigned to an object in one of the following cases –
1. Declared but not defined –
JavaScript assigns ‘undefined’ to any object that has been declared but not initialized or defined. In other words, in a case where no value has been explicitly assigned to the variable, JavaScript calls it ‘undefined’.
2. Array index or object property that does not exist.
3. A function parameter that has not been supplied.
4. The return value of functions that have to but don’t return a value.

No comments:

Post a Comment