whenever you insert an element into HashSet using
add() method, it actually creates an entry in the internally backing
HashMap object with element you have specified as it’s key and
constant called “PRESENT” as it’s value. This “PRESENT” is defined
in the HashSet class as below.
In the same manner, all methods of
HashSet class process internally backing HashMap object to get the
desired result. If you know how HashMap works, it will be easy for
you to understand how HashSet works. You go through the source code
of HashSet class once, you will get a clear picture about how
HashSet works internally in Java.
17. What is the difference between Log4j 1 and log4j 2?
Log4j only supported configuration
files in properties and XML formats, while Log4j2 supports
configuration through XML, JSON, YAML, and configuration
files/programmatic actions
18. Optimistic Locking and Pessimistic locking in Hibernate?
Optimistic locking , where a record is locked only when
changes are committed to the database. Pessimistic locking ,
where a record is locked while it is edited.
19. How can we create a Cache and cache in Spring Boot?
@Cacheable
The simplest way to enable caching behavior for a method is to
mark it with @Cacheable and parameterize it with the name of the
cache where the results would be stored.
@Cacheable(“name”)
public String getName(Customer customer) {…}
20. Second level cache in Hibernate?
A Hibernate second-level cache is one of the data caching
components available in the Hibernate object-relational
mapping (ORM) library. Hibernate is a popular ORM library for
the Java language, and it lets you store your Java object data
in a relational database management system (RDBMS).
21. Topic versus Queue?
The difference between a Topic and a Queue is that all
subscribers to a Topic receive the same message when the
message is published and only one subscriber to a Queue
receives a message when the message is sent.
22. What happens when JMS server crash what happens to the
queue Web logic server?
With the automatic JMS client reconnect feature, if a server
or network failure occurs, some JMS client objects will
transparently failover to use a another server instance, as
long as one is available. For example, if a fatal server
failure occurs, JMS clients automatically attempt to reconnect
to the server when it becomes available.
23. Any other methods required in comparable
implementation.
The Comparable interface contains the method compareTo to
decide the order of the elements. Override the compareTo
method in the Pair class.
24. Read property from property file in a class.
The Properties is a subclass of Hashtable class and it represents
a persistent set of properties. The Properties can be saved to a
stream or loaded from a stream. Each key and its corresponding
value in the property list is a string.
The Properties file can be used in Java to externalize the
configuration and to store the key-value pairs. The
Properties.load() method of Properties class is convenient to load
.properties file in the form of key-value pairs.
Syntax
public class Properties extends Hashtable
credentials.properties file
Example
import java.io.*;
import java.util.*;
public class ReadPropertiesFileTest {
public static void main(String args[]) throws IOException {
Properties prop = readPropertiesFile("credentials.properties");
System.out.println("username: "+ prop.getProperty("username"));
System.out.println("password: "+ prop.getProperty("password"));
}
public static Properties readPropertiesFile(String fileName) throws IOException {
FileInputStream fis = null;
Properties prop = null;
try {
fis = new FileInputStream(fileName);
prop = new Properties();
prop.load(fis);
} catch(FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
fis.close();
}
return prop;
}
}
Output :
username: admin
password: admin@123
25. Write a program to print something but should not
execute PSVM?
As we know that the static block executes before the main method,
hence we can place the statement that we want to execute in the
static block, But in case of JDK7, and the above versions of the
JDK, the code would not execute as compiler firstly looks for the
main method before any other thing. Also, it depends on the IDE
being used to run the program, ie the program might get executed
successfully on some IDE, and might not on some IDE’s. Also, we
can abnormally exit our program in the static block so that the
JVM will not check the main method, but as discussed it depends on
IDE, whether the program will run or not.
Example: Below is the code implementation of the above approach.
// Java Program printing the statement without using main
// method.
class PrintWithoutMain {
// static block
static {
// prints "Hello World!!" to the console
System.out.println("Hello World!!");
// exit from the program
System.exit(1);
}
}
The above code does not compile before and on JDK7. Also, one
might get the error like below if run the above code on some IDE
like Intellij or Netbeans or console.
26. What annotations we have in Entity classes?
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "STUDENT_NAME", nullable = false, unique = false)
private String name;
@Transient
private Integer age;
@Temporal(TemporalType.DATE)
private Date birthDate;
@Enumerated(EnumType.STRING)
private Gender gender;
// other fields, getters and setters
}
27. What Class not found exception n Java?
ClassNotFoundException occurs when you try to load a class at
runtime using Class. forName() or loadClass() methods and
requested classes are not found in classpath. Most of the time
this exception will occur when you try to run an application
without updating the classpath with JAR files.
28. How we do validation in spring?
The Spring MVC framework provides us with standard predefined
validators to validate user input data in a simple and
straightforward way. The Bean Validation API is the popular
approach for data validations in Spring applications. Here we will
be using the hibernate implementation of the Bean Validation API
known as Hibernate Validator.
Validation annotations
Here are some of the most commonly used validation annotations.
1. @Min(value=) – Checks whether the annotated value is greater than
or equal to the specified minimum value.
2. @Max(value=) – Checks whether the annotated value is smaller than
or equal to the specified maximum value. ‘
@Min(value = 18, message = "Age must be greater than 18")
@Max(value = 25, message = "Age must be smaller than 25")
private int age;
3. @NotNull – Checks that the annotated value is not null.
4. @NotBlank – Checks that the annotated character sequence/string is
not null and the trimmed length is greater than 0.
5. @NotEmpty – Checks that the annotated element
is not null and not empty.
// @NotNull: The CharSequence, Collection, Map or Array object is
not null, but can be empty.
// @NotEmpty: The CharSequence, Collection, Map or Array object is
not null and size > 0.
// @NotBlank: The string is not null and the trimmed length is
greater than zero.
@NotEmpty(message = "First name cannot be null and
must have size greater than 0")
private String firstName;
@NotNull(message = "Second name must not be null,
empty value/space can be considered")
private String lastName;
@NotBlank(message = "Username must not be null and
must contain 1 or more characters")
private String userName;
6. @Email – Checks whether the specified character
sequence/string is a valid email address.
@Email(message = "Email should be valid")
private String email;
7. @Pattern(regex=, flags=) – Checks that the annotated string matches the
regular expression considering the given flag matches.
// The regex specifies that the password can contain characters from
a to z, A to Z and 0-9 only,
// also it must be in between 6 to 10 characters long.
@Pattern(regexp = "^[a-zA-Z0-9]{6,10}$")
private String password;
8. @AssertFalse – Checks that the annotated element is false.
9. @AssertTrue – Checks that the annotated element is true.
@AssertTrue
private boolean isWorking;
@AssertFalse
private boolean isStudent;
10. @NegativeOrZero – Checks if the given element is
smaller than or equal to 0.
11. @Null – Checks that the annotated value is null.
12. @Negative – Checks if the element is strictly
smaller than 0.
13. @Positive – Checks if the element is strictly
greater than 0.
14. @PositiveOrZero – Checks if the given element is
greater than or equal to 0.
@Positive
private int operand1;
@Negative
private int operand2;
@PositiveOrZero
private int operand3
@NegativeOrZero
private int operand4;
@Null
private int nullVal;
15. @Size – Checks if the annotated element’s size is
between min value
and max value provided (inclusive).
@Size(min = 10, max = 200, message = "About Me must be
between 10 and 200 characters")
private String aboutMe;
Example 1: User class
// Java Program to Illustrate Calculator class
package com.example.springmvc;
// Importing required classes
import javax.validation.constraints.*;
import lombok.Data;
// Annotation
@Data
// Class
public class User {
@NotEmpty(
message
= "First name cannot be null and must have size
greater than 0")
private String firstName;
@NotNull(
message
= "Second name must not be null, empty value/space
can be considered")
private String lastName;
@NotBlank(
message
= "Username must not be null and must
contain 1 or more characters")
private String userName;
@AssertTrue private boolean working;
@Min(value = 18,
message = "Age must be greater than 18")
@Max(value = 25,
message = "Age must be smaller than 25")
private int age;
@Size(
min = 10, max = 200,
message
= "About Me must be between 10 and 200 characters")
private String aboutMe;
@Email(message = "Email should be valid")
private String email;
@Pattern(regexp = "^[a-zA-Z0-9]{6,10}$")
private String password;
@AssertTrue private boolean isWorking;
@AssertFalse private boolean isStudent;
}
29. Two classes implement same Interface and how do we create
reference of 1 class in Spring(not using new keyword)
You don't call a method directly from an interface, you call it
on a reference that points to an instance of a class. Whichever
class that is determines which method gets called.
30. How do you do your db connections in property files?
Connect to your database using application.properties.
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/todo_example
spring.datasource.username=todouser
spring.datasource.password=YOUR_PASSWORD
31. Explain SOLID principles?
Single Responsibility Principle (SRP) - A class should have only
one reason to change
Open/Closed Principle - Software entities (classes, modules,
functions, etc.) should be open for extension, but closed for
modification
Liskov’s Substitution Principle (LSP) - Derived or child classes
must be substitutable for their base or parent classes
Interface Segregation Principle (ISP) - Do not force any client to
implement an interface which is irrelevant to them
Dependency Inversion Principle (DIP) -
-
High-level modules/classes should not depend on low-level
modules/classes. Both should depend upon abstractions.
-
Abstractions should not depend upon details. Details should
depend upon abstractions.
32. Co-relation id in micro services.
Correlation ids are unique identifiers that help you trace
requests across multiple services in a distributed system.
They are essential for debugging, logging, and monitoring the
performance and behavior of your microservices.
33. How do we monitor micro services?
There are three monitoring tools are as follows:
- Hystrix dashboard
- Eureka admin dashboard
- Spring boot admin dashboard
34. How objects converted to json in restful web
services
You can use GSon to convert json object to java object
Gson gson = new Gson();
//to get json object use toJson
String json = gson.toJson(obj);
//to get java object use fromJson
MyClass obj = gson.fromJson(jsonObj, MyClass.class);
jackson is also pretty fast and easy to use
35. What is Volatile and where it is used?
Volatile keyword is used to modify the value of a variable by
different threads. It is also used to make classes thread
safe. It means that multiple threads can use a method and
instance of the classes at the same time without any problem.
The volatile keyword can be used either with primitive type or
objects.
36. Where you do database configuration in Spring boot?
Connect to your database using application.properties.
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/todo_example
spring.datasource.username=todouser
spring.datasource.password=YOUR_PASSWORD
37. Why set does not allow duplicates – reason?
Why set does not allowed duplicates, How it will work
internally. The meaning of "sets do not allow duplicate
values" is that when you add a duplicate to a set, the
duplicate is ignored, and the set remains unchanged. This does
not lead to compile or runtime errors: duplicates are silently
ignored.
38. How do we Configure classes in Spring boot?
Spring Boot favors Java-based configuration. Although it is
possible to use SpringApplication with XML sources, we
generally recommend that your primary source be a single
@Configuration class. Usually the class that defines the main
method is a good candidate as the primary
@Configuration
39. what is the difference between component, bean,
Services, Repository?
@Component is a generic stereotype for any Spring-managed
component or bean.
@Repository is a stereotype for the persistence layer.
@Service is a stereotype for the service layer.
The @Bean annotation is a method-level annotation, whereas
@Component is a class-level annotation. The @Component annotation
doesn't need to be used with the @Configuration annotation,
whereas the @Bean generic annotation has to be used within a class
annotated with @Configuration .
40. How you configured jdbc template in Springboot
Create a SpringBoot maven based project and add
spring-boot-starter-jdbc module.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
The jdbcTemplate automatically reads the spring.datasource
properties from my application.properties file
41. What changes required to deploy spring boot as war file
in Server?
We need to deploy WAR file so change the package type to WAR in
pom.xml file.
<packaging>war</packaging>
42. Iterate over hash set?
There are three simple ways to iterate over a HashSet, which is
the following :
- Using Iterator
- Without using Iterator (using for loop)
- Using for-each loop
43. JPA how you write a query in JPA?
package com.javaforsomeone.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.javaforsomeone.entity.Employee;
@Repository
public interface EmployeeRepository extends CrudRepository {
public List findByName(String name);
public List findByAge(int age);
public Employee findByEmail(String email);
@Query(value = "SELECT e FROM Employee e ORDER BY name")
public List findAllSortedByName();
}
44. what is the difference between RestController and
controller?
@RestController is nothing but the shortcut to use both
@Controller and @ResponseBody annotation together. In other
words, @Controller is used to controller which can accept and
return HTML while @RestController annotation can be used to
return JSON response.
45. what are default methods in interface added in Java 8?
The default methods were introduced to provide backward
compatibility so that existing interfaces can use the lambda
expressions without implementing the methods in the implementation
class. Default methods are also known as defender methods or
virtual extension methods.
46. When String created using new, "", where it will be
present in heap or string pool?
|
String creation using new()
|
String creation using String literal
|
|
If we create a String using new(), then a new object is
created in the heap memory even if that value is already
present in the heap memory.
|
If we create a String using String literal and its
value already exists in the string pool, then that
String variable also points to that same value in the
String pool without the creation of a new String with that
value.
|
|
It takes more time for the execution and thus has lower
performance than using String literal.
|
It takes less time for the execution and thus has better
performance than using new().
|
|
Example:
String n1= new String(“Java”);
String n2= new String(“Java”);
String n3= new String(“Create”);
|
Example:
String s1=”Java”;
String s2=”Java”;
String s3=”Create”;
|
47. what new features are there in java 8?
- Some of the important Java 8 features are;
- forEach() method in Iterable interface
- default and static methods in Interfaces
- Functional Interfaces and Lambda Expressions
- Java Stream API for Bulk Data Operations on Collections
- Java Time API
- Java Stream API1
- Concurrency API improvements
- Java IO improvements
48. Does toUpper. toLower creates new string object or
not?
Java automatically interns String literals. when you use
toUpperCase() it creates a new instance of the string, using
new String(), that's why both the objects are different.
49. Serializable interface is a marker interface
The Serializable interface is present in java.io package. It
is a marker interface. A Marker Interface does not have any
methods and fields. Thus classes implementing it do not have
to implement any methods. Classes implement it if they want
their instances to be Serialized or Deserialized.
Serialization is a mechanism of converting the state of an
object into a byte stream. Serialization is done using
ObjectOutputStream. Deserialization is the reverse process
where the byte stream is used to recreate the actual Java
object in memory. This mechanism is used to persist the
object. Deserialization is done using ObjectInputStream. Thus
it can be used to make an eligible for saving its state into a
file.
50. What is Static synchronization & non static synchronization?
A synchronized method or block works on a given monitor.
Synchronized non-static methods all synchronize on the Java
instance of a class. Each instance has a lock monitor. For the
case of static methods, what object does static synchronized
methods use for locking? The static synchronized statements obtain
a lock on the Class object.
If you make any static method as synchronized, the lock will be on
the class not on object.
Why we use Static Synchronized Block/Method?
Suppose there are two objects of a shared class(e.g. Account)
named object1 and object2.In case of synchronized method and
synchronized block there cannot be interference between t1 and t2
or t3 and t4 because t1 and t2 both refers to a common object that
have a single lock.But there can be interference between t1 and t3
or t2 and t4 because t1 acquires another lock and t3 acquires
another lock. I want no interference between t1 and t3 or t2 and
t4. Static synchronization solves this problem.
The JVM creates a Class object when the class is loaded (When it
is used for the first time). Once a class is loaded into a JVM,
the same class will not be loaded again. The JVM creates one
instance of Class for each class that is loaded, The Class
instances are Objects and can be synchronized via static
synchronized methods.
For example
class MyClass {
...
public synchronized static someMethod() {
...
}
...
}
It is the equivalent to the following static synchronized block:
synchronized ( MyClass.class ) {
...
}
Example of static synchronization
In this example we are applying synchronized keyword on the static method to perform static synchronization.
class Account{
synchronized static void showAccount(String accountName){
System.out.println("My account name is "+accountName+"
Holder Name is "+Thread.currentThread().getName());
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
class MyThread1 extends Thread{
public void run(){
Account.showAccount("Javaforsomeone.com");
}
}
class MyThread2 extends Thread{
public void run(){
Account.showAccount("Linkedin.com");
}
}
class MyThread3 extends Thread{
public void run(){
Account.showAccount("Facebook.com");
}
}
class MyThread4 extends Thread{
public void run(){
Account.showAccount("Twitter.com");
}
}
class StaticSyncDemo{
public static void main(String t[]){
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
MyThread4 t4 = new MyThread4();
t1.setName("DAV JavaServices");
t2.setName("Java For Some");
t3.setName("Java For One");
t4.setName("admin@javaforsomeone.com");
t1.start();
t2.start();
t3.start();
t4.start();
}
}