Blogs On Job Interview Questions

Core Java Tutorial with Top 10 Interview Questions

Core Java Tutorial with Top 10 Interview Questions

by Vibrant Publishers on May 20, 2022
Introduction This tutorial will help you to understand the basics of Core Java. The content has been designed to keep students in mind. A separate link is provided for each basic Core Java sub-topic. We highly recommend you to take the quizzes at the end of the tutorial to assess your understanding of the subject.Followed by the quiz are the Top 10 Core Java Interview Questions You’ll Most Likely Be Asked to ensure your readiness for an Interview. These questions will help you get an idea of the most common questions that interviewers ask and the answers you’re expected to give. Follow the below links to access the tutorial of each topic:       Tutorial: Flow Control and Assertion Wrapper Classes, Garbage Collection, and Exception Handling Threads Object Oriented Programming Concepts Declarations and Access Controls Java Assignments Java Operators Inner Classes and String Handling Streams Collections     Quiz: Take these Java quizzes to assess your understanding of the subject. Quiz 1 Quiz 2       Top 10 Core Java Interview Questions: These Interview Questions are answered in a crisp and concise way requiring minimum time to understand the most important concepts in CORE JAVA. The Questions and Answers have been crafted by professionals around the globe with years of industry experience and are on quite a few interview panels.       1) What is an assertion in Java? How is it different from if - else conditions?   An assertion is a Boolean expression that is assumed by the programme. If true it executes the next statement and if false, the program throws an exception and ends. If–else conditions are different from assertions— if the if condition is false then the else part takes over, but in the case of an assertion if the assert expression is false, the program ends up throwing an error but will execute the second expression in the assert statement.     Example:     {   int var = 0;   System.out.println(“Enter a value bigger than 20 : ”);   var = in.nextLine();   assert var / 2 >5 : System.out.println(“Please try again and enter the   correct value”); System.out.println(“Good Choice!”);   }     Case 1: Enter a value bigger than 20: 10 Exception in thread “main” java.lang.AssertionError: Please try again and enter the correct value     Case 2: Enter a value bigger than 20: 30 Good Choice!     When Case 1 executes, the output will be – Exception in thread “main” java.lang.AssertionError: Please try again and enter the correct value. Case 2 will not throw any exception as the assumption or assertion is true and hence the next line in program will execute and the output is Good Choice!       2) What is a Wrapper class in Java? What are the special properties of Wrapper class objects?​   Java is completely Object-oriented programming. So, everything in Java should correspond to an object. But the primitives in Java are not objects. So, the wrapper classes convert Java Primitives to corresponding objects so that they can be utilized in the programs. Each primitive has a corresponding wrapper class and you can create an object of that type. In the same way, you can convert a wrapper object to the primitive type too. If you have an integer variable in Java, you can convert it into an Integer object using a wrapper class. Similarly, you can convert an Integer object to an int primitive type also. All wrapper objects are final. So, you cannot extend the wrapper classes.       3) What are the different types of Thread? Explain? Threads are of 2 types – Daemon Threads and Non-Daemon Threads.   All user-defined threads are Non-Daemon Threads unless they are explicitly set to be a Daemon thread. Daemon threads are usually used for background processes such as Garbage Collection. As soon as all Non-Daemon threads stop running, the JVM stops running and does not wait for the Daemon threads to stop.       4) What is an Object in software and what are the benefits of Objects?​   Software objects consist of state and their behavior. State of an object is stored in its fields and the behavior is exposed through the methods. Object-oriented programming helps to hide the internal characteristics of an object and this is called encapsulation. The main advantages of Objects are:   Independent: An Object’s definition can be kept separate from other objects and passed on to other programs. Encapsulation: The object’s fields and characteristics are hidden from the outer world. The only way to access the object’s characteristics are through the methods they provide. So the programmer can decide what to hide and what to expose. Reuse Code: Existing objects can be reused in many programs by creating an instance of extending its functionality. Easy to debug: Problematic objects can be traced out and debugged easily without affecting or touching any other portion of the code.       5) What is the benefit of declaring a class as final? By declaring a class as final, we ensure that the class is secured thereby no one can change its existing implementation. Also, the final class is thread-safe thereby restricting interaction between multiple threads.   Example:     final class MyClass {}     By making the class ‘MyClass’ as final, it is not possible for us to extend this class and use its implementation.Also, inter-thread communication is not possible when we declare the class as final.       6) Give an example for implicit cast? The below line of code is an example for implicit cast:     int iValue = 250;   long lValue = iValue;     The above code explains that an int value can always be assigned to a long variable without casting and the conversion happens by default.       7) State the use of instance of operator. Give an example? The use of instanceof operator is to check if an object belongs to a particular type. So, it is used only with object reference variables.   Example:       String name = “This is Java”;   if (name instanceof String)   {     System.out.println(name);   }     The above code checks if the variable ‘name’ is of type String. Since the condition is true, it will print the result “This is Java” when you execute the above code.       8) Explain about anonymous inner class? The anonymous inner class can be better explained with the below example.   Example:       Runnable runnable = new   Runnable() { //Line 1   public void run() { } //Line 2   }; //Line 3     Anonymous inner class can either extend a subclass or implement one interface but not both. In the above code, we have used the Runnable interface as an anonymous inner class. This inner class has a closed curly brace followed by a semicolon as coded in Line 3. This is the syntax of declaring an anonymous inner class. This inner class can have a method which is from its reference sub-class or interface. In the above code, we have used the run() method which belongs to the Runnable interface.       9) What is the difference between streams and collections? Though Streams and Collections look similar, their functionality is very different. The major differences between Streams and Collections are:   Collection holds an array of values whereas streams do not hold any value. They only help us carry the source value through a pipeline of computations. As they do not hold any value, they perform the function and do not change the value at the source. Collections are finite whereas strings are infinite. Streams perform mapping and other computations lazily which is more efficient.       10) What are the four interfaces of Java collections?​ Collection is the root of the collection hierarchy. A collection incorporates a multitude of objects cited as its elements. The Java platform doesn’t give any direct implementations of this interface.   Set can be a collection that contains distinctive elements. This interface is used to represent data similar to the deck of cards.   List is a collection that is ordered and it allows duplicate elements too. You may be able to access any part from its index. List is more like an array with variable length.   Queue is a collection in Java that works on the First In First Out principle. The elements that are added first will be removed first from the queue.   Map matches keys to values. A map will not contain duplicate keys: every key can map to at the most one value.     End note: In this blog, we took a look at the different types of questions asked in Java interviews. We also briefly glanced at various Java concepts that are commonly tested in interviews.      Get one step closer to your dream job!   Prepare for your Java programming interview with Core Java Questions You’ll Most Likely Be Asked. This book has a whopping 290 technical interview questions on Java Collections: List, queues, stacks, and Declarations and access control in Java, Exceptional Handling, Wrapper class, Java Operators, Java 8 and Java 9, etc. and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.     We’ve updated our blogs to reflect the latest changes in Java technologies. This blog was previously uploaded on March 24th, 2020, and has been updated on January 3rd, 2022.
JAX-RS Client

JAX-RS Client

by Vibrant Publishers on Jan 04, 2022
Introduction Resources form the basic building block of any REST service. These resources are accessed using the REST client libraries. JAX-RS client is such an implementation. This library makes it easy for any Java programmer to access any REST resources over the internet. JAX-RS ClientThe first version of JAX-RS ie. JAX-RS 1.1 does not had any client implementation. It is from JAX-RS 2.0 onwards it started supporting REST clients. The JAX-RS client API can be found under the javax.ws.rs.Client package. Classes under this package provide high-level APIs for accessing any REST resources, not just JAX-RS services. Let us have a look into the basic operations of JAX-RS Client API. Creating a basic client requestBefore defining a client request, we have to set certain things in place. They are: Obtain an instance of javax.ws.rs.Client class. Configure the client with a resource target. Create a request. Invoke the client request. Let’s have a look into these steps by considering the following code snippet: Client apiClient = ClientBuilder.newClient(); String URI = “http://foodchain.com/api/foodmenu”; String foodMenu = client.target(URI).request(MediaType.JSON).get(String.class); client.close(); Here we first created the client instance by declaring the client variable using the newClient() method. Client apiClient = ClientBuilder.newClient();After this step, we are chaining a set of methods with the client instance that will return the API resource to the string variable foodMenu. There are three steps involved in this process. Setting the target by apiClient.target(URI). This is the remote location where the resource is located. Building a REST request entity using the apiClient.request(Mediatype.JSON) statement. Here we also set the media type of the entity. Invoking the HTTP GET request with apiClient.target(URI).request(MediaType.JSON).get(String.class) statement. Also, the return type of the entity is set into String type. Once the client API successfully receives the response, we will close the client connection with the apiClient.close() statement.We have now seen a simple JAX-RS client API call in action. Now let us look into some of the extended use cases of JAX-RS client library.Setting multiple client targetsWe used the client.target() method in the previous example to set the target URI. We can also use the javax.ws.rs.client.WebTarget class for the same purpose. This will help us in handling REST resources where multiple targets are involved. In the given example, we are setting a base target “http://restapi.com/assignments” using the WebTarget class. The base target is used for building several resource targets that will point to different API services provided by a given RESTful resource. Client apiClient = ClientBuilder.newClient(); WebTarget base = apiClient.target(“http://restapi.com/assignments”); // WebTarget at http://restapi.com/assignments/read WebTarget read = base.path(“read”); // WebTarget at http://restapi.com/assignments/write WebTarget write = base.path(“write”);  Invoking the WebTarget.path() method with a path parameter creates a new WebTarget instance by appending it with the base URI.Invoking the requestThe JAX-RS client can invoke every available REST request method. This is accomplished by calling the WebTarget.request() method and passing the relevant media type value. This will provide an instance of javax.ws.rs.client.Invocation.Builder. This helper object will provide HTTP methods for the client API request. In the first example, apiClient.target(URI).request(MediaType.JSON).get(String.class) we had invoked the HTTP GET request and the same process stands for POST(), DELETE(), PUT() methods also. SummaryJAX-RS client API that got introduced in version 2.0 is one of the best implementations of the REST client library. It’s quite easy to make client API calls using this library. We can use this library in Java for accessing any REST resource over the web.  
JAX-RS Filters

JAX-RS Filters

by Vibrant Publishers on Dec 14, 2021
Introduction JAX-RS is the Java implementation for REST services.There are a lot of features in this library that helps us to build web services in Java. The JAX-RS Filters are used for processing the incoming and outgoing requests and responses including headers, entity and other parameters. This feature was introduced in JAX-RS 2.0. These filters get executed after a request and before a response.The filters are available for both server and client side processing. Use of filters You might be wondering what is the use of filters in web services. Well, there can be situations where you would like to do a common modification for all the requests originating from a particular client or some signature like “Powered by XX” in all the responses going from a particular server. Instead of doing this implementation on all the service methods we would use a filter which will include this modification in all the API requests and responses. The below given is a diagram that schematically represents the filtering process on both client and server sides.     In the first section we got to know that there are filters available for server side and client side as well. Let us look into the details of their types and implementations. Server Side Filters The server side has got two types of filters. ContainerRequestFilters             They get executed before your JAX-RS request resource method is getting invoked.This filter can be used in two ways post-matching and pre-matching. In post-matching filters will be applied after a suitable resource method selection that processes the actual request. Here the filter will not affect the resource matching process. In certain scenarios, this can become a disadvantage. In-order to solve that problem there is pre-matching. When we mark a server request filter as pre-matching using the @PreMatching annotation, the filters are executed before the request matching process. ContainerResponseFilters        These filters get executed after your response method is invoked.They will help you to alter the outgoing response before it reaches the client. ContainerResponseFilter can only be implemented in the pre-matching way. With this filter one can modify the HTTP headers, media type(json,xml,etc.) and other meta-data. They also have the capability to abort a method execution. Client Side Filters Like we saw on the server side, the client side also has two types of filters. ClientRequestFilters            These filters are executed before the client API request is sent to the server over a network. ClientResponseFilters              These filters will be invoked after the client receives a response from the server, but before it is being unmarshalled. They can modify the response body before it is getting processed by the client side code. Summary JAX-RS filters are useful in dealing with modification of REST API request-response services.These filters can be installed at any point in the REST service pipeline. There can be multiple request-response filters where they are executed in a chain. It is very useful when we are working with API driven applications where we might need modification on multiple REST APIs at a given time.  
10 Most Likely Asked Java/J2EE Design Pattern Interview Questions And Answers

10 Most Likely Asked Java/J2EE Design Pattern Interview Questions And Answers

by Vibrant Publishers on Dec 14, 2021
According to the Bureau of Labor Statistics (BLS), the median annual salary for software developers like J2EE developers is $101,790.The BLS has predicted a job growth rate of 31 percent through 2026, which is much faster than average for all occupations. Demand for developers will grow with the increased demand for computer software. Prepare with the top 10 Java/J2EE Design Patterns Interview Questions highly asked in job interviews. These are the questions that we will be covering today: 1: What does the JTable class do in Design Patterns? 2: What does the getStepCount() Method do in Design Patterns? 3: What is an Abstraction in Design Patterns? 4: What does the Monitor Function do in Design Patterns? 5: What are the differences between factory and abstract factory Patterns? 6: What is the main advantage of the Facade Pattern? 7: What happens with the response to the request in the case of these two patterns? 8: What problem does the Business Delegate Pattern try to solve? 9: How are new Observers added to existing ones? 10: Give some examples of Behavioral Patterns and how they are used. 1: What does the JTable class do in Design Patterns? Answer: The JTable class is used to handle almost every aspect of displaying a table, but cannot know in advance what data the developer wishes to present. It is a main setter for the use of the Adapter. 2: What does the getStepCount() Method do in Design Patterns? Answer: This method is used as an operation in the Process Component class to count the number of steps needed in a process flow; it has to count each step only once and not enter an infinite loop when a process contains a cycle. 3: What is an Abstraction in Design Patterns? Answer: Abstraction is an oops concept where necessary details are hidden from the user, and only relevant details are exposed. It helps in designing a solution to the problem during the design phase. Abstraction can be achieved by an interface or an abstract class. The abstract class consists of abstract methods without providing concrete implementations for the abstract methods. It can also consist of non-abstract methods with core implementation. While the interface only consists of abstract methods without their implementation. 4: What does the Monitor Function do in Design Patterns? Answer: The Monitor Function is a way of designing an application object so that it does not produce unpredictable results when more than one thread tries to access the object at the same time. 5: What are the differences between factory and abstract factory Patterns? Answer: Both Factory and Abstract Factory are creational design patterns. However, there are some differences between the two: a) Factory method design pattern can be implemented by a method; the abstract factory design pattern needs to be implemented via a class b) In the factory method pattern, we define an interface but decide which class to use at runtime. In the abstract factory method, we define interfaces corresponding to the factory classes and decide which factory class to use at runtime. c) The abstract factory design pattern provides a higher level of abstraction as compared to the factory method d) The factory method pattern uses inheritance whereas the Abstract Factory pattern uses Composition 6: What is the main advantage of the Facade Pattern? Answer: The Facade Pattern helps in hiding the complexities of the application beneath the layer of an interface. This interface helps reduce the dependency of the client classes on the subsystem classes, thus resulting in a manageable and user-friendly subsystem. 7: What happens with the response to the request in the case of these two patterns? Answer: In the case of Proxy Pattern, the response to the request is guaranteed, provided the communication between the client and the server locations is working. In the case of Chain of Responsibility, the response is not guaranteed. It means that the request may end up reaching the end of the chain and still might not be processed. 8: What problem does the Business Delegate Pattern try to solve? Answer: When the presentation tier or client application accesses the business tier directly, the business service API is exposed to the client application or presentation tier. So if the business API changes, the corresponding changes will have to be made in the presentation tier. Also, in such an implementation, there is a performance issue as well, since the business service is invoked each time by the client application. Thirdly, this kind of implementation causes a tight coupling between the presentation tier and the business tier. The business delegate pattern solves all these problems. The Business Delegate class is present on the client side and it hides the implementation details of the business tier by providing an abstraction. So the client application only interacts with the delegate class which in turn routes the client’s request to the appropriate business method. 9: How are new Observers added to existing ones? Answer: This is achieved after applying the Observer Pattern and adding them dynamically without requiring any changes to the Subject Class. Also, Observers remain unaffected when the state chance logic of the subject changes. 10: Give some examples of Behavioral Patterns and how they are used. Answer: Some of the most common Behavioral Patterns are: a) Iterator -This design pattern is used to access elements of a collection sequentially hiding the internal implementation. b) Chain of Responsibilities – This design pattern is used where a chain of objects is used to handle the responsibilities. In this design pattern, a request to process the client call is only passed to the next object when the first object fails to process the same. c) Observer – It is used where a one-to-many relationship exists among the objects and modifying a single object can impact the dependent objects. d) Mediator -This design pattern encapsulates the communication complexity that takes place between different objects and acts as an intermediary between the objects for communication. To have a successful career as a Java/J2EE developer, one must get a good start. Refer to our book HR Interview Questions You’ll Most Likely Be Asked (Third Edition) to find out interview questions for your HR round, and prepare yourself for all the aspects of your interview. Good Luck!
JAX-RS Security

