Blogs On Programming

Multithreading in Java

Multithreading in Java

by Vibrant Publishers on May 20 2022
Introduction: In this blog, we will look at Threading in Java.We will cover the following topics in detail: Introduction to Java Thread The Java Thread Model Creating & Using a Java Thread Multithreading in Java     Introduction to Java Thread When it comes to programming languages, Java is the only one that provides built-in support for multithreading. In a multithreaded programming environment, two or more programs can run concurrently. Each of these programs are called threads and are considered as the smallest unit of processing. During run-time, the threads in a given program exist in a common memory space and therefore share both data & code. However, each thread maintains an exclusive execution path. This enables the language to perform multitasking without having the heaviness of multiprocessing.   Java achieves threading through java.lang.Thread class. These are lightweight in nature and can run concurrently in synchronous or asynchronous mode.   We can classify threads into User-defined threads and Daemon threads. (1) User-defined threads are those that are created programmatically by the user. These are high priority threads. The Java Thread Model (JVM) waits for these threads to finish. (2) Daemon threads are created by the JVM.     The Java Thread Model The Thread Model in Java has got a life-cycle with different stages as shown below:     New: A thread is said to be in a new state just after we initiate the instance of a new thread class. Runnable: A thread becomes runnable after it gets started. Running: When the Java thread is executing its task, it is said to be in a running state. Suspended: When a thread is in this stage, its activity is temporarily suspended. This state can be resumed from the part where it left off. Blocked: When a Java thread is waiting for a resource, we can keep it in the blocked state. Terminated: This means that the execution of a thread is halted immediately at any given time. Once the thread is terminated, it cannot be resumed.     The following are some of the important Thread Methods that are used in managing a thread object.   public void start(): The start() starts the thread in a separate path of execution, after which it invokes the run() method, on this thread object. public void run(): The run() method is invoked on a thread object that is instantiated using a separate runnable target. public static void yield(): This method is used by a currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. public final void join(long millisecond): This method is invoked by a thread on a second thread, causing the first thread to be blocked until the second thread is terminated. public static void sleep(long millisecond): This method causes the currently running thread to be blocked for the specified number of milliseconds. public static void setName(): The setName() method sets the name of the thread to the value specified. public static void is Alive(): This method returns a boolean value that indicates whether the current thread is alive or not. public static void setPriority: The setPriority method changes the priority of the thread to the specified value.     Creating a Java Thread In Java, two ways you can create a thread: Through implementing the Runnable Interface. Through extending the Thread Class.     1. Runnable Interface A thread created by implementing Runnable Interface will execute the code defined in the public method run(). Sample code will look like the one given below:       class SampleRunnable implements Runnable {   private String threadName = “Runnable Interface   Demo Thread”;   public void run() {     System.out.println(“Running ” + threadName );   } }     Given code will create a thread that will print Runnable Interface Demo Thread during execution. Before that, we need to start the created thread, and for that, we pass an instance of our SampleRunnable Class into the constructor of the Thread class.     The code will look like this:     Thread sampleThread = new Thread(new SampleRunnable ()); sampleThread.start();     2. Extending Thread Class In this method we create a class that extends the Thread class and we override the existing run() method in it. Here in order to run the thread, we will create an instance of the class that extended the Thread Class.     public class SampleThreadClass extends Thread {   private String threadName = “Thread Class Demo”;   public void run() {     System.out.println(“Running ” + threadName );   } }     Inorder to run the above thread, we will do the following:     SampleThreadClass threadClass = new SampleThreadClass (); threadClass.start();     This code when it gets executed will call run() and will print Thread Class Demo.     Multithreading in Java When we have more than one thread in a Java program, it becomes a multithreaded program and at this point, there are some more things we have to be aware of. There may be a scenario where multiple threads try to access the same resource and finally they might produce a hang. In this kind of scenario, there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Java has a provision for creating threads and synchronizing their tasks by using synchronized blocks. This way, we can efficiently manage the resource allocation to multiple threads during execution. But at the same time, synchronization sometimes produces a case called dead-lock. It’s a situation where one thread waits for the second one to finish object lock, but the latter is waiting to release the object lock of the first thread. By structuring the code properly we can avoid such dead-lock situations.     End note: We studied threads in Java. We also looked at two types of Java thread models and understood how the Java Thread Model (JVM) works. Additionally, we learned how to create the Java thread by using two methods, i.e. runnable interface and through extending the Thread class. Overall, we learned how the concept of thread is implemented in Java, and last but not the least, how multithreading works in Java.     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 27th, 2020, and has been updated on January 4th,  2022.
Wrapper Classes, Garbage Collection and Exception Handling in Java

Wrapper Classes, Garbage Collection and Exception Handling in Java

