1. Explain briefly about your project experience .
2. Explain about oops concept and how you implemented in your project.
3. I have a class A having main method, also I have another class B extends A when compiling B will it be executed or not?.
Yes, It will get executed.
public class Test2 {
public static void main(String[] args) {
System.out.println("Called Test 2"); } }
public class Test4 extends Test2 { }
output: Called Test 2
4. What will happen when a method is called inside the same method. Who Checks and stop the program termination.
eg: public class Test2 {
public void greet(){
greet();
}
public static void main(String[] args) {
Test2 test2 = new Test2();
test2.greet();
}
}
The above Code throws Exception in thread "main" java.lang.StackOverflowError. Which means The StackOverflowError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.
When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no
space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).
The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided.
5. If I have a static method in both parent class and extended class and while creating the object reference for the child method which method will be invoked.?
private, final and static methods and variables use static binding and bonded by the compiler while overridden methods are bonded during runtime based upon the type of runtime object
Hence the method in the parent class is called also the compiler throws the warnings."The static method greet() from the type Test2 should be accessed in a static way"
6. How many objects are created when (Parent)Test2 test2 = new (child)Test4();
In inheritance, subclass acquires super class properties. An important point to note is, when subclass object is created, a separate object of super class object will not be created. Only a subclass object object is created that has super class variables.
7. Explain static binding?
Static Binding: The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time .
Why binding of static, final and private methods is always a static binding? Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static.
8. I have two class and methods with different argument how do you call this during the runtime.
public class ReflectionDemo1 {
public static void main(String[] args) {
System.out.println(greet("Syed Ghouse Habib", 1));
}
public static String greet(String string, long log) {
return string + log;
}
}
public class ReflectionDemo2 {
public static void main(String[] args) {
System.out.println(greet("Syed Ghouse Habib"));
}
public static String greet(String string) {
return string;
}
}
It can be called using the reflection.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class InvokeMain {
public static void main(String...args) {
try {
for (String arg: args) {
Class << ? > c = Class.forName(arg);
Class[] argTypes = new Class[1];
argTypes[0] = String[].class;
Method main = c.getDeclaredMethod("main", argTypes);
String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
System.out.format("invoking %s.main()%n", c.getName());
main.invoke(null, (Object) mainArgs);
}
// production code should handle these exceptions more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } catch (NoSuchMethodException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace();
} catch (InvocationTargetException x) {
x.printStackTrace();
}
}
}
9. What will happen when the Employee object with the same value is added to the set.
Having only the equals method. It will have two objects created. When we have only the hashcode method. It will have two objects created. It will have only one entry when both the methods are available.
10. Write a program to sum the value from the given alphanumeric string.
sampleString = "pq12s56"
import java.util.stream.Collectors;
public class StringSummer {
public static void main(String args[]) {
String sampleString = "pq12s56";
int sum8 = 0; //using java8
sum8 = sampleString.chars().filter(val - > Character.isDigit((char) val)).mapToObj(num - > Character.getNumericValue(num)).collect(Collectors.summingInt(Integer::intValue));
System.out.println(sum8);
int sum = 0; //using java 7
char[] charVal = sampleString.toCharArray();
for (char c: charVal) {
if (Character.isDigit(c)) {
sum = sum + Character.getNumericValue(c);
}
}
System.out.println(sum);
}
}
11. Explain memory management in java?.
Runtime data area in JVM can be divided as below,
Method Area: Storage area for compiled class files. (One per JVM instance)
Heap: Storage area for Objects. (One per JVM instance)
Java stack: Storage area for local variables, results of intermediate operations. (One per thread)
PC Register: Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread)
Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread)
Following are points you need to consider about memory allocation in java.
Note: Object and Object references are different things.
1)There is new keyword in java used very often to create a new objects. But what new does is allocate memory for the object of class you are making and returns a reference.
That means whenever you create an object as static or local, it gets stored in HEAP.
2) All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap.
3) Classes loaded by classloader and static variables and static object references are stored in a special location in heap which permanent generation.
4) Local primitive variables, local object references and method parameters are stored in Stack.
5) Local Functions (methods) are stored in stack but Static functions(methods) goes in permanent storage.
6) All the information related to a class like the name of the class, Object arrays associated with the class, internal objects used by JVM (like java/lang/Object), and optimization information goes into the Permanent Generation area.
7) To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems.
12. Explain the initial capacity of ArrayList?. How would you force to create an array of capacity 8?
In java 8 default capacity of ArrayList is 0 until we add at least one object into the ArrayList object (You can call it lazy initialization).
Now question is why this change has been done in JAVA 8?
The answer is to save memory consumption. Millions of array list objects are created in real-time java applications. Default size of 10 objects means that we allocate 10 pointers (40 or 80 bytes) for the underlying array at creation and fill them in with nulls. An empty array (filled with nulls) occupy lot of memory .
Lazy initialization postpones this memory consumption till moment you will actually use the array list.
List<String> s = new ArrayList<>(8);
This statement will create the array of inital capacity 8.
13. What is the algorithm used in Java GC.
Mark & sweep algoritm.
14.what are the different types of method avaliable in
1. GET Method HTTP GET method used to retrieve information from the REST API.We should not use this method to change any information or the resource.GET should be idempotent, meaning regardless of how many times it repeats with the same parameters, the results are the same.
2. POST Method This method in the REST API should only be used to create a new resource.In some cases, POST method is used to update entity but this operation is not very frequent.POST API call is not idempotent nor safe and should be used with care.
3. PUT Method If we want to update an existing resource, PUT method should be used for this operation.PUT method has some features as compare to the POST method and we should keep those in mind · PUT method is idempotent.This means the client can send the same request multiple time and as per HTTP spec, this has exactly the same effect as sending once. (This is for us to make sure PUT behaves correctly every time)
4. DELETE Method DELETE method should be used to remove a given resource.Similiar to PUT method, DELETE operation is idempotent.If a resource is deleted any later request will change anything in the
system and it should return 404 response.DELETE can be a long-running or asynchronous request.
5. PATCH Method Partial update to a resource should happen through PATCH method.To differentiate between PATCH and PUT method, PATCH request used to partially change a given resource while PUT used to replace existing resource.There are few things to keep in mind while using PATCH method. · Support for PATCH in browsers, servers and web applications are not universal, this can post some challenges. · Request payload for Patch is not simple and a client is required to send information to differentiate between the new and original documents.
15. Difference between put and post method.
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)! POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
16. How does the springboot works.
From the run method, the main application context is kicked off which in turn searches for the classes annotated with @Configuration, initializes all the declared beans in those configuration classes, and based upon the scope of those beans, stores those beans in JVM, specifically in a space inside JVM which is known as IOC container. After the creation of all the beans, automatically configures the dispatcher servlet and registers the default handler mappings, messageConverts, and all other basic things.
Basically, spring boot supports three embedded servers:- Tomcat (default), Jetty and Undertow.
You can add cross filters in spring boot in one of the configuration files as
@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter {
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**"); } }
17.What are the Embeded servers in spring boot and which one is default.
Tomcat (default), Jetty and Undertow.
18. Difference between spring mvc and spring boot, is dispatcher servlet not used in the springboot?
Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs.
Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on). So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer.
You understood it right.
@Configuration @Configuration is an analog for xml file. Such classes are sources of bean definitions by defining methods with the @Bean annotation.
@Configuration is:
not required, if you already pass the annotated class in the sources parameter when calling the SpringApplication.run() method; required, when you don't pass the annotated class explicitly, but it's in the package that's specified in the @ComponentScan annotation of your main configuration class. For readability, classes that are even explicitly passed as sources may anyway be annotated with @Configuration - just to show the intentions more clearly.
Your current class is not really source of bean definitions, because it doesn't have any, but if you had @Bean annotated methods, Spring would see them.
@EnableAutoConfiguration Can be used with or without @Configuration. It tells Spring to setup some basic infrastructure judging by what you have in the classpath. It's done by invoking a so called import class that's
derived from the value of the @Import annotation that @EnableAutoConfiguration includes. Only one class should be annotated with @EnableAutoConfiguration, duplicating it doesn't do anything.
19.what is a stream in java 8 and what are its features?.
Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package.
Stream provides following features:
Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations. Stream is functional in nature. Operations performed on a stream does not modify it's source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection. Stream is lazy and evaluates code only when required. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. You can use stream to filter, collect, print, and convert from one data structure to other etc. In the following examples, we have apply various operations with the help of stream.
20. Draw microservices componets.
21. How to implement the retry mechanism for the microservices.
@SpringBootApplication
@EnableRetry
public class So52193237Application {
public static void main(String[] args) {
SpringApplication.run(So52193237Application.class, args);
}
@Bean
public ApplicationRunner runner(Foo foo) {
return args - > {
try {
foo.exec();
} catch (Exception e) {
try {
foo.exec();
} catch (Exception ee) {
Thread.sleep(11000);
try {
foo.exec();
} catch (Exception eee) {
}
}
}
};
}
@Component
public static class Foo {
private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);
private final Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
@CircuitBreaker(maxAttempts = 1, openTimeout = 10000, resetTimeout = 10000)
public void exec() throws TypeOneException {
LOGGER.info("Foo.circuit");
this.bar.retryWhenException();
}
@Recover
public void recover(Throwable t) throws Throwable {
LOGGER.info("Foo.recover");
throw t;
}
}
@Component
public static class Bar {
private static final Logger LOGGER = LoggerFactory.getLogger(Bar.class);
@Retryable(value = {
TypeOneException.class
}, maxAttempts = 3, backoff = @Backoff(2000)) public void retryWhenException() throws TypeOneException {
LOGGER.info("Retrying");
throw new TypeOneException();
}
@Recover
public void recover(Throwable t) throws Throwable {
LOGGER.info("Bar.recover");
throw t;
}
}
}
22. What are the types of exceptions you have handled in your application?
23. Do you like to work in a team or an individual contributor?
24. Do you like to learn about new technologies?.
25. Have you heard of cucumber?.
26. What you will do in your free time?.
27. If you have a conflict with one of your college how you will resolve it?.
28. If the requirements are not clear what you will do first?.
29. Any Questions for me?
x
No comments:
Write comments