JAX-RS Security

by Vibrant Publishers on Nov 23, 2021
Introduction Web services play a very vital role in any web application. Since these services deal with data which are of varied criticality, the security considerations of these services are very high. The JAX-RS library implemented to create REST web services in Java uses strict measures to ensure the security of the APIs built on top of it. Let us examine those security features of JAX-RS in detail. JAX-RS Security The JAX-RS library provides a core set of security features at three levels that are as follows. Encryption Authentication Authorization   Encryption    We all know that the REST is built on top of the HTTP protocol. The security of REST services lies in the security of its transfer protocol also. So while implementing APIs developers also make sure that they use HTTPS protocol with SSL certificates to ensure end-to-end encryption. This will block any third party from reading the information by intercepting the network. Authentication         This is another common strategy that people use to make sure the client has access to a particular API resource. This is done by validating the client identity on the server-side. There will be a credential matching process that will confirm the client. In JavaEE containers, there is a web.xml file that can be configured for such processes. Below shown activity diagram shows a sample API authentication process.       Authorization          When a client is authenticated, the next step in the security process is to check whether the client is authorized to access certain resources from the server. In some cases, certain resources are read-only for certain types of clients. Some may have read and update access. So these permissions have to be validated. These settings are also configured in the web.xml file of the application which is hosted in the server container. JAX-RS Security Implementations  We have seen the main ways by which security can be forced into web services. Now let us see how JAX-RS is implementing these measures.  There are three ways by which JAX-RS security can be implemented. They are: Using a deployment descriptor file. Using the security context. Use of annotations.   Using a deployment descriptor file. The deployment descriptor file is an XML file that is part of the container. It is called web.xml. You will configure the web.xml file for web services security in such a way that any client trying to access a resource via an API, it will be asked for authentication and authorization. This is done through the following steps: Define the tag for every URIs or RESTful API resources that we are planning to protect. Use an element that will define a type of authentication that we would like to use. Define one or multiple security roles by including the tag. Once done, map them with security constraints defined in Step.1.   Using the security context The use of SecurityContext class helps us to get the below mentioned security information for a given resource. java.security.Principal object that has the name of the user who is making a request. Authentication type that is used to secure a resource, like FORM_AUTH, BASIC_AUTH, CLIENT_CERT_AUTH. Check whether the authenticated user has been included in any security roles. See whether the request is coming from a secure channel like HTTPS. Use of annotations The javax.annotations.security package in Java provides security annotations. They can be used for securing APIs methods. Following are the common annotations in use:                                                                                     Annotation Usage @PermitAll Specifies that all security roles are allowed to invoke the given resource method. @RolesAllowed Lists out the security roles that are allowed to access a given resource method. @DenyAll It specifies none of the security roles are allowed to invoke the given resource method. @DeclareRoles This will provide the security role of the current user invoking a resource method.   Summary Security implementation in JAX-RS leverages the help of server container and transport protocols. They are implemented mainly using configuration parameters and through annotations. When we are building APIs for web applications, it is always a good practice to include these security features in our API code.    
JAX-RS Asynchronous Processing