by Vibrant Publishers on May 20 2022
Introduction In this blog, we will look at some features of wrapper classes and how garbage collection works in Java. Java is an Object-oriented language. The primitive data types in Java are not objects. Sometimes, we will need object equivalents of the primitive types. An example is when we use collections. It contains only certain objects, not primitive types.To solve such issues, Java introduced Wrapper class that wraps primitive types into objects and each primitive has corresponding wrapper class.Garbage collection is the process of freeing memory allocated to an object that is no longer used. During run-time, when  objects are created, the Java virtual machine (JVM) allocates some memory to hold the object. The JVM uses the Mark and sweep algorithm internally for garbage collection.     Wrapper Classes: As the name suggests, wrap means to cover something, and wrapper class in Java does the same. Wrapper classes in Java are objects encapsulating Java primitive data types.Each primitive data type has a corresponding wrapper in Java, as shown below:       Primitive Data Type boolean byte short char int long float double Wrapper Class Boolean Byte Short Char Int Long Float Double     Since all these classes are part of java.lang.package we don’t need to import them explicitly.But if you are wondering about its use case, you must know that in Java, all generic classes only work with objects and they do not support primitives. So when we have to work with primitive data types, we have to convert them into wrapper objects. That’s where wrapper classes come in handy.This conversion can be done by either using a constructor or by using the static factory methods of a wrapper class. The example below shows how to convert an int value to Integer object in Java:       int intValue =1;   Integer object = new Integer.valueOf( intValue);     Here, the valueOf() method will return an object with specified intValue.Similarly, all other conversions can be done with corresponding wrapper classes.     Garbage Collection: It is a memory management technique that the Java language has implemented by scanning heap memory (where Java objects are created) for unused objects and deleting them to free up the heap memory space.Garbage Collection is an automatic process that each JVM implements through threads called Garbage Collectors to eliminate any memory leaks. There are four types of garbage collectors in Java namely Serial, Parallel, CMS & G1 Garbage Collectors depending upon which part of heap memory you are doing the garbage collection on. We can make use of them based on our requirements.The basic process of garbage collection is to first identify and mark the unreferenced objects that are ready. The next step is to delete the marked objects. Sometimes, memory compaction is performed to arrange remaining objects in a contiguous block at the start of the heap. Before the deletion of an object, the garbage collection thread invokes the finalize() method of that object that allows all types of cleanup.The recommended way of calling a garbage collector programmatically is given below:       public static void gc() {       Runtime.getRuntime().gc();   }     One important thing to note here is that Java is non-deterministic in garbage collection, i.e., there is no way to predict when it will occur at run-time. JVM will trigger the garbage collection automatically based on the heap size. We can include some hints for garbage collection in JVM using System.gc() or Runtime.gc() methods. But we can not force the garbage collection process.     Exception Handling: An exception is an event that disrupts the normal execution of a program. Java uses exceptions to handle errors and other abnormal events during the execution of the program. The master class for this is class ’throwable’ in Java.When we discuss exceptions, we must understand that they are different from Errors. Errors are impossible to recover while exceptions are recoverable. Errors only occur at run-time and are caused by the Java run time environment, while exceptions can occur at compile time as well and the cause is the application itself, not the Java compiler.In Java, exceptions that occur at compile time are called checked exceptions and run-time exceptions are called unchecked exceptions.A basic example of an exception is shown below:     class SampleException{     public static void main(String args[]){       try {         //code that raise exception      }      catch (Exception e) {       // rest of the program }      }   }     There are many built-in exceptions in Java.Users can also define their exceptions by extending the Exception class.A new exception is thrown using the ‘throw’ or ‘throws’ keywords. If there is only one exception to throw we use the throw keyword:       public static void findRecord() throws IOException {       throw new IOException(“Unable to find record”);   }     The main difference between throw & throws are:       Throw Used to explicitly throw an exception. The throw is followed by an instance. Used inside a function. We cannot throw multiple exceptions. It cannot be used to propagate checked Throws Used to explicitly declare an exception. Throws followed by a class. Used with function signature. It can declare multiple exceptions.  It can be used to propagate checked exceptions.     An exception is handled using a statement in Java.The statements for monitoring errors are put within the try block. The code that needs to be executed in case an exception occurs should be placed within the catch block. In the finally block, you need to put in code that is executed irrespective of whether an exception is thrown or not.   try : A try block is where you will put the code that may raise exceptions. catch: The catch block is used to handle a given exception. finally: The keyword ‘finally’ is used to define the code block that must be executed irrespective of the occurrence of an exception.   A sample code would be:       class ExceptionSample{    public static void main(String args[]){     try{      int intData= 0/3;      System.out.println(intData);     }     catch(NullPointerException e){      throw new NullPointerException(“There was an error in the calculation.”);     }     finally {System.out.println(“ We have completed the exception handling”);}     //remaining code    }   }     End note: In this blog we have studied wrapper classes and the necessity of it. We also looked at garbage collection and how it functions, as well as its types and the part of JVM in which it is stored. We briefly explored the process of Exception handling and its statement, which handles exceptional errors in the code.     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, 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 26th, 2020 and has been updated on January 11th, 2022.    
Flow Control and Assertions in Java

Flow Control and Assertions in Java

by Vibrant Publishers on May 20 2022
Introduction: This blog will elaborate on the concept of flow control statements in Java. We will also take a look at the syntax of flow control statements, their flow charts, and assertions which are used to validate the correctness of assumptions in Java programming.      Flow Control: Flow Controls are a set of statements in Java that govern the order in which statements are executed in a running program. Flow Control statements are mainly classified into three categories: Selection statements: if, if-else & switch Iteration Iteration statements: while, do-while & for. Transfer statements: break, continue, return.     1. Selection Statements: Selection statements are used in Java for selecting alternative actions during the execution of a program. The selection statements are:   Simple if statement:   The simple if statement follows the syntax below:     if (condition): {   statement   }     These kinds of statements are useful when we have to decide whether an action is to be performed or not, based on a condition. The condition may be an integer value or float value and the action to be performed is based on this condition, which can be in the form of a single statement or a code block. They must evaluate a boolean value. That is, it should return either a True or False.   The code flow is illustrated in the given activity diagram.     The if-else statement:   The Java if-else statement is used to decide between two actions, based on a condition. It has the following syntax:       if (condition1): { Statement1 } else { Statement2 }     The code flow is illustrated in the given activity diagram.   The switch statement:   The switch statement can be used to choose one action among many alternative actions, based on the value of a switch expression. In general, a switch case will be written as follows:       switch ( ) { case label 1 : case label 2 : … case label n : default: }     2. Iteration Statements: Iteration statements or looping structures that allow a block of code to execute repeatedly. Java provides three iteration mechanisms for loop construction. They are as follows:   The while statement:   The syntax will be as follows:       while (condition);   {   statement   }     Here the condition of the while loop is evaluated first and then if the resulting value is True, the loop gets executed. On the other hand, if the condition is False, the loop is terminated and execution continues with the statement immediately following the loop block.     The do-while statement:   The syntax is as follows:       do { statement } while(Condition );     Example:       int i=1; do{   System.out.println(i);    i++; }while(i<=10);     The above code block will print numbers 1 to 10 in a row. One thing to note here is that do loop is executed whenever the condition of the while loop is true. The activity diagram given below will explain the control flow:     The for( ; ; ) statement:   It is mostly used for counter controlled loops where we already know the number of iterations needed to be made.   The syntax is as given below:       for (int;condition;increment/decrement)  // code to be executed     The for( ; ; ) statement usually declares and initializes a loop variable that controls the execution of the loop. The output of the loop must be a boolean value. If the output is true, the loop body is executed, otherwise, execution continues with the statement following the for(;;) loop. After each iteration, the loop is executed, which will usually modify the value of the loop variable to ensure a loop termination. Note that this is only executed once on entry to the loop.     The enhanced for(:) statement:   This for(:) statement, otherwise called the enhanced for loop structure, is convenient when we need to iterate over an array or a collection, especially when some operation needs to be performed on each element of the array or collection.The syntax for an enhanced for(:) loop is shown below.       for (data_type item : collection)       3. Transfer Statements: Transfer statements are used for transferring control in a Java program. They are:   The break statement:   The break statement terminates loops ( for(;;), for(:), while, do-while) and switch statements, and it transfers control to the closest enclosing code block.       while (condition) {    if (condition ): {   statement     break;    }   }     The given diagram will explain the control flow in break statements:     The continue statement:   We use the continue statement to skip the current iteration of a loop. The diagram given here explains the control flow of the continue statement in a code block.     The return statement:   The return statement stops the execution of a method and transfers control back to the calling code. If the parent function is void, the return statement does not carry any value. For a non-void method, the return statement will always have a return value.     Assertions: In Java, assertions are used to validate the correctness of assumptions being made in the code. They are used along with boolean expressions and are mainly used for testing purposes.   We use the assert keyword for assertion in Java. This feature was introduced in Java JDK 1.4 onwards. Before that, it was only an identifier. There are two ways we can use assert keyword, namely:   assert expression; assert expression1: expression2;   By default, this feature will be disabled in Java. You have to enable it by typing the following command:       java -ea for all non-system classes   java -ea or for particular named packages & classes alone.     Example:       public void setup() {                         Connection conn = getConnection();                         assert conn != null : “Connection is null”;                         }     The above code will automatically throw an assertion error Exception in thread “main” java.lang.AssertionError: Connection is null.   Using assertions we can remove if & throw statements with a single assert statement.     End note: In this blog, we looked briefly at Flow control statements and its syntax and when to use them while coding. We also learned about assertions in Java.     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 25th, 2020, and has been updated on January 15th, 2022.    
Collision Resolution with Hashing

Collision Resolution with Hashing

by Vibrant Publishers on May 19 2022
While many hash functions exist, new programmers need clarification about which one to choose. There’s no formula available for choosing the right hash function. Clustering or collision is the most common problem in hash functions and must be addressed appropriately.     Collision Resolution Techniques: When one or more hash values compete with a single hash table slot, collisions occur. To resolve this, the next available empty slot is assigned to the current hash value. The most common methods are open addressing, chaining, probabilistic hashing, perfect hashing and coalesced hashing techniques.Let’s understand them in more detail:     a) Chaining: This technique implements a linked list and is the most popular out of all the collision resolution techniques. Below is an example of a chaining process.     Since one slot here has 3 elements – {50, 85, 92}, a linked list is assigned to include the other 2 items {85, 92}. When you use the chaining technique, the insertion or deletion of items with the hash table is fairly simple and high-performing. Likewise, a chain hash table inherits the pros and cons of a linked list. Alternatively, chaining can use dynamic arrays instead of linked lists.     b) Open Addressing: This technique depends on space usage and can be done with linear or quadratic probing techniques. As the name says, this technique tries to find an available slot to store the record. It can be done in one of the 3 ways –   Linear probing – Here, the next probe interval is fixed to 1. It supports the best caching but miserably fails at clustering. Quadratic probing – the probe distance is calculated based on the quadratic equation. This is considerably a better option as it balances clustering and caching. Double hashing – Here, the probing interval is fixed for each record by a second hashing function. This technique has poor cache performance although it does not have any clustering issues. Below are some of the hashing techniques that can help in resolving collision.     c) Probabilistic hashing: This is memory-based hashing that implements caching. When a collision occurs, either the old record is replaced by the new or the new record may be dropped. Although this scenario has a risk of losing data, it is still preferred due to its ease of implementation and high performance.     d) Perfect hashing: When the slots are uniquely mapped, the chances of collision are minimal. However, it can be done where there is a lot of spare memory.     e) Coalesced hashing: This technique is a combo of open address and chaining methods. A chain of items is are stored in the table when there is a collision. The next available table space is used to store the items to prevent collision.    To ace your interview, you can explore related topics. Learn about other data structures through the following blogs on our website:  The Basics of Stack Data Stucture  Trees Basics of hash data structures Know your Queue Data Structures in 60 seconds These provide insights into the various types of data structures and will give you better understanding.Pave the route to your dream job by preparing for your interview with questions from our Job Interview Questions Book Series These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
Basics of Hash Data Structures

