Blogs On Programming

Future Job Market for Java Professionals

Future Job Market for Java Professionals

by Vibrant Publishers on May 22, 2022
When contemplating opportunities for Java professionals, many dismiss it as an outdated technology option, thinking, will Java remain in demand? Let us dispel this illusion for you with some illuminating facts. According to CODEGYM, the Java job market had more opportunities in the year 2020 than ever before, regardless of the global pandemic crisis. The market witnessed several Java job vacancies. Even the job switch rate for Java professionals is less than 8%, compared to 27% for the software development profession as a whole and 35% for database administrators. Also, given a higher-level administrative role, a significant number of Java developers simply prefer to retain their position. If this isn’t the best proof that Java programming is the ideal career choice for the vast majority of professionals, we don’t know what is. We can state that the future for Java professionals is as bright as the rising sun. Now that it’s pretty clear the Java job market is not going anywhere, Java job vacancies will witness an increasing trend in the coming decade. So, let us begin with what this beloved programming language has in store for all Java Job seekers out there. What can Java professionals expect from the Java job market in the near future? According to reports, the IT industry will witness significant job shifts, resulting in numerous Java job vacancies. With the advancement of the tech industry, the Java job market will experience a favorable turn as many corporations rely on this programming language to create their core offerings. Java job vacancies reach a rather high ranking with every season. The above facts back up the Java obsession. Fresh graduates and experienced professionals remain inclined towards Java. Presently, there are over 7 million Java developers, with around 0.5 million new coders joining the Java community each year. This showcases the level of aggressive competition in the field for Java developers. How can Java professionals achieve lucrative jobs in the cut-throat Java job market? Java is unquestionably an excellent way to begin for people who are new to coding. Even the Java professionals who have sustained in the market till now need to stay updated with the market needs to scale their careers to new heights. However, getting past the screenings and interviews for a Java job is no cakewalk. Coders have to go through various technical rounds of tests and interviews. Adequate preparation of commonly asked questions in a Java job interview is crucial for selection. One can unearth smart tactics from specially compiled books that put the candidate in charge and push them to do their best. Acquiring additional skills in Java-related technologies can also provide you an edge in the Java job market. What is the scope for other Java-related technologies/platforms? Java professionals can multiply their prospects for a high-paying job by upgrading their skills and mastering related tools and frameworks. This language has several frameworks (VUE.js, jQuery, Angualr.js, and React.js) with a strong presence in the market and is continually expanding. As per the Devskillers report, Javascript stands as the most sought-after IT skill among developers worldwide. At least 80 percent of the websites rely on a third-party JavaScript web framework or library to perform client-side scripting tasks. To understand the potential of Java in the job market, it is also necessary to know how it fairs in contrast to other popular languages. So, before we move further, let’s take a peek at Java’s performance in contrast to other competing languages such as Python and C++. Where does Java stand in comparison to other eminent languages like Python and C++? The most common programming languages used besides Java are C++ and Python. These have been the foundation for almost all prominent development projects worldwide. C++ has grown in popularity as a fast and compiled programming language, and it is among the first languages that a newbie programmer learns. However, in contrast to Java, the language has lower portability. C++ programmers are anticipated to have a satisfactory amount of opportunities at least until 2022. Candidates with substantial expertise will have bright prospects and multiple avenues in C++ programming. On the other hand, Python is an interpreted language that is both current and quick to type. The code is 3-4 times shorter than that of Java. There has always been a tussle between Python and Java in terms of their demand. Python programmers have a very strong job market for web development projects. As a result, there is always business for a Python coder. Java remains popular because of its platform independence. Programmers have used this language to give life to many popular apps and software systems. Java is also being employed to create solutions for machine learning, genetic programming, and multi-robotic systems, all of which have a promising future—no wonder the Java job market continues to thrive. Conquer greater heights in the Java job market with robust preparedness! Some of the world’s biggest companies, such as Twitter, Google, LinkedIn, eBay, and Amazon, use Java to establish a coherent architecture between their web application and backend systems. This fact emphasizes the scope and appeal of Java Programmers. As a result, the salaries of Java Programmers in many countries are among the highest in the computer and internet networking industries. Artificial Intelligence, Big Data, and Blockchain are some of the new technologies where the scope of Java is likely to expand. Therefore, being on your feet and educating yourself to meet industry standards improves your chances of landing a successful job in Java programming. A great deal of preparation with assistance from Vibrant Publishers will help you accomplish this goal. Remember friends, the best way to predict your future is to create it! We wish you success! The new edition of the book, Core Java Interview Questions You’ll Most Likely Be Asked, released in Sep 2021, has all the goods of the old edition plus additions like the latest Java interview questions, scenario-based questions, and a tutorial on building an ATS-compliant resume. The book is ideal for job seekers with zero to five years of experience.
Java Collections – List, Set, Queue & Map

