Blogs On Programming

Deep Dive into Java Operators

Deep Dive into Java Operators

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.