Basics of Hash Data Structures

by Vibrant Publishers on May 19 2022
A Hash Table is an abstract data structure that stores data in the key-value form. Here the key is the index and value is the actual data. Irrespective of the size of the data, accessing it is relatively fast. Hence, hashing is used in search algorithms.     Hash Table: A hash table uses an array to store data and hashing technique is used for generating an index. A simple formula for hashing is (key)%(size), where the key is the element’s key from the key-value pair and size is the hash table size. This is done for mapping an item when storing in the hash table.   The below illustration shows how hashing works.   As shown above, we calculate the slot where the item can be stored using % modulo of the hash table size.     Applications: Hash tables make indexing faster, because of which they are used to store and search large volumes of data. Hash tables have 4 major functions: put, value pair and get, contains, and remove. Caching is a real-time example of where hashing is used.     Hash tables are also used to store relational data.     Issues with Hashing: Although hash tables are used in major search programs, they sometimes take a lot of time especially when they need to execute a lot of hash functions. Data is randomly distributed, so the index has to be searched first. There are many complex hash functions, hence they may be prone to errors. An unwarranted collision occurs if a function is poorly coded.     Types of Hashing: Probabilistic hashing: Caching is implemented by hashing in the memory. The old record is either replaced by a new record or the new record is ignored whenever there is a collision. Perfect Hashing: When the number of items and the storage space is constant, the slots are uniquely mapped. This method is desirable, but not always guaranteed. This ideal scenario can be achieved by mapping a large hash table with unique spots provided there is a lot of free memory. This technique is easy to implement and has a lesser collision probability. It may adversely affect the performance as the entire hash table needs to be traversed for search. Coalesced Hashing: Whenever a collision occurs, the objects are stored in the same table as the chain rather than being stored in a separate table. Extensible Hashing: Here the table bucket can be resized depending on the items. This is suitable for implementing time-sensitive applications. Whenever a resize is needed, we can either recreate a bucket or a new bit is then added to the current index with all the additional items and mapping is updated.   For example:     Linear hashing: Whenever an overflow occurs, the hash table is resized and the table will be rehashed. The overflow items are added to the bucket. When the number of overflow items changes, the table is rehashed.   A new slot is then allocated to each item.   To ace your interview, you can explore related topics. Learn about other data structures through the following blogs on our website:   The Basics of Stack Data Structure  Trees Know your Queue Data Structures in 60 seconds Basics of hash data structures These provide insights into the various types of data structures and will give you better understanding.   Get one step closer to your dream job!   Under our Job Interview Questions book series, we have books designed to help you clear your interview with flying colors, no matter which field you are in. These include:  HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked Check them out on our website!
Introduction to Data Structures

Introduction to Data Structures

by Vibrant Publishers on May 19 2022
Data Structures define how the data is organized, efficiently stored in memory, retrieved and manipulated. Data has to be defined and implemented in any program. Data Structures segregate the data definition from its implementation. This introduces a concept called data encapsulation which improves code efficiency. Data Structures are used to store the relationship between the data. A simple example is to implement database and indexing data using the Data Structures.     Data Objects and Data Types: Data Structures allow basic operations such as traversing, inserting, deleting, updating, searching and sorting. These operations are backed up by data objects and data types. You can compare data structure to the data definition, while an object is its implementation.   Data Objects: contain the actual information and can access the methods or information stored in the data structure. They can store, retrieve, or process the information in your program. Unless you garbage collect them at the end of the program, they continue to persist in the memory.   Data Types: define what type of data is stored in the variable. We can categorize them into primitive data types such as boolean, integer, float, or character and complex data types such as an integer array.     Real-world applications: All complex solutions rely on Data Structures. We use them in many scenarios as described below:   Memory allocation: This process uses heap and stack concepts for storing and retrieving data from memory.     Business operations: The complexity of data makes it even more complex to represent them in a more meaningful way. Graphs, for example, can help resolve the issue giving more clarity and meaning to the data.   Others: Whether it is building operating systems, or database management, Data Structures are helpful. Most modern technologies such as artificial intelligence, data analytics, or numerical analysis also need Data Structures for proper storage and representation.     Types of Data Structures: We can categorize Data Structures into:   Linear Data Structures: Some data structures are sequentially stored for easy storage and management. Files, queues, lists, arrays and stacks are some examples of linear data structures. Files can be stored and accessed sequentially. Arrays, linked lists, queues or stacks are accessed directly using the address pointers. Below are some representations of arrays, stacks, queues, and linked lists.     Arrays:     Queues and Stack:       Linked list:       Non-Linear Data Structures: When information doesn’t follow any specific storage pattern, but is still related, non-linear data structures are used to manage them. Non-linear data structures are complicated and not easy to manage.   However, many real-time applications are complex and need non-linear data structures like trees and graphs. To ace your interview, you can explore related topics. Learn about other data structures through the following blogs on our website:  The Basics of Stack Data Structure  Trees Know your Queue Data Structures in 60 seconds Basics of hash data structures These provide insights into the various types of data structures and will give you better understanding. Get one step closer to your dream job! Pave the route to your dream job by preparing for your interview with questions from our Job Interview Questions Book Series These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
Linked List Operations

Linked List Operations