Java Collections – List, Set, Queue & Map

by Vibrant Publishers on May 22, 2022
Introduction: Most real-world applications work with collections like files, variables, records from files, or database result sets. The Java language provides a set of collection frameworks that you can use to create and manage various types of object collections. This blog describes the most common collection classes and how to start using them.     List: The list is an ordered collection, also known as a sequence. Because the list is organized, you have complete control over where list items are placed in a list. One thing to note here is that the Java list collection can only contain objects.   Declare a List:   A generic way       List listOfStrings = new ArrayList();     Using the Diamond operator       List<String> listOfStrings = new ArrayList<>();     Here the object type is not specified during ArrayList instantiation. This is because the type of the class to the right of the expression must match the type on the left. Note that the ArrayList java object is assigned to a variable of the list type. In Java programming, you can assign one type of variable to another, as long as the assigned variable is a superclass or interface implemented by the assignment variable.     List Methods:   To place a list item on a list using add() method       List<Integer> listOfIntegers = new ArrayList<>(); listOfIntegers.add(Integer.valueOf(100));     Note that the add() method adds elements to the end of the list.     To ask how big the list is, call size(). Here in the above example to get the current list size we will call,       listOfIntegers.size();     To retrieve an item from the list call get() and pass it the index of the item you want. For example if you want to get the first item from the listOfIntergers, then you will specify it like this:       listOfIntegers.get(0);     To go through all the records in a list you will iterate through the collection. You can do that easily because list implements the java.lang.Iterable.   When java.lang.Iterable is implemented by a collection it is called an Iterative variable collection. Here you will begin at one end and work on the collection, item by item until you’ve finished processing all the items.To get each item in a list, you can do the following:       for (Integer i : listOfIntegers) {   System.out.print(“Integer value is : ” + i); }     Set: Java Set is a collection construct that, by definition, contains unique elements — that is, no duplicates. The Java Set collection can only contain objects, and it is not an ordered list, which means it does not care about the order of the elements. Because the set is an interface, you cannot instantiate it directly.   Types of Java Set:   In Java, there are three implementations available for a set. They are HashSet, LinkedHashSet & TreeSet.   Declare a Set:       Set<Integer> setOfNumbers = new HashSet<>();     This Hashset is the most widely used version of a Set which gives a unique ordered list.       Set<String> setOfNames = new LinkedHashSet<>();     The only difference in LinkedHashSet with HasSet is that it orders the elements based on insertion order.       Set<Integer>setOfNumbers = new TreeSet<>();     In a TreeSet the ordering takes place based on the values of the inserted element. It follows a natural ordering by default.       Queue: Java Queue is a collection that works on FIFO (First In First Out) principle. The elements that are added first will be removed first from the queue. LinkedList and Priority Queue are the most common types of Queue implementations in Java.   Basic Queue Operations The common operations that can be performed in a queue are addition, deletion & iteration. Like other collections here also we can find out the queue size & length. The enqueue() method will add an element at the back of the queue and the dequeue() method will remove the item which is at the front of a given queue.         Map: The map is a convenient collection construct that you can use to associate one object (key) with another object (value). As you can imagine, the key of the Map must be unique and can be used later to retrieve values. Different implementations of the Map are HashMap, TreeMap, LinkedHashMap, etc. HashMap Java is the common Map type used by programmers.   Declare a Map: A Map can be declared using the Diamond Operator as given below:       Map<Integer, String> sampleMap = new HashMap<>();     Here, the Integer will be the ‘Key’ and Sting will be the ‘Value’. Basic Map Operations: The basic operations that can be performed in a Map are: Put the content in Map Get content from Map Get the key set for Map – use it to iterate.       Common Operations in Java 8 Collections: The collection framework in Java has many common operations that apply to all types of collections. They are summarized here.     End note: We have seen different types of collections in Java, their usage, and the main operations that each collection can perform. When dealing with large amounts of data, collections are the most commonly used data structure in the Java programming world. So it is important to understand their usage thoroughly to become a good Java developer. A Java developer will also need to understand Wrapper class, Streams, Enumeration, Autoboxing, and Threads.     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 April 3rd, 2020, and has been updated on January 8th, 2022.
Java Streams