JAX-RS Asynchronous Processing

by Vibrant Publishers on Nov 19, 2021
IntroductionThe JAX-RS library is used for implementing REST web services in Java. They are designed for quick request-response processing to ensure speed and optimal use of the underlying container thread pool. But there can be scenarios where certain resources need to run for a longer time to process and provide a response. To address these scenarios, JAX-RS has implemented an asynchronous processing mechanism. This feature was introduced in JAX-RS version 2.0. Let us have a look into the JAX-RS Asynchronous processing mechanism.Asynchronous processing This means the thread that responds to a request will be a different one than that of the thread that handled the request. In short, the request and response won’t happen in one stretch. There can be a considerable time gap between the two.Why is it required?If you are wondering what is the need for such an implementation, there mainly two benefits: Consider a synchronous request-response scenario. If a JAX-RS client sends a request that requires long waiting for a response from the server, it is blocking the request thread. The same thread, if released faster, could have been used by some other requests. This is avoided by implementing the asynchronous method. Similarly on the server side also, it allows the server to suspend the original request thread and create a new thread for responding to an asynchronous request. Due to the above-said reasons, the implementation will ensure high throughput, responsiveness, and scalability. The below given process diagram will give you a clear picture of this concept. JAX-RS Asynchronous ImplementationThere are separate implementations available on the server-side and client-side for asynchronous APIs.Server-side implementation of Asynchronous processing On the server-side, the asynchronous behavior is ensured by using: AsyncResponse: This class is responsible for bridging the client-side request with the server-side methods. Using this class the server methods update the status of asynchronous processes. Based on this status the underlying logic will take appropriate action. The resource method that is running a long process should call AsyncResponse.resume() so that a response can be sent back to the client. @Suspend: This annotation is used to instruct the container to inject the AsyncResponse method and invoke it asynchronously. The resource methods called with AsyncResponse instance will be in the suspended state. One important thing to remember here is that the resource method that is annotated with @Suspend will not be called using a separate thread. It is the responsibility of the programmer to create a new thread for the long-running process and return the caller thread. One more thing to remember here is to specify a time-out period using AsyncResponse.setTimout(). This will ensure that the client will get back an HTTP 503 (Service Unavailable ) response, in case there are some issues on the server and the resource method could not respond. If this timeout is not specified, the client-side request will end up in a long wait. Client side implementation of Asynchronous processing The client side implementation of asynchronous call is pretty easy. The only thing you need to do is get an instance of the AsyncInvoker. This can be done by executing async() function on an instance of Invocation.Builder class. Let us see an example here:Client restClient = ClientBuilder.newBuilder().build();WebTarget URL = restClient.target(“https://api.example.com/search/menu?query=pasta”);Invocation.Builder requestBuilder = URL.request();AsyncInvoker asyncInvoker = requestBuilder.async();Future futureResponse = asyncInvoker.get();Response apiResponse = futureResponse.get(); String responseBody = apiResponse.readEntity(String.class);In the above example, the highlighted portion explains how to use the asynchronous call on the client-side. Summary There are lots of features in JAX-RS that help for rapid request-response processing. But the asynchronous feature implementation in JAX-RS helps a developer to give a time lag between request and response processing. This is very useful especially when there is heavy server-side processing required on certain client requests.
JAX-RS Miscellaneous

JAX-RS Miscellaneous

by Vibrant Publishers on Nov 02, 2021
Introduction REST APIs serve as the backbone of millions of web applications. This is one of the most commonly used web service standards in today’s world. The JAX-RS provides the REST support in Java and has lots of features that help us build scalable web services. In this article we are going to explore some of the JAX-RS features that are important to know while building a web service. Bootstrapping a JAX-RS applicationIt is very simple to start a JAX-RS application. All you need to do is to create a subclass of  javax.ws.rs.core.Application on your classpath. The below given sample explains how you will do that:                                                                        import javax.ws.rs.core.Application; @ApplicationPath(“api”) public class SampleWebAPIApplication extends Application           {       } The annotation @ApplicationPath provides the context root for all your APIs. In this case the APIs will have a URI starting with ‘/api’. So if you have an API to provide employee details, the URI will look like “http://www.example.com/api/v2/employee/” here the “/v2/” stands for versioning. It’s always a good practice to include versioning while creating APIs. This will be helpful when you want the same resource in custom APIs for different clients. Defining  REST endpointsThe REST endpoints serve as the connection point with the client. The JAX-RS specification has given the @Path annotation to map each HTTP (PUT, DELETE, POST, GET)  method to a java method. Consider the following example:                                                                                 public class EmployeeDatabse {  @GET  @Path(“/{id}”)    public Response getNameById(@PathParam(“id”) Long id,      @QueryParam(“name”)    @DefaultValue(“”) String name) {   @POST       public Response getNameById(Employee employee, @Context UriInfo uriInfo) {  // …  }       // …     } Here the entire class is mapped to “/employee” with different HTTP methods. The @PathParam is used for getting the value of a path variable and the @QueryParam is used for retrieving values for a query parameter of a URL.JAX-RS Providers Providers are extensions of JAX-RS that are responsible for providing functionality to the JAX-RS runtime. Mainly two types of providers are there. Exception mapping providers and Entity providers. Exception Mapping ProvidersThese are responsible for mapping services between JAX-RS response and Java exceptions. The ExceptionMapper interface is provided when a resource method throws a runtime exception. The response provided by these exception mappers are treated as same as the response provided by the resource methods. Entity ProvidersEntity providers provide marshalling / unmarshalling service between Java types and the resource representations (XML/JSON etc.). The MessageBodyReader interface is an entity provider that is used for deserializing a resource representation into a Java type. The reverse operation is performed by another entity provider interface named MessageBodyWriter. Exception Handling The exceptions that are thrown by a resource method are caught by the JAX-RS runtime and they are converted into error responses. By default they are converted into a “HTTP 500 – Server Error” message. There are two ways in JAX-RS to deal with exceptions, the first method is to throw “WebApplicationException” that can customize error response messages. The second method is to use the built in response mechanism of the JAX-RS runtime that will send a default Response to the client when an exception is caught. Summary When dealing with REST implementation using JAX-RS, there are some points that one must know to make use of its full potential. These concepts discussed here will help you build web services that conform to the REST principle.