by Vibrant Publishers on May 19 2022
A linked list supports the following operations: Traversal Insertion Deletion   All these operations are supported by single, double or circular linked lists. Before going into various operations the data structure supports, it is important to understand how to find the length of a linked list. Once the node pointer and count are initialized to 0, assign the head pointer to the current. The list has to be iterated using a counter variable until the current is not NULL. Increment the counter on every traversal, then return the count.   A pseudo-code to find the node length is illustrated below:     getCount()   {     //initialize node     Node temp = head     Count =0     While (temp !=null)     {       //increment count and       Count = Count + 1       //move to next node       temp = temp.next     }     //length of the list     return Count   }   Let’s see the list operations in more detail.     A) Traversal: Initialize the linked list to make sure the pointer address is set to the first node. Loop until the pointer until the end of the list and access the value stored in each node. Make sure to read the address of the next node each time. Assign the next address to the pointer and loop until the end of the list.   A simple pseudo-code is shown below:     head = linkedList   while head !=null   {     var = head ->value       /***  Process in your desired way  ***/     Print var     Head = head ->next   }     B) Insertion: In a singly linked list the header points to the first node and the tail address will be null. When you create a new node, assign the previous node’s next address to the new node’s address and the new node’s next address to null.     Doubly and circular linked lists work in a similar way. The only difference addition is the node’s previous pointer. Once you add a new node to the list, follow the same steps above to assign the node’s next address. In addition to this, the new node’s previous address will have to be assigned to the old node’s address.     C) Deletion: Given a linked list, deletion of the last node is fairly simple. The next pointer of the second last one needs to be updated to null. As the pointer is lost, that node will be the last node. However, if you are deleting a middle node then, you must traverse through the node and replace the previous node’s next address with the deleted node’s next address.   A simple algorithm can be as shown below:     CurrentNode = head   curPos =1   //start from the 1st node   prevNode = currentNode   currentNode = currentNode -> Next   curPos ++   If currentNode != NULL   {     prevNode->Next = currentNode -> Next     Delete currentNode   } You can learn more about ways to link lists through our blog Little Known Ways to Link Lists. Get one step closer to your dream job!   Pave the route to your dream job by preparing for your interview with questions from our Job Interview Questions Book Series These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
Data Structures for Sets

Data Structures for Sets

by Vibrant Publishers on May 19 2022
A set is a group of unique, yet similar items related to each other where order doesn’t matter. For example, a set of balls as shown in the picture is a real-world example off a set.         Below represents a set of balls, but none of them are the same. We can also arrange them in any order. We cannot extend the set to add new items as they are finite.  ball={football, baseball, basketball, cricket ball, tennis ball}     How are sets implemented? Set is an abstract data type that uses a List, an Associative array or a Bit array for its implementation. We can implement a simple data representation of similar items using a Linear list. However, if you are representing Boolean results like True or False, a Bit array comes in handy as it requires very little storage space. Hash tables and binary trees are used to depict search algorithms and Associative arrays are very useful in those scenarios.         A null set contains no elements. Null sets are used when we are not sure if the elements will be populated as a result of a runtime operation. The values are dynamically populated in a null set.     How are sets implemented? A set supports the following operations:   Subset: smaller set of the larger set. In the below example, A is a Subset of a larger portion of B. A subset returns 1 if the first set has some elements that are a subset of B, else returns 0.   Here, A is a subset of B and includes A={4,2,1}   Union: Returns a unique set of elements of both Set A and B. For example, pick all the musicians who play a band, sing a chorus, or sing both, without including the duplicates.   Intersection: When you need a set of elements common to both sets, you can create an intersection. Below is a representation of the intersection of sets A and B.         Types of sets: A Mutable Set: Sets can be mutable if you want to create them during runtime. The size of the set can be dynamically defined and elements can be added or removed during runtime. You can create, add, delete, or check the capacity when working with a mutable set.   An Immutable Set: When you are sure of the set size and the elements, immutable sets are best. These are static, so you cannot alter the set. You can check the size if empty, build or read the element of the immutable set.   A Disjoint Set: This set is a collection of subsets that do not overlap with each other.       A very good way to represent these singleton sets is using a linked list. Elements can be added to the set by pointing to other sets. Undirected graphs are another way to use a disjoint set. Disjoint set supports find, union and subset operations.   A Sparse Set: This is similar to the Bit set with the only difference being that the elements are indices of a larger array. As managing a very large array is a big hassle, a sparse set lets you easily break them into multiple sets and reference the parent set.Below is an example of a sparse set.     When you use a sparse set, the entire set is split into multiple coarse-grained arrays and each array stores the indices. This makes search faster and simpler. A sparse set supports Union and intersection operations. To ace your interview, you can explore related topics. Learn about other data structures through the following blogs on our website:  The Basics of Stack Data Structure  Trees Basics of hash data structures Know your Queue Data Structures in 60 seconds These provide insights into the various types of data structures and will give you better understanding.   Get one step closer to your dream job! by preparing for your interview with questions from our Job Interview Questions Book Series. These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
Little Known Ways to Link Lists

Little Known Ways to Link Lists

by Vibrant Publishers on May 19 2022
A linked list is a list of connected nodes. Each node stores the value and address of the next or the previous node. Since the address is stored in the node, linked lists can be dynamically allocated. Linked lists are used in implementing dynamic arrays, stacks, and queues. However, they consume extra memory for storing the address of the next node. These sequential lists are very cumbersome for traversing longer lists.     Array vs Linked List: Compared to an array, a linked list can be easily traversed if the list size is smaller. Unlike arrays linked list items cannot be randomly accessed. Lists store the address of the next node, hence consuming more space. The below picture shows how a linked list can store items anywhere and be accessed by the address sequentially. The address can be used to locate the element. This makes insertion, deleting or updating operations in a linked list faster.         Arrays are stored in memory sequentially and accessed using the array index. Hence, arrays take a longer time to insert, delete or update.     Types of Linked Lists: Linked lists are of 3 main types:   A Singly linked list: They contain a list of nodes that have a value and address to the next node. The last node’s address is always null. The below illustration shows that a singly linked list can traverse forward only.     Stacks, queues and dynamic arrays are some implementation areas where singly linked lists are used. They are best suited for smaller forward traversals and when the address to the element is unknown.     A Doubly linked list: A doubly linked list has 3 parts – node value, address to the next node and address to the previous node. The first node’s address to the previous element and the last node’s address to the next node will always be null. A doubly linked list can hence traverse both forward and backward.     We use a doubly linked list to navigate either forward or backward direction, when using an array or other data structures. However, both the next and previous address needs to be stored in the node and hence consume more memory.     A Circular linked list: When the last node’s address points to the first node, the linked list is called a circular linked list. A circular linked list can be singly or doubly linked.   Below is an example of a singly linked circular list.         A doubly linked circular list is just like the doubly linked list except that the last node’s next pointer stores the address of the first node and the first node’s previous pointer stores the address of the last node.     The operating system’s task scheduler, circular queues and multi-player games are great real-world examples of a circular linked list.   Learn more about Linked List operations here.   Get one step closer to your dream job!   Pave the route to your dream job by preparing for your interview with questions from our Job Interview Questions Book Series. These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
Basics of Stack Data Structure

Basics of Stack Data Structure

by Vibrant Publishers on May 19 2022
Stack is an abstract, Linear Data Structure that follows the Last-In-First-Out (LIFO) principle. All data operations are done at the top of the stack which means the last item inserted is first accessible. Insertions in a stack are called “PUSH” and deletions are termed “POP”. Other abstract data types such as Array, Structure, Pointer, or Linked List are used to implement the stack. It is most commonly used in real-world scenarios such as a stack of books or a stack of coins.     Stack Operations: Initialize stack and de-initialize once done. To support these tasks, the stack has to implement these basic operations:   Push:Lets you store an item on the stack This operation checks if the stack is full and exits. If the stack is not full, add the data and increment top to point to the next empty slot.   This pseudo code represents the Stack push operation:     push(item)   {     If stack is full     {       exit     }     else     {       top= top +1       stack[top]=item     }   }   Pop:Lets you access an item from the stack Pop operation checks if the stack is empty and exits for an empty stack. If the stack is not empty, we access the item at which the top is pointing. The top position is decremented by 1.     Below pseudo-code shows a simple representation of pop:   pop(item)   {     If stack is empty     {       exit     }     else     {       item=stack[top]       top= top -1       return item     }   }   Peek:Lets you read the top item of the stack without having to remove it   peek()   {     return stack[top]   }   isFull:It returns a Boolean and checks whether the stack is full before the push operation. The pseudo-code below checks if the top is at the max. If it is, that means the stack is full.   bool isfull()   {     if(top == MAXSIZE)     return true;     else return false;   }   isEmpty:It returns a Boolean and checks if the stack is empty before the pop operation. We sometimes use an array to implement stack and pointers to indicate top which is initialized to -1. So we check if the top is equal to -1, which means the stack is empty.   bool isempty(){     if(top == -1)     return true;     else     return false;   }   Rotate:Rotates the top-most items in the stack.   Swap:This operation lets you exchange 2 top-most items in a swap. This is most suitable for implementing sort algorithms.   To ace your interview, you can explore related topics. Learn about other data structures through the following blogs on our website:  The Basics of Stack Data Stucture  Trees Know your Queue Data Structures in 60 seconds Basics of hash data structures These provide insights into the various types of data structures and will give you better understanding.   Get one step closer to your dream job!   Pave the route to your dream job by preparing for your interview with questions from our Job Interview Questions Book Series These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
Know your Queue Data Structures in 60 seconds

Know your Queue Data Structures in 60 seconds

by Vibrant Publishers on May 19 2022
A queue is a powerful Data Structure that controls the asynchronous flow of data through the buffering technique. Unlike Stack, a queue is used to insert data from one end and retrieve it on the other.This abstract data structure follows the First In First Out(FIFO) concept where the data stored first is accessed first.  We can implement queues using Structures, Arrays, Linked-lists or Pointers. Queue uses 2 data pointers – head and tail for Enqueue and Dequeue operations     Applications: A ticketing system is a real-world example off a queue where the person first in the line is served first and the one at the end of the line is served last.   A queue is a special Data Structure efficiently used for buffering. This concept works similarly to the print queue where the jobs buffered are printed based on the order of requests received. We can also use queues to prioritize interrupts to address based on their priority.  Another simple example of a queue system is the first-come-first-served calls answered in a call center.     Queue Operations: The life cycle of a queue involves initializing, adding items to the queue (enqueue), retrieving items from the queue (dequeue) and deleting the queue from memory. Learning Queue is incomplete without understanding the steps involved in Enqueue and Dequeue operations.         Enqueue:   Enqueue operation manipulates only the tail pointer and does not hinder the head pointer. We insert data in a queue with the following steps:   Check if the queue is empty  If the queue is not empty, stop the operation  If the queue is empty, increment the tail pointer to point to the next available space  Insert the data in the newly created space  Now that becomes the current tail element of the queue     Algorithm for Enqueue:     Enqueue(data)   {     if queue is empty   {     tail = tail +1     queue[tail] = data   }   else   exit   }     Dequeue:   The dequeue operation does not manipulate the tail pointer. Here, data is removed from the Queue with the following steps: Check if the queue is empty  If the queue is not empty, stop the operation If the queue is not empty, move to the head of the queue Remove the data and increment the head pointer to the next position Now that becomes the current head element of the queue     Algorithm for Dequeue:     Dequeue( ){     if queue is empty     exit     else{       head = head +1       queue[head] = data     }   }     Types of Queues: A simple queue is a linear queue. We insert data until the queue becomes full. A circular queue, commonly referred to as a Ring buffer, is a linear queue where the head of the queue is connected back to the tail. Data is enqueued in the head and dequeued from the tail       To ace your interview, you can explore related topics. Learn about other data structures through the following blogs on our website:  Basics of Stack Data Stucture  Trees Basics of hash data structures These provide insights into the various types of data structures and will give you better understanding.   Get one step closer to your dream job!   Pave the route to your dream job by preparing for your interview with questions from our Job Interview Questions Book Series. These provide a comprehensive list of questions for your interview regardless of your area of expertise. These books include: HR Interview Questions You’ll Most Likely Be Asked (Third Edition)  Innovative Interview Questions You’ll Most Likely Be Asked Leadership Interview Questions You’ll Most Likely Be Asked You can find them on our website!
All You Need To Know About Arrays

All You Need To Know About Arrays

by Vibrant Publishers on May 19 2022
An array is a fixed collection of items of the same data type represented by a single variable. We can access the sequential Data Structure item called ‘element’ using an array index. Arrays can be single-dimensional or 2 dimensional with rows and columns.To reach node E we start from node A and move downwards, as deep as we can go. We will reach node C. Now, we backtrack to node B, to go downwards towards another adjacent vertex of B. In this way, we reach node E.       An array is used to implement other Data Structures such as Stacks, Queues and Lists.     How is an array represented? You can define integer arrays, string arrays or object arrays. Array size has to be defined when it is declared. This ensures memory is allocated based on the array size.   For example: int myarray[5];   We can initialize an array either during declaration or later.   For example: type myarray[size] = {values/elements}   Arrays can be declared in many ways depending on the programming language used. For example, a string in C is represented by a character array. Here, we have declared and initialized a character array.   char charArray = {‘ H ’,’ E ’,’ L ’,’ L ’,’ O ’}.   We can declare an array of Strings in the following way:   String names[3] = {“John”,”Kelvin”,”Simmons”} Array index [0]        John Array index [1]        Kelvin Array index [2]        Simmons     Array Operations: An array supports the following basic operations:   Insertion – insert an array element at the index and ensure there is no overflow Deletion – delete an array element at the index Traverse – loops through and prints all the array elements sequentially Search – search by using an array index or by the value Update – update the array element of the index   Let’s see how each operation works.         Array Insertion and Traversal: You can insert one or more elements into an array, at the beginning, end or any index. Let’s see the steps of inserting an array element at index 3.   int arr[5]={10,9,8,6}  insert 7 at arr[3]   Start traversing from the last position and move to the next until you reach the 3rd position. Remember, arr[0] is the 1st element. We need to reach arr[3] which has value 6 in our example. Move the arr[3] value to the right and insert 7 in arr[3].     Array deletion and Traversal: Deletion at the beginning and end of the array is straight forward. However, when you have to delete from the middle of the array, rearrange the element to occupy the space that has been emptied.   Let’s take the same example as above and delete the element with value 8 which is arr[2].   Traverse through arr[3] and delete the value of arr[3]. This value now becomes null. Go to the next index arr[4] and move this element to the 3rd position. Stop the move operation if this is the end of the array.   The new array now has these elements: {10,9,6}  Array Search: We can search an array for a specific element using the index or value. When you traverse through an array in a loop iterators reference the element and help to move to the next position.   Below is a pseudo code to indicate the same :     for(iter=0;iter<n;iter++) {   if ( arr[iter]== item)   Return iter; }     Get one step closer to your dream job! Check out the books we have, which are designed to help you clear your interview with flying colors, no matter which field you are in. These include HR Interview Questions You’ll Most Likely Be Asked (Third Edition) and Innovative Interview Questions You’ll Most Likely Be Asked.
Components required for JMS

Components required for JMS

by Vibrant Publishers on May 19 2022
JMS refers to Java Messaging Service which allows the software developers to loosely couple applications. It has an API (Application Programming Interface) through which we can receive, send, read, and create enterprise system messages. JMS is a message oriented product which is quite expensive and complex. It provides an interface (Java) to write infrastructure code and allow solutions to be built easily and quickly.   Following are the main components of JMS: Administered: ObjectsDestinationConnectionFactory Connection Session Objects: MessageProducer, MessageConsumer, MessageListener, MessageSelector   The component relationship could be explained with the below diagram.   1) Administered Objects:   Following are called as the administered objects as they are created by the JMS provider administrator: Destination ConnectionFactory     Destination:   This object has the configuration information provided by JMS provider. This object is used by the Client to specify the destination for messages to be send and location to receive the messages.   There are 2 types of Interfaces Destination uses. They are: Queue – It belongs to PTP (Point To Point) model Topic – It belongs to pub/sub (Publish / Subscribe) model     Connection Factory:   This object has the connection configuration information (IP address) provided by JMS provider. The connection is obtained through the Java Naming Directory Interface (JNDI) which enables the client to create a connection and get connected to the JMS server.     2) Connection: This component provides the connection (physical) to the JMS server. The physical connection is obtained with the help of ConnectionFactory object which provides the instances of configuration details to connect to the JMS server.     3) Session: This component is responsible to receiving and sending messages, and for handling acknowledgements and managing transactions with the help of JMS objects.   4) Objects:   It refers to the JMS object which are maintained and created by the admin that are used by the JMS clients. The following objects are used to receive and create messages in JMS: MessageConsumer MessageProducer MessageSelector:  This is used to filter the message that does not meet the specified criteria. MessageListener:  This is used to process and receive messages asynchronously     MessageConsumer:   MessageConsumer is for receiving messages synchronously or asynchronously to a particular destination which is created by the session object.   In case of synchronous communication, the consumer calls the any one of the methods receive or receiveNoWait and in case of asynchronous communication, the client registers MessageListener and starts consumer.   Almost all the messages in Java Messaging Service are exchanged asynchronously between clients where the producer never receive acknowledgement from consumer.     MessageProducer: MessageProducer is for sending messages either via PTP or through pub/sub. In PTP (Point-To-Point) model, the destination is known as queue and in pub/sub model, the destination is known as topic.   In producer, we can set the delivery mode either as NON-PERSISTENT or PERSISTENT using the setDeliveryMode method. Non-Persistent has less overhead as the messages are not logged in the server or database.   We can also use the setPriority method to set the message priority. 0 indicates low priority and 9 indicates high priority. We can also use setTimeToLive method to mention the life time of the message in milliseconds.     MessageSelector:   MessageSelector belongs to String object which is used to filter the message that does not fit into the specified criteria.   The message selector can examine the header and compares an expression which is present in the String. The example for expression comprises of arithmetic operators, relational operators, string literals, and logical operators.     MessageListener:   To process messages asynchronously, we have to use instantiate the MessageListener interface. We have to perform the following steps to process and receive messages asynchronously: Create object which implements MessageListener interface and invoke the onMessage method Use setMessageListener method to register with the session object Use Connection object’s start method to start receiving messages.  
REST APIs and Implementations