Java Streams

by Vibrant Publishers on May 22, 2022
Introduction This blog talks about Java streams. The stream is a new addition in Java 8 that gives much power to Java while processing data. One thing to note here is that the stream mentioned here has nothing to do with Java I/O streams. This Java tutorial will focus on the Java 8 Streams in detail.Streams make processing a sequence of elements of the same datatype a cakewalk. It can take input in the form of any collections in Java, Arrays, Java I/O streams, etc. The interesting fact here is that you don’t need to iterate through these inputs to process each element. Automatic iterations are a built-in feature of the stream.In this blog, we will learn to create a stream and look at how stream operations in Java function. We will also take a look at improvements made by Java 9 on the stream interface.     Creating a Stream: Let’s see how a stream can be declared in Java 8. First, you will import java.util.stream class to use the Java 8 Stream feature. Now assuming we have an array ‘arrayOfCars’ as the input source to the stream, private static Car[] arrayOfCars = {   new Car(1, “Mercedes Benz”, 6000000.0),   new Car(2, “Porsche”, 6500000.0),   new Car(3, “Jaguar”, 7000000.0) };     The stream can be created as given below:       Stream.of(arrayOfCars);     If we are having a List, a stream can be created by calling the stream() method of that list itself.       sampleList.stream();     We can also create Stream from different objects of a collection by calling the Stream.of() method.       Stream.of (arrayOfCars[0], arrayOfCars[1], arrayOfCars[2]);     Or just by using the Stream.builder() method.       Stream.Builder carStreamBuilder = Stream.builder(); carStreamBuilder.accept( arrayOfCars[0] ); carStreamBuilder.accept( arrayOfCars[1] ); carStreamBuilder.accept( arrayOfCars[2] ); Stream carStream = carStreamBuilder.build();     Stream Operations: We have seen the different ways of creating a stream. Now let us have a look into various Stream operations.   The main use of stream is to perform a series of computations operations on its elements until it reaches the terminal operation.   Let’s look at an example:       List flowers = Arrays.asList(“Rose”, “Lilly”, “Aster”, “Buttercup”, “Clover”); flowers.stream().sorted().map(String::toUpperCase).forEach(System.out::println);     Here the stream performs sorting and mapping operations before iterating and printing each element in the stream. So we can understand that the stream operations are either intermediate or terminal. In intermediate operations, the output will be stream format itself.       Intermediate stream operations:         Terminal stream operations:         Improvement made by Java 9 on stream interfaces Java 9 has added a stream.ofNullable() method to the stream interface. It helps to create a stream with a value that may be null. So, if a non-null value is used in this method, it creates a stream with that method; otherwise, it creates an empty stream. Both the methods takewhile() and drpwhile() can be operated in Java stream. They are used to obtain a subset of the input stream. Java 9 has added an overloaded version of the Stream.iterate() method that accepts a predicate and terminates the stream when the condition specified is true.     End note: In this blog, we learned about the improvements made by Java 9 on stream interfaces. We also studied Java 8 stream features in detail—how to create a stream, stream operations, the uses of a stream, among other topics. Next, we learned about different stream intermediate operations and stream terminal operations and briefly looked at how Java stream provides a functional style of programming to Java besides its Object-oriented programming style. It is important to learn and understand this newly-added feature of a stream while studying Java programming.     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 April 2nd, 2020, and has been updated on January 7th, 2022.
Deep Dive into Java Operators

Deep Dive into Java Operators