REST APIs and Implementations

by Vibrant Publishers on Jan 01 2022
Introduction Building a RESTful service is specific to every programming language. There are different libraries and implementations of REST in each programming language. In this post, we are going to look into the details of how Java language implements REST and how we can build RESTful applications in Java. Java and REST REST got into the Java world through the release of JavaEE 6. It included the JAX-RS API that is responsible for REST API creation using Java. JAX-RS follows the REST framework and the HATEOAS principle. The current version of JAX-RS is version 2.0. JAX-RS uses annotations for ease of development and deployment of web services. These annotations are part of the java package javax.ws.rs. The basic annotations provided by JAX-RS are: @Path @GET, @POST, @PUT, @DELETE, @HEAD @Produces @Consumes @PathParam JAX-RS Implementations There are many implementations of JAX-RS available in Java. They show minor variations in their ways of defining and using REST APIs. But the basic procedures remain the same in all of them. A few of those implementations are: Jersey: This is the reference implementation of JAX-RS from Sun Microsystems. This is one of the most widely used libraries for building RESTful services in Java. Spring REST: This REST library is part of the Spring web framework. If you are using the spring framework for building your application, making it restful is very easy. It follows an MVC architecture. RESTeasy: RESTeasy is developed by JBOSS and is part of their application server. This implementation has server-side caching and GZIP compression features. Apache CXF: This implementation of JAX-RS specification is by Apache. It is an open source library available for free download and modification. Restlet: This is again an open source implementation of JAX-RS 1.1 specification. It is a light-weight library that supports major media types and all REST specifications. Serialization Frameworks When we implement REST APIs depending on the request and response types, one would always need to use some kind of object serializers. The following are some of the popular serialization frameworks: JAXB It stands for “Java Architecture for XML Binding”. This library helps in the conversion of java objects into an XML data format and vice versa. One can find this API in the javax.xml.bind package. There are many implementations of JAXB in the form of annotations that can be used in java code for conversions. JACKSON Jackson is a JSON processor that is used widely in the Java world for converting Java objects into JSON document format and vice versa. This implementation is part of the Jersey library. Building a RESTful Application As you can see, there are many choices in the Java world for building a RESTful application. The libraries and implementations listed here can be used with any Java framework. It is our choice to go for a particular library based on our use case and technologies that we are adopting. General steps for building any RESTful services would be: Identify resources and build URIs Select or build representations. Identify method semantics. Select response codes. The below diagram shows a simple technology stack for a RESTful application.         Summary After the introduction of REST in JavaEE from version 6 onwards, a lot of implementations and libraries came into existence. The JAX-RS has got strict implementation principles and guidelines for building RESTful API services. As a java web services developer it is important to understand which library to use and how to build RESTful services adhering to the REST principles.  
Rest Resources, HTTP Methods and Status Codes