by Vibrant Publishers on May 21, 2022
Introduction: One of the most basic requirements of a programming language is to perform mathematical operations. Java is an Object-Oriented Programming language. It provides a rich set of operators to manipulate variables. In this blog, let’s take a look at the different types of Java operators and a few examples of sample code.   We can classify the Java operators into the following groups: Arithmetic Operators Relational Operators Bit Operators Logical Operators Assignment Operator       Arithmetic Operators: Arithmetic operators are used for mathematical expressions. In the following table, you will find a list of all arithmetic operators, as well as their descriptions and example usage.   The examples in the table given below assume that the value of the integer variable X is 20 and the value of variable Y is 40.         One thing to note here is the number of operands involved in each case. While addition, subtraction, multiplication & Java modulo operators require two operands, the increment & decrement operators operate on a single operand.   The sample code given below will show all the use-cases of the above-mentioned operators in detail.     public class TestArithmaticOperators {   public static void main(String [] args){     //operand variable declaration and initializatoin.     int a = 5; int b = 22; int c = 16; int d = 33;     System.out.printIn(“a + b =” + (a + b));     System.out.printIn(“a – b =” + (a – b));     System.out.printIn(“a * b =” + (a * b));     System.out.printIn(“b / a =” + (b / a));     System.out.printIn(“b % a =” + (b % a));     System.out.printIn(“c % a =” + (c % a));     System.out.printIn(“a++ =” + (a++));     System.out.printIn(“a– =” + (a–));       // Check the difference between d ++ and ++ d     System.out.printIn(“d++ =” + (d++));     System.out.printIn(“++d =” + (++d));   } }   The following output is thus produced:     $ javac TestArithmeticOperators.java $java -Xmx128M -Xms16M TestArithmaticOpertors a + b = 27 a – b = -17 a * b = 110 b / a = 4 b % a = 2 c % a = 1 a++ = 5 a– = 6 d++ = 33 ++d = 35     Relational Operators: When we want to relate or compare two values, we use relational operators in our Java code. Two operands are expected for the operator as inputs.The table given below will provide a detailed description of relational operators in Java. Assuming the values of variables are X = 20  & Y = 40.         Let’s look at a sample code that uses the above operators:     public class code {   public static void main (String [] args){       // operand varibale declaration and initialization.     int a = 5; int b = 22; int c = 16; int d = 33;       System.out.println( “a == b =” + (a == b));     System.out.println( “a != b =” + (a != b));     System.out.println( “a < b =” + (a < b));     System.out.println( “a > a =” + (a > a));     System.out.println( “b <= a =” + (b <= a));     System.out.println( “c >= a =” + (c >= a));   } }     After successful compilation, the above code will produce the following result:     Output:   a == b = false a != b = true a < b = true a > a = false b <= a = false c >= a = true     Bit Operator: Java defines bit operators for integer types (int), long integers (short), short integers (char), and byte types (byte).   Bit operators operate on all bits and perform bit-level operations. There are four bitwise operations and three bitshift operations that bit operators perform.   For example, if we take Bitwise AND operator which is a bitwise operator, the operation will be as follows:   Suppose X = 60 and Y = 13; their binary (bit) representation would be as follows:       X = 0011 1100 Y = 0000 1101     Now when we perform a Bitwise AND operation, ie. if both bits are 1, the result is 1 else it’s 0. So here the result will be:       X & Y = 0000 1100     The following table gives a summary of the available bitwise operators and bit shift operators in Java:       Logical Operators: The following table lists the basic operations of logical operators, assuming Boolean variable X is true and variable Y is false.         Assignment Operator: We have discussed this section in detail here: Java Assignment Operator     Other Operators:   Instanceof Operator: This operator is used to manipulate an object instance and check whether the object is a class type or interface type. The instanceof Java operator uses the following format:       (Object reference-variable) instanceof (class / interface type)     If the object pointed to by the variable on the left side of the operator is an object of the class or interface on the right side of the operator, the result is true. Below is an example:         Conditional Operator (?:): The conditional operator in Java is also called ternary operator. The ternary Java operator has 3 operands. The conditional operator is used to determine the boolean values. The main purpose of this operator is to finalize which value among the two should be assigned to a variable.   The syntax would be:       variable test_variable = (expression)? value if true : value if false;       Java operator precedence: When multiple operators are used in one Java statement, it is important to understand which one will act first. To solve this confusion, the Java language has something known as ‘operator precedence.’ This will allow the highest priority operators to act first and then the other operators act, following the precedence order. It’s important to understand that in a multi-operator expression, different operator precedence can lead to very different results.     End Note: We have learned about the different types of operators in Java language that are used for performing various mathematical operations. We also saw examples of  their syntax.   Besides Java Operators, you must also be well-versed with the concepts of Flow control statements and Assertion, Java collections and Stream, Threading in Java, etc. You can take a look at our blogs on these topics for in-depth understanding.     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 31th, 2020, and has been updated on January 12th, 2022.
Java Inner Classes and String Handling

Java Inner Classes and String Handling

by Vibrant Publishers on May 20, 2022
Introduction This Java tutorial deals with Java Inner Classes & String handling. Java Inner Classes are an extraordinary feature in Java. In simple terms, an inner class is a class declared inside a class. In a broad sense, inner classes generally include these four types:   Member inner class Local inner class Anonymous inner class Static inner class     Creation of an Inner class: You will create an inner class just like how you do it for a general class. The only difference is that the inner class is always declared inside a class. An inner class can have private access, protected access, public access, and package access.   The code given below will explain the concept in detail:     Here we declared the inner class as ‘private’ which makes it accessible only inside the outer class. The java main class will access the inner class via an instance of its outer class.     Types of Inner class 1. Member inner class:   The member inner class is the most common inner class, and its definition will be inside another class, as given below:     class Circle {   double radius = 0;   public Circle(double radius) {     this.radius = radius;   }   class Draw {     public void drawSahpe() {       System.out.println(“draw shape”);     }   } }     In this way, the class Draw looks like a member of the class Circle, which is called the outer class. Member inner class has unconditional access to all member properties and member methods of outer classes, including private members and static members.   However, we must note that when a member’s inner class owns a member variable or method with the same name as an outer class, a hidden phenomenon occurs, i.e. a member of the member’s inner class is accessed by default. If you want to access the same member of an outer class, you need to access it in the following form:       OuterClass.this.MemberVariable; OuterClass.this.MemberMethod;     2. Local inner class:   A local inner class is a class that is defined in a method or scope, and the difference between it and the member inner class is that access to the local inner class is limited to the method or within the scope.       class Animals{   public Animals() {   } } class Mammals{   public Mammals(){ }     public Animals getHerbivorous(){       class Herbivorous extends Animals{         int number =0;       }     return new Herbivorous();   } }     The local inner classes, like a local variable within a method, cannot have public, protected, private, and static modifiers.     3. Anonymous inner class:   Anonymous inner classes as it sounds don’t have a name. Using anonymous inner classes when writing code for purposes like event monitoring etc. is not only convenient but also makes code easier to maintain.   For a normal class, any number of constructors are possible. But in the case of anonymous inner classes, we can’t have any constructors just because they don’t have any name which is a must for defining a constructor. Due to this most of the anonymous inner classes are used for interface callbacks.   Let’ see an example:     interfaceWeight {   int x = 81;   void getWeight(); } class AnonymousInnerClassDemo {   public static void main(String[] args) {     // WeightClass is implementation class of Weight interface     WeightClass obj=new WeightClass();     // calling getWeight() method implemented at WeightClass     obj.getWeight();   } } // WeightClass implement the methods of Weight Interface class WeightClass implements Weight {   @Override   public void getWeight()   {     // printing the wight     System.out.print(“Weight is “+x);   } }     Here we had to create a separate class ‘WeightClass’ to override methods of an interface. But if we use the anonymous inner class feature we can easily achieve the same result by including the following code block inside the class ‘AnonymousInnerClassDemo’.       Weight obj = new Weight() {   @Override   public void getWeight() {     System.out.println(“Weight is “+x);   } };     Here an object of ‘Weight’ is not created but an object of ‘WeightClass’ is created and copied in the entire class code as shown above.     4. Static inner class:   Static inner classes are also classes defined within another class, except that there is one more keyword ‘static’ in front of the class. Static inner class does not need to rely on external classes, which is somewhat similar to the static member properties of classes, and understandably, they cannot use non-static member variables or methods of external classes. Because, without objects of external classes, you can create objects for static inner classes. Allowing access to non-static members of an external class creates a contradiction because non-static members of the outer class must be attached to specific objects.       public class Test {   public static void main(String[] args) {     Outter.Inner inner = new Outer.Inner();   } }   class Outer {   public Outer() {   }   static class Inner {     public Inner() {     }   } }     String Handling in Java: All the string handling operations in Java are powered by the Java String class. The String class is also known as an immutable character sequence. It is located in the java.lang package, and the Java program imports all classes under java.lang package by default.   Java strings are Unicode character sequences, such as the string “Java” is composed of four Unicode characters ‘J’, ‘a’, ‘v’, ‘a’. We can use the scanner class in Java to parse an input string.   There are multiple operations on a string that we can do with the Java String class. The following code will provide an idea of string handling operations that we can do in Java:       public class StringHandlingDemo {   public static void main(String[] args) {       String stringX = “core Java”;     String stringY = “Core Java”;       //Extract the character with subscript 3     System.out.println( stringX.charAt(3));       //Find the length of a string     System.out.println( stringY.length());       //Compares two strings for equality     System.out.println( stringX.equals(stringY));       //Compare two strings (ignore case)     System.out.println( stringX.equalsIgnoreCase(stringY));       //Whether the string stringX contains word Java     System.out.println( stringX.indexOf(“Java”));       //Whether the string stringX contains word apple     System.out.println( stringX.indexOf(“apple”));       //Replace spaces in stringX with &     String result = stringX.replace(‘ ‘, ‘&’);     System.out.println(“the result is:” + result);       //Whether the string start with ‘core’     System.out.println( stringX.startsWith(“core”));       //Whether the string end with ‘Java’     System.out.println( stringX.endsWith(“Java”));       //Extract substring: from the beginning of the subscript 4 to the end of the string     result = stringX.substring(4);     System.out.println(result);       //Extract substring: subscript [4, 7) does not include 7     result = stringX.substring(4, 7);     System.out.println(result);       //String to Lowercase     result = stringX.toLowerCase();     System.out.println(result);       //String to uppercase     result = stringX.toUpperCase();     System.out.println(result);     String stringZ = ” How old are you!! “;       //Strip spaces from the beginning and end of a string.     Note: the space in the middle cannot be removed     result = stringZ.trim();     System.out.println(result);       //Because String is an immutable string, stringZ is unchanged     System.out.println(stringZ);       String stringZ1 = “Olympics”;     String stringZ2 = “Olympics”;     String stringZ3 = new String(“Winner”);       //String comparison operations     System.out.println( stringZ1 == stringZ2);     System.out.println( stringZ1 == stringZ3);     System.out.println( stringZ1.equals(stringZ3));       //String concatenation operation     System.out.println(stringZ1+” “+stringZ3);     } }     The output of the above code will be:       Output: e 9 false true 5 -1 the result is:core&Java true true Java Ja core java CORE JAVA How old are you!! How old are you!! true false false Olympics Winner     End note: We learned about inner classes and string handling in Java in this blog. In Java, inner classes are very useful while implementing features such as event listening, code abstraction, etc. It also makes the Java code more concise and reusable. String handling operations like java string split etc. are a must for any Java programmer and are the most commonly used feature in Java language.     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. 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 April 1st, 2020, and has been updated on January 6th, 2022.                  
All About Java Assignment Operators

All About Java Assignment Operators

by Vibrant Publishers on May 20, 2022
Like every other programming language, Java language also provides a feature called Operators. There are a few types of Operators exist in Java. In this java tutorial, we will focus our learning on Assignment operators. Assignment Operators exist for assigning a value to a variable in Java. The right side of the operator will be a value and the left side will be the variable that we created. So a general syntax would be as follows:       VARIABLE assignment operator VALUE ;     They are also known as Binary Operators because it requires two operands for it to work. Since there are many data types in java, one important thing here to remember is that the data type of the variable must match with the value that we assign. These variables can be a java array variable, a java object or any variable of a primitive data type.Now let’s look into multiple assignment operators that exist in Java language.     Simple Assignment Operator: As the name suggests this operator assigns values to variables.Syntax:       variable = value ;     Example:       string  name = “This is awesome!”;   A sample java code will be as given below:     Here if we examine the java class ‘SimpleAssignment’, the value assigned for java int variable ‘number’ is 10. And the java string variable ‘name’ has been assigned the value ‘This is awesome!”.Apart from simple assignment operations, java developers use this operator combined with other operators. This gives compound operators in the java code world. Let’s see those operators here:     += Assignment Operator: This is a combination of + and = java operators. So instead of writing,       number = number + 10;     we can combine the above statement in a java code as:     number += 10;   For Example:The given java code blocks for java compiler will be the same and will produce the same output ie. 13.2       float java = 1.00; java +=12.2; float java = 1.00; java = java + 12.2;     -= Assignment Operator: Similar to the compound statement that we saw above, here also we combine ‘-’ and ‘=’ java operators. So here the value on the right side is subtracted from the initial value of the variable and it is assigned to the variable itself.Syntax:       numberA -= numberB ;     Example:       numberA -= 10; this means numberA = numberA -10;     *= Assignment Operator: In this case, we combine ‘*’ and ‘=’ java operators. So here the value on the right side is multiplied with the initial value of the variable and it is assigned to the variable itself.Syntax:       numberA *= numberB ;     Example:       numberA *= 10; this means numberA = numberA *10;     /= Assignment Operator: Just like the above cases,  here we combine ‘/’ and ‘=’ java operators. In this operation, the initial value of the variable on the left side is divided with the value on the right side and the resulting quotient is assigned to the left side variable itself.Syntax:       numberA /= numberB ;     Example:       numberA /= 10; this means numberA = numberA /10;     Summary: The following table provides a summary of the Assignment Operators in Java Language.     For a java developer, it’s important to understand the usage of Operators. If you want to learn java programming, then you must know these concepts well.
Declarations & Access Control in Java

Declarations & Access Control in Java

by Vibrant Publishers on May 20, 2022
Introduction In Java, creating a variable is also referred to as declaring a variable. To create a variable in Java, you must specify its type and name. This blog will talk about how declaration in Java works and the steps to create (declare) a variable and its different types such as Local variables, Instance variables. We will also learn constructors, Java access modifiers.     Source File Declaration: A Java file can have only one public class. If one source file contains a public class, the Java filename should be the public class name. Also, a Java source file can only have one package statement and unlimited import statements. The package statement (if any) must be the primary (non-comment) line during a source file and the import statements (if any) must come after the package and before the category declaration.     Identifiers Declaration: Identifiers in Java can begin with a letter, an underscore, or a currency character. Other types of naming are not allowed. They can be of any length. Only in the case of JavaBeans methods, they must be named using CamelCase, and counting on the method’s purpose, must start with set, get, is, add, or remove. In Java, we have variables, methods, classes, packages, and interfaces as identifiers.     Local Variables: The scope of local variables will be only within the given method or class. These variables should be initialized during declaration. Access modifiers cannot be applied to local variables. A local variable declaration will be as shown below:       public static void main(String[] args) {     String helloMessage;     helloMessage = “Hello, World!”;     System.out.println(helloMessage); }     Here String helloMessage; is a local variable declaration and its initialization is followed in the next line.     Instance Variables: Instance variables are values that can be defined inside the class but outside the methods and begin to live when the class is defined.Here, unlike local variables, we don’t need to assign initial values. It can be defined as public, private, and protected. It can be defined as a final. It cannot be defined as abstract and static. An example can be shown as below:       class Page {   public String pageName;   // instance variable with public access   private int pageNumber;   // instance variable with private access }     Here the declaration String pageName is an instance variable.     Constructors: We use the constructor to create new objects. Each class is built by the compiler, even if we do not create a constructor defined in itself. constructors can take arguments, including methods and variable arguments. They must have the same name as the name of the class in which it is defined. They can be defined as public, protected, or private. Static cannot be defined because it has a responsibility to create objects. Since it cannot be overridden, it cannot be defined as final and abstract. When the constructor is overloaded, the compiler does not define the default constructor, so we have to define it. The constructor creation order is from bottom to top in the inheritance tree.     Static: It allows invoking the variable and method that it defines without the need for any object. Abstract and static cannot be defined together, because the method presented as static can be called without creating objects and by giving parameters directly. The abstract is called to override a method. Abstract and static cannot be used together because static has different purposes in this respect.     ENUM: It is a structure that allows a variable to be constrained to be predefined by one value. With Enum’s getValues method, we can reach all values of enums. This is the most effective way to define and use constants in our Java program.     Features of Java Class Modifiers (non-access): Classes can be defined as final, abstract, or strictfp. Classes cannot be defined as both final and abstract. Subclasses of the final classes cannot be created. Instances of abstract classes are not created. Even if there is one abstract method in a class, this class should also be defined as abstract. The abstract class can contain both the non-abstract method and abstract method, or it may not contain any abstract method. All abstract methods should be overridden by the first concrete (non-abstract) class that extends the abstract class.     Java Class Access Modifiers: Access modifiers are an important part of a declaration that can be accessed outside the class or package in which it is made. Access modifiers enable you to decide whether a declaration is limited to a particular class, a class including its subclasses, a package, or if it is freely accessible. Java language has four access modifiers: public, protected, and private.     Public Enables a class or interfaces to be located outside of its package. It also permits a variable, method, or constructor to be located anywhere its class may be accessed. Protected: Enables a variable, method, or constructor to be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. Private: Prevents a variable, method, or constructor from being accessed only from within the class in which it is declared. Default: The default access occurs when none of the above access specifiers are specified. In such a case, the member is accessible within the package but not without the Java package.     End Note: In this blog, we talked about declarations of variables, constructors, and Java class modifiers. We also looked at the features of class modifiers and their types.   Do you want to know more about topics like Java collections, Java streams, Java Inner Classes, and many more aspects of Java? For in-depth information on these topics, you can check out our series of blogs here.     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 29th, 2020, and has been updated on January 5th, 2022.
Object Oriented Concepts in Java

Object Oriented Concepts in Java

by Vibrant Publishers on May 20, 2022
Object-oriented programming is all about using the real-world concept of an object in the programming world. Here real-world entities like Inheritance, Polymorphism, Binding, etc. come into the picture. We will be covering the following OOP Concepts in this article: Polymorphism Inheritance Encapsulation Abstraction Before going into the details, let’s find out some of the benefits of using the OOP concept in programming.     Benefits of Object Oriented Programming in Java: Reusability: OOP principles like Inheritance, Composition, and Polymorphism help in reusing existing code. In OOP, you will never code the same block again in your program, rather reuse the existing block. Extensibility: Code written using OOP principles like Inheritance makes the code extensible. Security: OOP principles like Encapsulation helps to keep the data and the code operating on that data secure. Simplicity: Java classes represent real world objects. This makes the code very easy to understand. For example, in real life a bus is an object which has attributes like color, weight, height, etc., and methods such as drive and break. Maintainability: Code written using OOP concepts is easier to maintain.   Now, let’s look into the main OOP concepts:       Polymorphism: Polymorphism is the ability to use the same interface to execute different interface codes. Java achieves Polymorphism via method overloading and overriding. In Java, the language can differentiate between entities having the same name efficiently.Consider the following example:         class multiplicationFunction {   // method with 2 parameters   static int multiply(int a, int b)   {     return a * b;   }     // method with the same name but 3 parameters     static int multiply(int a, int b, int c)   {     return a * b * c;   }   }   class Main {     public static void main(String[] args)   {     System.out.println( multiplicationFunction.multiply(2, 6) );     System.out.println( multiplicationFunction.multiply(6, 4, 2) );   } }     Though all the methods have the same name, the program will compile successfully and will provide output.     There are two kinds of methods in Java: Compile-time polymorphism, also known as static binding or method overloading Run-time polymorphism, also known as dynamic binding or method overriding   Inheritance: Like we see inheritance in the real-world, Java classes can also share or inherit properties or methods of other classes. This way, we can reuse the code once written in many other places in a program. The class that inherits properties from another class is called Derived Class or Child Class. The class that shares its properties with another class is called the Base Class or Parent Class.   In Java, we can use this feature by inserting ‘extends’ keyword:       public class Vehicle {     String vehicleType;     String vehicleModel;     void mileage() { }   }   public class Car extends Vehicle {   }     The inherited Car Class can use all the variables and methods of Vehicle Class.     Encapsulation: Encapsulation refers to keeping objects with their methods in one single place. It also protects the integrity of the information– prevents it from being needlessly altered by restricting access to the data, preferably by hiding it from outside elements. Encapsulation is usually confused with data abstraction, but they are different concepts entirely. Data hiding, or data abstraction, has more to do with access specifiers. A programmer must first encapsulate the information; only then he can take steps to cover it.   Procedural programs, for example, are not encapsulated. The procedures are grouped separately from the data. In OOP, the given data is usually grouped along with side methods that operate upon the information.   In Java, encapsulation is built-in and whenever you create a class, this principle is followed naturally.     Abstraction: This feature in OOP aims to hide the complexity from the users and provide them with relevant information only. There are abstract classes or interfaces available in Java through which we can provide only the required information to the users, hiding all unwanted code.   There are two types of abstractions commonly used in Java: Data Abstraction Control Abstraction   Consider the following code block:     abstract class Animal{     public abstract void animalSound();     public void sleep() {       System.out.println(“Zzz”);     }   }     Here you won’t be able to create an object for Animal class. Animal animalObj = new Animal(); will generate error.   If we want to access an abstract class, it must be inherited from another class. So, in the above example:       class Lion extends Animal {     public void animalSound() {     }   }     We create a class Lion that extends Animal class, now we can create an object for the Lion class: Lions lionObject = new Lion();     End Note: In this blog, we looked at Object-Oriented Programming (OOP) concepts. We also saw the benefits of this type of programming in Java. Some of the main OOP concepts like polymorphism, encapsulation, and inheritance, among other concepts, were briefly touched upon.   So, it’s important to understand these concepts in-depth to make use of the power of Object-Oriented Programming. Happy Learning!!     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 28th, 2020, and has been updated on January 19th, 2022.       
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.    
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.