Rest Resources, HTTP Methods and Status Codes

by Vibrant Publishers on Dec 29 2021
Introduction REST stands for REpresentational State Transfer. We use REST while doing web services programming to communicate between client and server. There are many concepts involved in the REST world that are required to know for building a RESTful service. We will have a look at some of those building blocks of RESTful service here. ResourcesEverything in REST is a resource. It can be a document, an image, a collection of objects, information stored in the database, etc. REST requires a Unique Resource Identifier (URI) associated with each resource for it to be accessible over the internet. URI is the endpoint of a given resource. The state of each resource is also an important factor while accessing it. The client-side can use the resource in the best possible way when it knows the type and state of the resource. So REST responses will have a machine-readable explanation about the resource. That is a resource representation. It can be the details of the resource, its format, size, etc. REST and HTTPWe saw resources can be of any type, but there are some rules in the REST world while interacting with resources. REST requests and responses use the HTTP protocol. There are specific HTTP message formats that REST clients have to follow while sending a request. The response from the server also will be in a certain message format that a REST client can decode.There are eight different message formats that HTTP has defined. The following are the commonly used four methods. GET: Get a representation of a given resource. DELETE: Destroy the specified resource. POST: Create a new resource, based on the given representation. PUT: Update the state of a given resource with the one described in the given representation. The main aspects of choosing these methods are because of its adherence to the REST specification (RFC 2616). The two main properties in RFC 2616 are safety and idempotency. Safety here means the ability of the client to make requests without altering the state of a given resource. Idempotency means the effect of doing an operation will be the same for single or multiple times. Request Response Structure Now we will see how these methods are used in an HTTP request and response in a RESTful way. A REST client library will create a REST API request in the following format: The API response, in turn, will have the following format:Following is a sample GET request:Method: GET URL: http://api.clothshop.com/shirtsWhich will provide the following response: HTTP/1.1 200 Content-Type: application/json { “id”: 10, “name”: “Lee Shirt”, “color”: “yellow”, “price”: “$30” }HTTP Status CodesWhenever we do a REST API request to the server, the server will return a response with an HTTP status code. Each status code will tell a brief about the response from the server. These status codes will be part of the HTTP header which the client will decode and understand. These are wrapped with HTML code and all HTML /HTML5 browsers are capable of understanding these HTTP codes. The following table summarizes the major status codes and their meaning. HTTP Status Codes Summary 200 OK. Request successful. 201 Resource Created. 204 No content found. 400 Bad Request. 401 Unauthorised. 404 Resource not found. 405 Method not allowed 500 Internal Server Error. Summary There are multiple building blocks in the REST framework that makes web services communication happen over the internet. HTTP protocol is one of the main blocks upon which the entire REST communication is built. While designing a REST API it is important to consider the nature of resources that we are planning to expose as APIs. Also it is important to know various HTTP methods and status codes that will help us in the process of accessing these resources at the client side.
JAX-RS Basics

JAX-RS Basics

by Vibrant Publishers on Dec 29 2021
Introduction The implementation of REST framework in Java is done through JAX-RS API. It serves as the basic building block for RESTful services in Java. Let’s take a look at the basics of JAX-RS. JAX-RS JAX-RS (Java API for RESTful Web Services) is also part of the JSR, with a detailed specification definition. Starting with JAVA EE 6, this technology has been built, similar to RESTful WCF in .NET, that exposes the RESTful service by using some simple annotations in the conventional method.The current version of JAX-RS in use is version 2.0. The below-given diagram shows the features of this version. HTTP Methods and annotationsWe know that the REST APIs work through HTTP protocol. The following are the HTTP methods used in REST via annotations. @GET: Defines HTTP GET request method. @PUT: Defines HTTP PUT request method. @POST: Defines the HTTP POST request method. @DELETE: Defines HTTP DELETE request method. A basic GET requestLet’s see how a basic HTTP GET request is implemented using JAX-RS API using a simple ‘Hello World’ example.   @Path(“/”)       public class SampleWebService {         final String XMLNS_NAMESPACE = “http://localhost:8080/rest/service”;         final String ROOT_NODE = “root”;              @GET          @Path(“/json/hello”)          @Produces(MediaType.APPLICATION_JSON)          public JAXBElement<String> getHelloWorldJSON() {         JAXBElement<String> result = new JAXBElement<String>(new QName(“”, ROOT_NODE), String.class, sayHelloWorld());          return result;        }         ……….        }             private String sayHelloWorld() {        return “Hello, this is a sample JAX-RS API!”;       }     @GET indicates that the service can be accessed directly in the browser address bar (for the GET method in HTTP requests). @Path used here twice, the first on Class, the base address of service, and the second time on a method, representing the URL of a specific service method. @Produces defines the output type of method. Here we are opting for a JSON string format output.   We will also deploy the web.xml file in the root folder of the application.                                                                           Now this REST API can be accessed at the address http://localhost:8080/rest/service/json/hello This will return output in the HTML browser as {“root”: “Hello, this is a sample JAX-RS API!”}In this way, any resource at the server side is made available to the client through simple REST API calls over HTTP. Similarly, create, update and delete operations on a resource can be done at the server-side by calling corresponding REST API commands from the client-side. Content NegotiationWhile using REST APIs, we are sharing resources that are represented by multiple data types. JSON and XML are the two most popular content types that are commonly used. The JAX-RS annotations @Produces, @Consumes are used to specify the content format. As the name suggests, @Produces annotation specifies the type of content produced by a method. The @Consumes annotations specify the type of content that a method is expecting as input. For example, @Produces({“application/xml,application/json”})means the method will produce content in two MIME types, XML and JSON. One thing we should understand here is the differences between data and data format. Data can be anything and the data format is the representation of that data. Data transformations occur before or after transmission.  When there is an equal match with the request and response type, the server will return a 200 OK response or a 400 Bad Request if the data format is not matching with the MIME type that the server expects.  Now, let us say the client does not specify any content format, then in JAX-RS 2.0 there is a factor called ‘QS’ ie. ‘QUALITY FROM SERVER’. It can take value from 0 to 1. So in the above scenarios ‘qs’ factor instructs the server to choose a content type that is the default content format. If we consider, @Produces({“application/json qs=0.8; ,application/xml; qs=0.75”}),  it is clear that the server has to consider the JSON format. Request Matching Request matching is a process where the client API request is mapped to the corresponding method at the server-side. This is achieved using the @Path annotation. The value of the @Path annotation is an expression that indicates the relative URI. Consider the following example:  @Path(“/orders”) public class OrderResource {    @GET    public String getAllOrders() {        …    } } Here if you send an HTTP request of GET /orders to the server, that would dispatch to the getAllOrders() method. The JAX-RS has strict precedence and sorting rules for URI expressions matching. This is based on the ‘most specific match wins’ algorithm. You must also abide by the URL encoding rules that only allow alphabetic characters, numbers and some special characters only. Summary The JAX-RS library has specifications and rules that will help a developer to build web services in the RESTful way. In JAX-RS the importance of annotations and how HTTP methods are mapped using these annotations are important to understand. The request – response matching mechanism and specifying the content type while making a request are also important concepts in JAX-RS implementation. 
JAX-RS Response Handling

JAX-RS Response Handling

by bhagyashree kolge on Dec 22 2021
Introduction The JAX-RS specification for building RESTful services gives clear directions for handling API responses. Some specific annotations and classes are available for this task. Let’s have a look at how the responses are handled at the server-side of JAX-RS web services. Building a JAX-RS ResponseBy default, JAX-RS supports response messages of common Java types. These responses can be either in plain text, XML or JSON format. JAX-RS provides javax.ws.rs.core.Response class for creating responses. The below code sample will produce a response in the plain-text format. @GET   @Path(“color”)   @Produces(TEXT_PLAIN)   public Response getTextileColor()   {     if (color) {       return Response.ok().build();     }     // return 404 Resource not found error.     return Response.status(Response.Status.NOT_FOUND).build();   } }   Normally a response will contain a resource that the client is requesting from the server. The resource representation in java must be marshaled and converted into the media type specified in the REST API request. A POJO [Plain Old Java Object] is converted into REST response format through the process as given below:Response EntityThe response entity is also referred to as ‘payload’ or ‘message body’. While using JAX-RS, response entities are mapped to and from java types by Entity Providers that implement the JAX-RS interface MessageBodyWriter.Message Body WriterThe JAX-RS Message Body Writer converts java types to a stream. There are three main methods in this class. They are isWritable(), getSize() and writeTo() which can be overridden while implementing our logic. Successful ResponsesSuccessful responses are sent along with corresponding HTTP codes. They range from 200 to 399. The JAX-RS response specifications are similar to that of HTTP specifications for GET, PUT, POST, DELETE methods. If an API request is successful and the response contains a message body, then the status code will be 200, ‘OK’. Otherwise, it will be a 204, ‘No Content’ message in the response status. Error ResponsesError response codes range from 400 to 599. These are used based on failure cases. By examining the error code that is returned to the client, we can understand the type of issue faced at the server-side. @Produces AnnotationThe @Produces annotation mentions the media types that a resource can produce and set back to the client. If no method can produce the resource in the specified media type, the REST library will send a “406 Not Acceptable” error to the client. SummaryIn general, responses are built according to the request type. There are classes in JAX-RS that help in the process of building responses. The responses are handled with specific HTTP codes that are sent along with the responses. These codes help the client application to understand the server-side better.  
JAX-RS Exception Handling

JAX-RS Exception Handling

by Vibrant Publishers on Dec 22 2021
Introduction An exception is a case where an unexpected outcome occurs during computation. This often disrupts the normal flow of the program. There are different mechanisms available to handle an exception. Here in this article, we are going to see some of the mechanisms that JAX-RS has implemented to handle exceptions in its API services. JAX-RS Exceptions A RESTful API may throw exceptions at many scenarios and its proper handling is important for the functionality of that service. In JAX-RS exceptions are handled in two ways. By throwing a web application exception. By mapping exception using exception mapper.   Throwing a web application exception The WebApplicationException is a special RuntimeException class that JAX-RS has implemented in itself. By throwing a WebApplicationException, JAX-RS can abort a particular service method. This exception class can take an HTTP status code or a Response object as its constructor parameter. Let us consider the following code snippet:  @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (registration == null) {               Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND);               builder.type(“text/html”);               builder.entity(“   Registration Not Found   “);               throw new WebApplicationException(builder.build());           }           return registration;   }       Here if the object ‘registration’ is null, we create a response using the ResponseBuilder class. Here since we could not find any registration number we are setting the HTTP response code as 404 NOT_FOUND. This response class is then passed to WebApplicationException class which then throws this message as an exception to the client. Throwing a Not Found Exception The above code can be made even simpler by just throwing a NotFoundException. Because this class extends the WebApplicationException. So instead of creating a response using the ResponseBuilder, we can throw this exception as shown below:   @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (registration == null) {                     throw new NotFoundException(“Registration NOT found”);           }           return registration;   }       Mapping an exception using ExceptionMapper JAX-RS also provides a mechanism to map generic or custom exceptions into a JAX-RS response. This is done using the ExceptionMapper interface. So the code that throws the exception will implement the ExceptionMapper interface. Let us consider the above code snippet itself. There we were using the exceptions that already existed. Now let’s have a look at how we can use the ExceptionMapper in the same scenario. First, we will build a custom ‘RegistrationNotFoundException’ class.  public class RegistrationNotFoundException extends RuntimeException {       public RegistrationNotFoundException(String message) {          super(message);       }   }     Now we will map this exception to HTTP status message 404 – Resource NOT_FOUND and will build a JAX-RS response. The RegistrationNotFoundMapper class will do this job. Note that it is implementing the ExceptionMapper interface.  @Provider   public class RegistrationNotFoundMapper implements ExceptionMapper {       public Response toResponse(RegistrationNotFoundException exception) {           return Response.status(Response.Status.NOT_FOUND).                   entity(exception.getMessage()).                   type(“text/plain”).                   build();       }   }       Here the @Provider annotation is used for automatic discovery. You don’t need to declare the exception manually. The JAX-RS runtime will automatically discover it during the provider scanning phase. Finally, you throw the RegistrationNotFoundException.   @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (exam == null) {               throw new RegistrationNotFoundException(“Registration is not Found”);           }           return registration;   }    This will invoke RegistrationNotFoundMapper.toResponse and will send the custom response to the client.   The mapping of exceptions in this case is explained in the below given diagram.     Exception Mapping Mechanism Exception mapping providers map a runtime or checked exception to an instance of JAX-RS Response. If multiple exception providers are available, then one with the highest priority will be chosen. What will happen if an exception mapper fails to map an exception and that itself throws an error? In this case, a server error with status code 500 is returned to the client as a response. Summary There are different exception handling mechanisms available in JAX-RS. The simple and easy choice would be to use the built-in WebApplicationException. If there is a need to use custom exceptions, then the ExceptionMapper interface can be implemented in the code.    
JAX-RS Request Handling

JAX-RS Request Handling

by Vibrant Publishers on Oct 28 2021
Introduction Creation and handling of API requests are very important while implementing RESTful services. Invoking a request, mapping of the request, handling the request call and responding to it, etc. are very essential steps in building RESTful services. In this article, let’s have a look at how the Java REST library, JAX-RS handles requests from the clients. JAX-RS Request Handling There are multiple stages for handling a request in JAX-RS. The diagram below shows some of the main aspects of JAX-RS request handling.     JAX-RS uses annotations at the server-side for handling requests from the client. Different types of annotations match different use cases. We are going to have a look at those annotations that are used while handling a client-side API request. @Path Annotation If you want a Java class to be able to handle REST requests, the class must add at least one @Path (“/”)” annotation. The value of this @Path variable can be simple strings to complex regular expressions. Some of the things that we must know about the @Path annotations are: Priority Check Rules  First, check the number of matching characters in a @Path.  Second, check the number of embedded template expressions.  Finally check the number of non-default template expressions. Path Characters If the expression in the path contains characters that need to be escaped, it will be escaped automatically. Otherwise, the URL encoding will be thought and performed. Here the following characters are allowed.  a-z, A-Z, 0-9, -!. ~'()* The following characters are reserved as escape characters.  ??$??/? @ Sub-resource locators If a method that specifies @Path annotations but does not specify HTTP method annotations returns another resource class object that then distributes and processes requests for sub-resources. Sub-resource classes do not need to be exposed as services, so the class can be without @Path annotation. Consider the following example, here @Path(“{database}-dB”) servers as the sub-resource locator.   public class CustomerData    { ……      @Path(“{database}-dB”)      public CustomerDatabase getDatabase(@PathParam(“database”) String dataBase)       {         // find the instance based on the dataBase parameter         CustomerRecord resource = locateCustomerRecord(dataBase);         return resource;        }        …..     }         The @Consumes annotation This annotation specifies which media type a resource can accept at the server-side from an API request. This is important to specify while creating or updating resources at the server side using REST APIs. If this annotation is applied at the class level, all the methods in the class accept the same media type by default. When there is a method that applies @Consumes at a method level, that will override the class level annotation. The value of @Consumes is a string array with acceptable media types. For example: @Consumes({“text/plain,text/html”}) Request Method Annotations The request method annotations are used to map the HTTP methods to Java programming language methods. These are run-time annotations defined by JAX-RS. They correspond to the similarly named HTTP methods. JAX-RS defines @GET, @POST, @PUT, @DELETE, and @HEAD as common request method annotations. You can also create your own custom request method annotations. Methods decorated with request method annotations must return a void or a javax.ws.rs.core.Response Object. Extracting Request Parameters When we create an API request, we can include different parameters into it so that we can extract information at the server side based on these parameters. The following types of parameters can be extracted from a given request. Query Query parameters are specified by @QueryParam in the method parameter arguments. One must import javax.ws.rs.QueryParam class for this. The following example demonstrates application of                                                                   @QueryParam.   @Path(“smooth”)   @GET   public Response smooth(      @DefaultValue(“2”) @QueryParam(“count”) int count,      @DefaultValue(“true”) @QueryParam(“has-min”) boolean hasMin)           {             ……….           }       Here one thing to note is the use of @DefaultValue annotation. They are used to set a specific value to the request if there is no value is provided by the client while using a specific @QueryParam URI path URI path parameters are extracted from the URI request itself. The parameter name is included in the @Path annotation. In the java method arguments, they are specified using the @PathParam annotations. For example:                                                                               @Path(“/{name}”)   public class UserNamePrinter    {      ……    @GET      public String printUserName(@PathParam(“name”) String userID)      {        ……..         }     }     Form Form parameters use the @FormParam annotation and extract information from a request that is of the MIME media type application/x-www-form-urlencoded and conforms to the HTML form encoding specifications. They are mostly used when information is sent in HTML form using the POST method. Cookie Cookie parameters extract information from the cookie-related HTTP headers. It uses @CookieParam annotation. Header Header parameters extracts information from the HTTP headers. Here we use @HeaderParam annotation. One must include the javax.ws.rs.HeaderParam class for using this annotation. Matrix Header parameters extracts information from the URL path segments. The annotation for the Matrix request parameter is @MatrixParam. The class is located in javax.ws.rs.MatrixParam. Summary JAX-RS uses annotations at the server side for handling API requests and there are specific annotations for handling requests from a client-side API. Forming a correct URI, specifying the media types, extracting information from the URI, etc are some of the important steps while processing an API request at the server-side.