Tuesday, March 31, 2020

Java Class and Objects

Java Class, Java Objects, Oracle Java Tutorial and Materials, Oracle Certification, Oracle Cert Exam

We know that Java is an Object-Oriented programming language. Everything in Java revolves around a class. But before going much further in the study of Java, you need to be familiar with the most fundamental OOP concepts which are Java Class and Java Object. Java Classes and Objects are one of the core building blocks of Java applications, frameworks and APIs (Application Programming Interfaces).

A class is a non-primitive or user-defined data type in Java, while an object is an instance of a class. A class is a basis upon which the entire Java is built because class defines the nature of an object.

Since all the activities in a Java program occur within a class, we have already been using classes and objects since the start of this Java tutorial. Of course, those were extremely simple classes that we have used, but we didn’t take advantage of the majority of the useful features of classes. There are many things that you do not know about Java classes and objects, so let us understand them in this tutorial.

Objects and Classes in Java


Let’s first understand the concept of Object and Class in Java –

Object:


An object is an identifiable entity with some characteristics, state and behavior. Understanding the concept of objects is much easier when we consider real-life examples around us because an object is simply a real-world entity. You will find yourself surrounded by the number of objects which have certain characteristics and behaviors.

For example, we can say ‘Orange’ is an object. Its characteristics are: spherical in shape and color is orange. Its behavior is: juicy and tastes sweet-sour.

Class:


A class is a group of objects that share common properties and behavior.

For example, we can consider a car as a class that has characteristics like steering wheels, seats, brakes, etc. And its behavior is mobility. But we can say Honda City having a reg.number 4654 is an ‘object’ that belongs to the class ‘car’.

It was a brief description of objects and classes. Now we will understand the Java class in detail.

Java Class


The core element of Object orientation in Java is the class. A class is often defined as the blueprint or template for an object. We can create multiple objects from a class. It is a logical entity that does not occupy any space/memory. Memory is allocated when we create the objects of a class type. A class contains properties and methods to define the state and behavior of its object. It defines the data and the methods that act upon that data.

Have you ever thought why a class is the blueprint of an object?? The reason is :

A class allows the programmer to define all the properties and methods that internally define the state and behavior of an object, and all the APIs that externally define an object, and also the complete syntax for handling encapsulation, abstraction, polymorphism, and inheritance. Therefore, we can say that a class is the BLUEPRINT of an object.

Java Class, Java Objects, Oracle Java Tutorial and Materials, Oracle Certification, Oracle Cert Exam
A class defines the shared characteristics like –

◉ The set of attributes/properties
◉ The set of behavior or methods or actions
◉ How to construct an object

Objects are the “instances” of a Class:

The class as a blueprint specifies what an object will look like. You can think of a class as a cookie cutter and an instance as an actual cookie!! Similarly, you can consider a class as “Mobiles” and Samsung, Nokia mobiles as objects of the class Mobile.

“Class is the basis of all Computation in Java”

A class forms the basis of all computation in Java. Anything that exists as a part of the Java program has to be present as a part of a class, whether it is a variable or a method or any other code fragments. The reason is that Java is a pure Object Oriented language, in which all the functionalities revolve around the classes and objects. All Java programs contain objects that interact with each other by calling methods.

Some Important points about a class:

◉ In Java, we can not declare a top-level class as private. Java allows only public and default access specifiers for top-level classes. We can declare inner classes as private.

◉ We can include any type of the three variables in Java – local, instance and static variables.

◉ There can be only one public class in a single program and its name should be the same as the name of the Java file. There can be more than one non-public classes in a single Java file.

◉ A public class is visible to all classes from all the packages.

◉ A class with default access is visible only to the classes within the same package.

◉ We can also use the non-access modifiers for the class such as final, abstract and strictfp.

◉ We cannot create an object or instance of an abstract class.

◉ No subclasses or child class can be created from a class that is declared as final.

◉ A class cannot be declared both as final and abstract at the same time.


Declaration of Java Classes


In order to bring class into existence, we should declare it. We can declare a class with the use of a class keyword.

The components of the Java Class declaration are –

1. Access Modifiers – We can access Java classes using any access modifiers such as public, private, protected and default.

2. Class Name – In Java, the class name generally represents nouns which should begin with a capital letter without any spaces.

3. Superclass (if any) – The name of the parent class is a superclass and its child class is a subclass, and child class inherits the properties of a parent using the extends keyword. A subclass can only inherit a single parent.

4. Interfaces (if any) – To declare an interface, we just write the keyword interface followed by the interface name.

5. Class Body – The class body follows the class declaration and embeds within curly braces {}.

The syntax for declaring classes:

<access-modifier> class <ClassName>
  {
    //Class body containing variables and methods
  }

Example:

public class Student
{
  String name;
  int age;
        void display()
  {
         //method body;
  }
}

Code Snippet:

//declaring a class
public class Person
{ //class body starts here
  //creating the data members of the class
  static String name = "John";
  static int age = 25;
  //creating the methods of the class
  void eat()
  {
    //methodBody
  }
  void study()
  {
    //methodBody
  }
  void play()
  {
    //methodBody
  }
  public static void main(String args[])
  {
    System.out.println("Name of the person: " +name);
    System.out.println("Age of the person: " +age);
  }
} class body ends here

Output:

Name of the person: John
Age of the person: 25

Creating Objects from a Java Class


We know that an object is an instance of a class. To create an object of a class, first, we need to declare it and then instantiate it with the help of a “new” keyword.

Syntax of creating an object of a class:

To create an object of a class, specify the class name, followed by the object name, by using the new keyword –

ClassName objectName = new ClassName();

Example:

MyClass object1 = new MyClass();


Accessing the members of a Java Class


We can access the data members of a class using the object of the class. We just write the name of the object which is followed by a dot operator then we write the name of the data member (either variables or methods) which we want to access.

Syntax of accessing data members and methods of a Java Class:

objectName.variableName; //accessing the variables
objectName.MethodName(); //accessing the methods

Example:

Object1.number; //accessing the variables
object1.display(); //accessing the methods

Code snippet to understand the usage of Java Class and Object:

//creating a class named City
public class City
{
  //declaring class variables
  public String name;
  public long population;
  //defining the method of the class
  public void display()
  {
    System.out.println("City name: " +name);
    System.out.println("Population: " +population);
  }
  public static void main(String args[])
  {
    //declaring the objects of the class City
    City metro1,metro2;
    //Instantiating the objects of the class using the new keyword
    metro1 = new City();
    metro2 = new City();
    metro1.name ="Delhi";
    metro1.population = 10000000;
    System.out.println("Details of metro city 1:");
    metro1.display(); //display() method is being invoked for the object metro1
    metro2.name ="Bangalore";
    metro2.population = 5000000;
    System.out.println("Details of metro city 2:");
    metro2.display(); //display() method is being invoked for the object metro2
  }
}

Output:

Details of metro city 1:
City name: Delhi
Population: 10000000
Details of metro city 2:
City name: Bangalore
Population: 5000000

Using Multiple Java Classes


Using multiple classes means that we can create an object of a class and use it in another class. Also, we can access this object in multiple classes. One class contains all the properties, fields and methods while the other class contains a main() method in which we write the code which has to be executed. We often use this concept for proper organization and management of classes.

We have to keep one thing in mind that the name of the class should be the same as the name of the java file. Now, we will understand this with the help of an example, in which we will create two files in the same folder: ClassOne.java and ClassTwo.java

ClassOne.java :

public class ClassOne
{
String sentence = “Hello World”;
}

ClassTwo.java :

public class ClassTwo
{
      public static void main(String[] args)
      {
        ClassOne object1 = new ClassOne();
        System.out.println(object1.sentence);
    }
}

Output:

Hello World

Saturday, March 28, 2020

How to check if two String are Anagram of each other - Coding Problem

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Oracle Java Exam Prep

Hello guys, if you are preparing for Coding interviews then you already know that String is one of the most popular topics. You will bound to get some string-based coding problems on interviews. If not, you have come to the right place becuase we'll look one of the most popular String programming interview questions today,  how to check if two given string are Anagram of each other? Two String is said to be an anagram of each other, if they contain exactly the same characters but in a different order. For example "ARMY" and "MARY" is an anagram of each other because they contain exact same characters 'A', 'R', 'M' and  'Y'.

The order doesn't matter, as long as both Strings contains exactly the same character and the same number of time they are Anagram. For example, if one letter is repeated on one String and not on other then they will not be Anagram of each other.

Another example of Anagram is "Tokyo" and "Kyoto", two of the most popular cities in Japan. Interestingly both have also served as the capital of Japan, Kyoto was old capital before they moved the capital to Tokyo in the 16th century.

For the sake of simplicity, you can also assume that your solution need not be case-sensitive, which means both army and mary can be matched as an anagram of each other.

Btw, strong knowledge of data structure and algorithm is expected in coding interviews. At the bare minimum, you should be familiar with essential data structures like an array, string, linked list, binary tree, binary search tree, balanced tree, stack, queue, heap, and graphs.

Java Program to find if two String are Anagram or not


Here is a Java program to check if two String is an anagram of each other or not.

import java.util.Arrays;

/**

* Java Program to check if two String is an anagram of each other or not. Two

* String is said to be an anagram of each other, if they contain exactly same

* characters but in a different order. For example "army" and "mary" are anagram

* of each other because they contain exact same characters 'a', 'r', 'm' and

* 'y'.

*

*/

public class Testing {

    public static void main(String args[]) {

        String[][] data = {{"army", "mary"}, {"stop", "tops"}, {"soap", "abcd"}};

        System.out.println("======== Testing areAnagrams() method =======");

        for (String[] value : data) {

            String s1 = value[0];

            String s2 = value[1];

            System.out.printf("Are %s and %s are Anagrams? %b%n", s1, s2,
                       areAnagrams(s1, s2));

        }

        System.out.println("======== Testing isAnagaram() method =======");

        for (String[] value : data) {

            String s1 = value[0];

            String s2 = value[1];

            System.out.printf("Does %s and %s are Anagrams? %b%n", s1, s2,
                               isAnagram(s1, s2));

        }

    }


    /*

     * One of the easiest way to check if two Strings are an anagram of each other

     * is to take their character array, sort them and check if they are equal.

     * If sorted character arrays are equal then both String are an anagram of

     * each other.

     */

    public static boolean areAnagrams(String first, String second) {

        char[] fa = first.toCharArray();

        char[] sa = second.toCharArray();

        // sort arrays

        Arrays.sort(fa);

        Arrays.sort(sa);

        // check if arrays are equal

        if (Arrays.equals(fa, sa)) {

            return true;

        }

        return false;

    }

    /*

     * Earlier method was using a couple of library methods, which is not permitted during

     * interviews. This method checks if two Strings are anagram without using any utility

     * method. This solution assumes that both source and target string are ASCII strings.

     */

    public static boolean isAnagram(String source, String target) {

        if ((source == null || target == null) || source.length() != target.length()) {

            return false;

        }

        int[] table = new int[256];


        int numOfUniqueCharInSource = 0;

        int numOfCharProcessedInTarget = 0;


        char[] characters = source.toCharArray();


        // store count of each unique character in source String

        for (char ch : characters) {

            if (table[ch] == 0) {

                ++numOfUniqueCharInSource;

            }

            ++table[ch];

        }

        for (int i = 0; i < target.length(); ++i) {

            int c = target.charAt(i);

            if (table[c] == 0) {

                return false;

            }

            --table[c];

            if (table[c] == 0) {

                ++numOfCharProcessedInTarget;

                if (numOfCharProcessedInTarget == numOfUniqueCharInSource) {

                   // it’s a match if t has been processed completely

                    return i == target.length() - 1;

                }

            }

        }

        return false;

    }

}

Output

======== Testing areAnagrams() method =======

Are army and mary are Anagrams? true

Are stop and tops are Anagrams? true

Are soap and abcd are Anagrams? false

======== Testing isAnagaram() method =======

Does army and mary are Anagrams? true

Does stop and tops are Anagrams? true

Does soap and abcd are Anagrams? false

That's all about how to check if two String is Anagram of each other or not. If you need more String based coding problems for practice then you can also solve problems listed below.  It's an interesting problem and there are a couple of invariants as well as the case-sensitive one I discussed in the first paragraph. You may also be asked to calculate the time and space complexity of this problem, can you calculate?

Friday, March 27, 2020

Difference between static and non static nested class in Java - Inner class

Oracle Java Study Material, Oracle Java Tutorials and Material, Oracle Java Certification, Oracle Java Inner Class

Static vs non Static class in Java


In Java you can make a class either static or non static. Now what is difference between making a class static vs non static? well there is lot of difference between them. First of all there are two kinds of class in Java, one is called top level class and other is called nested class. As name suggested top level class is a class which is declared in .java file and not enclosed under any other class. On other hand nested class is declared inside another class. The class which enclosed nested class is known as Outer class. Now let's come back to static vs non static class. In Java programming language you can not make a top level class static. You can only make nested class either static or non static. If you make a nested class non static then it also referred as Inner class. Now let's come to the point regarding Difference between static and non static nested class in Java

Difference between static and non static nested class in Java


1) Nested static class doesn't need reference of Outer class but non static nested class or Inner class requires Outer class reference. You can not create instance of Inner class without creating instance of Outer class. This is by far most important thing to consider while making a nested class static or non static.

2) static class is actually static member of class and can be used in static context e.g. static method or static block of Outer class.

3) Another difference between static and non static nested class is that you can not access non static members e.g. method and field into nested static class directly. If you do you will get error like "non static member can not be used in static context". While Inner class can access both static and non static member of Outer class.

Here is the code sample of using both nested static class vs non static class :

/**
 * Java program to demonstrate What is nested static and non static class.
 * How to create instance of static and non static class and How to call
 * methods of nested static and Inner class in Java. Overall comparison of
 * static vs non static class.
 */
class Outer{
    private static String message = "HelloWorld";

    // Static nested class
    private static class MessagePrinter{
        //Only static member of Outer class is directly accessible in nested static class

        public void printMessage(){
            // Compile time error if message field is not static
            System.out.println("Message from nested static class : " + message);
        }
    }

    //non static nested class - also called Inner class
    private class Inner{
   
        // Both static and non static member of Outer class is accessible in this Inner class
        public void display(){
            System.out.println(" Message from non static nested or Inner class : " + message);
        }
    }

    // How to create instance of static and non static nested class
    public static void main(String... args){
   
        // creating instance of nested Static class
        Outer.MessagePrinter printer = new Outer.MessagePrinter();
   
        //calling non static method of nested static class
        printer.printMessage();
   
        // creating instance of non static nested class or Inner class
   
        // In order to create instance of Inner class you need an Outer class instance
   
        Outer outer = new Outer(); //outer class instance for creating non static nested class
   
        Outer.Inner inner  = outer.new Inner();
   
        //calling non static method of Inner class
        inner.display();
   
        // we can also combine above steps in one step to create instance of Inner class
        Outer.Inner nonStaticIner = new Outer().new Inner();
   
        // similarly you can now call Inner class method
        nonStaticIner.display();
    }

}

Oracle Java Study Material, Oracle Java Tutorials and Material, Oracle Java Certification, Oracle Java Inner Class
Output:
Message from nested static class : HelloWorld
Message from non static nested or Inner class : HelloWorld
Message from non static nested or Inner class : HelloWorld

That's all on Difference between Static and non Static nested class in Java. So far we have only touched member Inner class and not discussed other two types on Inner class e.g. Local class and Anonymous Inner class. In this Java tutorial we have seen What is nested static class in Java and How to create instance of both nested static and non static class in Java.

In summary its easy to create instance of nested static class as it doesn't require instance of Outer class while non static nested class e.g. Inner class will always need an Outer class instance and can not exist without Outer class. If you have to choose between static vs non static class than prefer static nested class if you can use that.

Thursday, March 26, 2020

5 difference between Hashtable and HashMap in Java

Oracle Java Hashtable, Oracle Java HashMap, Oracle Java Tutorial and Material, Oracle Java Certifications, Oracle Java Exam Prep

Hashtable vs HashMap in Java


Hashtable and HashMap are two hash based collection in Java and used to store objects as key value pair. Despite being hash based and similar in functionality there are a significant difference between Hashtable and HashMap and without understanding those difference if you use Hashtable in place of HashMap than you may run into series of subtle programs which is hard to find and debug.Unlike Difference between ArrayList and HashMap,  Difference between Hashtable and HashMap are more subtle because both are similar kind of collection. Before seeing difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.

Similarities between Hashtable and HashMap in Java


There are lot of similar things between Hashtable and HashMap in Java which is good to know and these also helps to find exactly what is different between HashMap and Hashtable in Java:

1) Both Hashtable and HashMap implements java.util.Map interface.

2) Hashtable and HashMap both are a hash based collection and works on the principle of hashing.

3) Hashtable and HashMap both provide constant time performance for put and get method if objects are distributed uniformly across bucket.

4) From JDK 4 both Hashtable and HashMap are part of Java collection framework.

Difference between Hashtable and HashMap in Java


What is Difference between HashMap and Hashtable in Java CollectionDespite being so similar there are some differences between Hashtable and HashMap in Java which separates them completely, let's have a look:

1) First and most significantly different between Hashtable and HashMap are that HashMap is not thread-safe  while Hashtable is a thread-safe collection.

2) The second important difference between Hashtable and HashMap is performance since HashMap is not synchronized it perform better than Hashtable.

3) The third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

These were some important difference on Hashtable and HashMap in Java. If you know any other difference which is not included here then feels free to add them in the comment section. Remember this is an important question on Java interview and good to prepare it well.

Tuesday, March 24, 2020

Steps to Preparing for Oracle 1Z0–809 Certification Exam

OCPJP 1Z0-809 Overview

Java 8 Certification or OCJP Certification Syllabus (Oracle Certified Java Profession) has two certification exams. The first certification exam is called OCA (Oracle Certified Associate 1Z0-808). This java certification is known as Associates Certification. The second level exam is a slightly advanced level certification at some extent, called OCP 8 (Oracle Certified Professional 1Z0-809) exam.

1z0-809, OCPJP 1Z0-809, 1z0-809 exam, exam 1z0-809, 1z0-809 syllabus, OCPJP 1Z0-809, 1Z0-809 Certification Exam, Oracle 1Z0-809, 1Z0-809 Practice Tests, java 1z0-809, ocp 1z0-809, java se 8 programmer ii 1z0-809, ocp java se 8 programmer ii exam guide (exam 1z0-809) pdf, ocp java se 8 programmer ii exam guide (exam 1z0-809), ocpjp 8 syllabus, ocpjp, ocpjp 8, ocpjp syllabus, ocpjp certification

Oracle Java Certifications

The Java community is employing the knowledge, skills, and recognition acquired through Oracle Java Certification Exams to enhance their job prospects, receive higher salaries, and become more valuable employees for their organization.

Eventually, earning a Java Certification makes you a better Java programmer. You will become more relevant to your current and potential future manager, improve job security, and enhance your future prospects.

Java is the number one development platform, and it is NOT only confined to Enterprise Application Development but also widening its extent to distributed computing (like Apache Hadoop, etc.) and Machine Learning applications.

Because of the prevalence of Java, there is a constant requirement for well-qualified, highly-skilled certified Java programmers to formulate and maintain critical applications.

Oracle JAVA Certification | 1Z0-807 Certification | Java Certification | Java Career | 1Z0-808 Certification | 1Z0-803 Certification | 1Z0-804 Certification | 1Z0-805 Certification | 1Z0-809 Certification | 1Z0-895 Certification | 1Z0-897 Certification | 1Z0-899 Certification | 1Z0-810 Certification | 1Z0-813 Certification | JAVA Developer | Java Career Opportunities | OCAJP Certification | OCPJAP Certification | Java programming language
Energize Your Career Opportunities as a Java Developer

Oracle Java Certification exam intensifies & expand your knowledge and sharpens your skills through exposure to a broad array of distinctive features, functions, and tasks. As you study for java certification exams, you’ll make our way through hands-on exercises and labs practicing real Java code, which inflates your abilities as a Java developer.

Furthermore, the certification exams prove your skills using real-world, scenario-based questions that evaluate and challenge your ability to think and perform.

Furthermore, the certification exams prove your skills using real-world, scenario-based questions that evaluate and challenge your ability to think and perform.

To study well and get a high score in the 1Z0-809 certification exam, you must be disciplined and follow the tips described below. These tips have helped many aspirants in the past to score more than 90% on Java Certifications.

Best 6 Tips to Prepare Well for the 1Z0-809 Certification Exam


1. Coding, Coding, and Coding

There is no alternate for coding; you must code every day to promote a coding sense, which will help you to understand the code given in the real exam. In the case of a 1Z0-809 exam, it becomes even more complicated.

2. Understand the 1Z0-809 Syllabus

This is one of the fundamental mistakes many Java developers and programmers seeking for Oracle Java certification make. They don’t even read the Oracle Syllabus expecting that the book or study guide from which they are studying will comprise everything.

A brief overview is enough to start with and review it once in a while; you will find something which you have not studied yet.

Oracle 1Z0-809 Certification Syllabus:

  • Java Class Design
  • Advanced Java Class Design
  • Generics and Collections
  • Lambda Built-in Functional Interfaces
  • Java Stream API
  • Exceptions and Assertions
  • Use Java SE 8 Date/Time API
  • Java I/O Fundamentals
  • Java File I/O (NIO.2)
  • Java Concurrency
  • Building Database Applications with JDBC
  • Localization

3. Obtain a Good Study Book

Once you have bought the books, start reading every chapter in the book. Read every single line in the book. Also, practice the example programs to understand the concepts thoroughly. Otherwise, you may not be able to learn the essential concepts. Once you studied each chapter, read the important tips given at the end of each chapter. That is essential for you.

4. Participate in Community Discussions

My advice is to participate in some of the popular online community for OCPJP and ask your questions. This way, you will learn many new ideas from experienced professionals.

5. Make Notes

You are going to face many complicated concepts and complex code on your journey to being a Certified Java professional. While you are studying, write down the theories or code which don’t look familiar, or you are having difficulty with.

6. 1Z0-809 Practice Tests

Even though you might understand every concept, the exam is intended to confuse you, and see how you perform as a “compiling program.” Practice tests give you an accurate picture of where you stand, and what you should emphasize.

Moreover answering Java certification exam questions quickly does not come easily to most people. It takes a lot of practice and experience to understand a question, a code sample, and 4–6 answers, and be able to answer it in a minute or two - the best way is to give practice tests as many as possible.

Before you take the exam, it is essential you measure your learning. Failing the exam, not only will cost you hundreds of dollars, but you also have to wait one month to re-schedule the exam.

1z0-809, java 1z0-809, oracle 1z0-809, 1z0-809 exam, exam 1z0-809, ocp 1z0-809, java se 8 programmer ii 1z0-809, ocp java se 8 programmer ii exam guide (exam 1z0-809) pdf, 1z0-809 syllabus, 1z0-809 dumps, ocp java se 8 programmer ii exam guide (exam 1z0-809), ocpjp 8 syllabus, ocpjp, ocpjp 8, ocpjp syllabus, ocpjp certification, 1Z0-809 pdf, 1Z0-809 questions, 1Z0-809 exam guide, 1Z0-809 practice test, 1Z0-809 books, 1Z0-809 tutorial, 1Z0-809 syllabus, 1Z0-809 study guide, 1Z0-809, 1Z0-809 sample questions, 1Z0-809 exam questions, 1Z0-809 exam, 1Z0-809 certification, 1Z0-809 certification exam, 1Z0-809 dumps free download, 1Z0-809 dumps free

Concluding Words

The Oracle Java certification is undoubtedly acknowledged as one of the most distinguished certifications in the IT field from years. Whether you’re an experienced Java programmer or a beginner, the Java Programming certification will be positive for your career.

Your first motivation should be to enhance and update your understanding of the Java Language. However, you must keep in mind that achieving a Java certification is not a cakewalk: it requires preparation and takes remarkable time and effort.

Monday, March 23, 2020

JVM

7 JVM arguments of Highly Effective Applications

In this article, we are highlighting seven important JVM arguments that you may find it useful.

1. -Xmx and -XX:MaxMetaspaceSize


-Xmx is probably the most important JVM argument. -Xmx defines the maximum amount of heap size you are allocating to your application. (To learn about different memory regions in a JVM, you may watch this short video clip). You can define your application’s heap size like this:

-Xmx2g

Heap size plays a critical role in determining your

a. Application performance

b. Bill, that you are going to get from your cloud provider (AWS, Azure,…)

This brings question, what is the right heap size for my application? Should I allocate a large heap size or small heap size for my application? Answer is: ‘It depends’. In this article, we have shared our thoughts whether you need to go with large or small heap size.

You might also consider reading this article: advantages of setting -Xms and -Xmx to same value.

Metaspace is the region where JVM’s metadata definitions, such as class definitions, method definitions, will be stored.  By default, the amount of memory that can be used to store this metadata information is unlimited (i.e. limited by your container or machine’s RAM size). You need to use -XX:MaxMetaspaceSize argument to specify an upper limit on the amount of memory that can be used to store metadata information.

-XX:MaxMetaspaceSize=256m

2. GC Algorithm


As on date (March 2020), there are 7 different GC algorithms in OpenJDK:

a. Serial GC

b. Parallel GC

c. Concurrent Mark & Sweep GC

d. G1 GC

e. Shenandoah GC

f. Z GC

g. Epsilon GC

If you don’t specify the GC algorithm explicitly, then JVM will choose the default algorithm. Until Java 8, Parallel GC is the default GC algorithm. Since Java 9, G1 GC is the default GC algorithm.

Selection of the GC algorithm plays a crucial role in determining the application’s performance. Based on our research, we are observing excellent performance results with Z GC algorithm. If you are running with JVM 11+, then you may consider using Z GC algorithm (i.e. -XX:+UseZGC). 

Below table summarizes the JVM argument that you need to pass to activate each type of Garbage Collection algorithm.

GC Algorithm JVM argument 
Serial GC  -XX:+UseSerialGC
Parallel GC   -XX:+UseParallelGC 
Concurrent Market & Sweep (CMS) GC   -XX:+UseConcMarkSweepGC 
G1 GC  -XX:+UseG1GC 
Shenandoah GC  -XX:+UseShenandoahGC 
Z GC  -XX:+UseZGC 
Epsilon GC   -XX:+UseEpsilonGC 

3. Enable GC Logging


Garbage Collection logs contain information about Garbage Collection events, memory reclaimed, pause time duration, … You can enable Garbage collection log by passing following JVM arguments:

From JDK 1 to JDK 8:

-XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:{file-path}

From JDK 9 and above:

-Xlog:gc*:file={file-path}

Example:

-XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:/opt/workspace/myAppgc.log
-Xlog:gc*:file=/opt/workspace/myAppgc.log

Typically GC logs are used for tuning garbage collection performance. However, GC logs contain vital micro metrics. These metrics can be used for forecasting application’s availability and performance characteristics. In this article we would like to highlight one such micrometric: ‘GC Throughput‘. GC Throughput is the amount of time your application spends in processing customer transactions vs the amount of time it spends in processing GC activities. Say if your application’s GC throughput is 98%, then it means application is spending 98% of its time in processing customer activity, and the remaining 2% is spent in GC activity.

Now let’s look at the heap usage graph of a healthy JVM:

Core Java, Oracle JVM, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Exam Prep

Fig: Healthy JVM’s heap usage graph (generated by https://gceasy.io)

You can see a perfect saw-tooth pattern. You can notice that when Full GC (red triangle) runs, memory utilization drops all the way to bottom.

Now let’s look at the heap usage graph of a sick JVM:

Core Java, Oracle JVM, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Exam Prep

Fig: Sick JVM’s heap usage graph (generated by https://gceasy.io)

You can notice towards the right end of the graph, even though GC repeatedly runs, memory utilization isn’t dropping. It’s a classic indication that the application is suffering from some sort of memory problem.

If you take a closer look at the graph, you will notice that repeated full GC’s started to happen right around 8 am. However, the application starts to get OutOfMemoryError only around 8:45 am. Till 8 am, the application’s GC throughput was about 99%. But right after 8 am, GC throughput started to drop down to 60%. Because when repeated GC runs, the application wouldn’t be processing any customer transactions and it will only be doing GC activity. As a proactive measure, if you notice GC throughput starts to drop, you can take out the JVM from the load balancer pool. So that unhealthy JVM will not process any new traffic. It will minimize the customer impact.

Core Java, Oracle JVM, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Exam Prep

Fig: Repeated Full GC happens way before OutOfMemoryError

You can monitor GC related micrometrics in real time, using GCeasy REST API.

4. -XX:+HeapDumpOnOutOfMemoryError, -XX:HeapDumpPath


OutOfMemoryError is a serious problem that will affect your application’s availability/performance SLAs. To diagnose OutOfMemoryError or any memory-related problems, one would have to capture heap dump right at the moment or few moments before the application starts to experience OutOfMemoryError. As we don’t know when OutOfMemoryError will be thrown, it’s hard to capture heap dump manually at the right around the time when it’s thrown. However, capturing heap dumps can be automated by passing following JVM arguments:

 -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath={HEAP-DUMP-FILE-PATH}

In ‘-XX:HeapDumpPath’, you need to specify the file path where heap dump should be stored. When you pass these two JVM arguments, heap dumps will be automatically captured and written to a defined file path, when OutOfMemoryError is thrown. Example:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/crashes/my-heap-dump.hprof

Once heap dumps are captured, you can use tools like HeapHero, EclipseMAT to analyze heap dumps.

5. -Xss


Each application will have tens, hundreds, thousands of threads. Each thread will have its own stack. In each thread’s stack following information are stored:

a. Methods/functions that are currently executed

b. Primitive datatypes

c. Variables

d. object pointers

e. return values.

Each one of them consumes memory. If their consumption goes beyond a certain limit, then StackOverflowError is thrown. However, you can increase the thread’s stack size limit by passing -Xss argument. Example:

-Xss256k

If you set this -Xss value to a huge number, then memory will be blocked and wasted. Say suppose you are assigning -Xss value to be 2mb whereas, it needs only 256kb, then you will end up wasting huge amount of memory, not just 1792kb (i.e. 2mb – 256kb). Do you wonder why?

Say your application has 500 threads, then with -Xss value to be 2mb, your threads will be consuming 1000mb of memory (i.e. 500 threads x 2mb/thread). On the other hand, if you have allocated -Xss only to be 256kb, then your threads will be consuming only 125mb of memory (i.e. 500 threads x 256kb/thread). You will save 875mb (i.e. 1000mb – 125mb) of memory per JVM. Yes, it will make such a huge difference.

Note: Threads are created outside heap (i.e. -Xmx), thus this 1000mb will be in addition to -Xmx value you have already assigned. 

Our recommendation is to start from a low value (say 256kb). Run thorough regression, performance, and AB testing with this setting. Only if you experience StackOverflowError then increase the value, otherwise consider sticking on to a low value. 

6. -Dsun.net.client.defaultConnectTimeout and -Dsun.net.client.defaultReadTimeout


Modern applications use numerous protocols (i.e. SOAP, REST, HTTP, HTTPS, JDBC, RMI…) to connect with remote applications. Sometimes remote applications might take a long time to respond. Sometimes it may not respond at all.

If you don’t have proper timeout settings, and if remote applications don’t respond fast enough, then your application threads/resources will get stuck. Remote applications unresponsiveness can affect your application’s availability. It can bring down your application to grinding halt. To safeguard your application’s high availability, appropriate timeout settings should be configured.

You can pass these two powerful timeout networking properties at the JVM level that can be globally applicable to all protocol handlers that uses java.net.URLConnection:

1. sun.net.client.defaultConnectTimeout specifies the timeout (in milliseconds) to establish the connection to the host. For example, for HTTP connections, it is the timeout when establishing the connection to the HTTP server.

2. sun.net.client.defaultReadTimeout specifies the timeout (in milliseconds) when reading from the input stream when a connection is established to a resource.

Example, if you would like to set these properties to 2 seconds:

-Dsun.net.client.defaultConnectTimeout=2000
-Dsun.net.client.defaultReadTimeout=2000

Note, by default values for these 2 properties is -1, which means no timeout is set.

7. -Duser.timeZone


Your application might have sensitive business requirements around time/date. For example, if you are building a trading application, you can’t take transaction before 9:30 am. To implement those time/date related business requirements, you might be using java.util.Date, java.util.Calendar objects. These objects, by default, picks up time zone information from the underlying operating system. This will become a problem; if your application is running in a distributed environment. Look at the below scenarios:

a. If your application is running across multiple data centers, say, San Francisco, Chicago, Singapore – then JVMs in each data center would end up having different time zone. Thus, JVMs in each data center would exhibit different behaviors. It would result in inconsistent results.

b. If you are deploying your application in a cloud environment, applications could be moved to different data centers without your knowledge. In that circumstance also, your application would end up producing different results.

c. Your own Operations team can also change the time zone without bringing to the development team’s knowledge. It would also skew the results.

To avoid these commotions, it’s highly recommended to set the time zone at the JVM using the -Duser.timezone system property. Example if you want to set EDT time zone for your application, you will do:

-Duser.timezone=US/Eastern

Source: javacodegeeks.com

Saturday, March 21, 2020

What is double colon (::) operator in Java 8 - Example

The double colon (::) operator is known as the method reference in Java 8. Method references are expressions which have the same treatment as a lambda expression, but instead of providing a lambda body, they refer to an existing method by name. For example, to print all elements of the list, you can use the forEach() method as follows

list.stream.forEach( s-> System.out.println(s));

but here you can replace lambda expression with method reference to improve readability as shown below:

list.stream.forEach( System.out::println);

For referring a static method, you can either use className or instanceRef, but to refer an instance method of a particular object, you need instanceRef.

Here are some examples of a method reference in Java 8:

1. A static method (ClassName::methodName) like Person::getAge

2. An instance method of a particular object (instanceRef::methodName) like System.out::println

3. A super method of a particular object (super::methodName)

4. An instance method of an arbitrary object of a particular type (ClassName::methodName)

5. A class constructor reference (ClassName::new) like ArrayList::new

6. An array constructor reference (TypeName[]::new) like String[]:new

The idea is that if you are passing a lambda expression, e.g. a function that takes a value and prints in the console than instead of giving lambda expression, just pass the println() method of PrintStream class which you can access as System.out::println.

Real-world Example of Double Colon Operator in Java 8


Here is a real-world example fo method reference using a double colon operator in Java 8. In this example, we are creating a Comparator which compares person by their age. In the first example, we have used a lambda expression to pass the logic to compare age, while in the second line of code, we have used a double colon operator or method reference.

You can see that the second example is much more readable and clean:

Oracle Java Cert Exam, Oracle Java Learning, Oracle Java Guides, Oracle Java Learning

Btw, If you are using IDE like Eclipse, NetBeans, or IntelliJ IDEA, the IDE will also suggest you convert your lambda expression to method reference as shown in the following screenshot.

This confirms that it's a best practice in Java 8 to convert lambda expression to a method reference or constructor reference using a double colon operator.

Oracle Java Cert Exam, Oracle Java Learning, Oracle Java Guides, Oracle Java Learning

That's all about the double colon operator of Java 8. As I said, it's known as method reference and can be used to refer to an existing method by name instead of using a lambda expression.  It's a  Java 8 best practice to favor method reference over lambda expression as it results in cleaner code.

Friday, March 20, 2020

Abstract Class vs Interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Exam Prep

In Java, the Abstract classes and interfaces are fundamental building blocks as they both are used to implement one of the essential concepts of Object-Oriented Programming that is, Abstraction. Though both of them are used for Abstraction, they differ from each other, and we cannot use them interchangeably. We will compare abstract class vs interface, along with real-life examples. We will also discuss when we should use interfaces and abstract classes.

Abstract Class In Java


An Abstract class is a class whose objects can’t be created. It is a kind of guideline or a template for other classes. An abstract class should contain at least one abstract method (method without any implementation or method body).

◉ The abstract class is declared with the help of an abstract keyword.

◉ An abstract class can be considered as an incomplete class that does not represent complete behavior.

◉ The abstract class can have abstract methods (methods without body) as well as concrete methods (methods with the body).

◉ We can not create objects or instances from the abstract classes, but they can be subclassed.

Syntax of writing Abstract classes:

abstract class TestAbstractClass
{
  public abstract void abstractMethod();
  public void normalMethod()
  {
    //method body
  }
}

Reasons For Using Abstract Class in Java


◉ An abstract class provides a guideline or template for other future specific classes.
◉ An Abstract class gives a default functionality of Inheritance.
◉ The abstract class helps in achieving code reusability.
◉ The abstract class also allows us to define a common interface for its subclasses.

Abstract Methods in Java


◉ Abstract methods are methods with no implementation. They do not contain any method statement.

◉ The child classes of this abstract class must provide the implementation of these inherited abstract methods.

◉ An abstract method is declared with an abstract keyword.

◉ The declaration of an abstract method must end with a semicolon ;

Syntax of declaring abstract methods:

access-specifier abstract return-type method-name();

Example of Abstract class:

package com.oraclejavacertified.abstractclass;
//parent class
abstract class Animal
{
  //concrete method
  public void show1()
  {
    System.out.println("Concrete method of parent class Class");
  }
  //abstract method
  abstract public void show2();
  }
//child class
Class Dog extends Animal
{
  // Must Override this method while extending the parent class
  public void show2()
  {
    System.out.println("Overriding abstract method of parent class");
  }
  //Overriding concrete method is not compulsory
  public void show1()
  {
    System.out.println("Overriding concrete method of parent class");
  }
}
public class AbstractClassDemo
{
  public static void main(String[] args)
  {
    Dog obj = new Animal();
    obj.show2();
    obj.show1();
  }
}

Output:

Overriding abstract method of parent class
Overriding concrete method of parent class

Rules to be followed for Abstract Class


◉ The abstract class cannot be instantiated or we can’t create objects from abstract classes.

◉ The child class which extends the abstract class should implement all the abstract methods of the parent class otherwise, the child class should also be declared as an abstract class.


Interfaces in Java


An interface is another building block of Java which is a blueprint or template of a class. It is much similar to the Java class but the only difference is that it has abstract methods and static constants. There can be only abstract methods in an interface, that is there is no method body inside these abstract methods. The class that implements the interface should be declared as abstract, otherwise, all the methods of the interface need to be defined in the class.

Syntax of declaring Interfaces in Java:

To declare an interface, the interface keyword is used. Here is a syntax to declare an interface:

interface interface-name
{
  //abstract methods
}

Example:

Following is an example of an interface:

//Filename: NameOfInterface.java
                    import java.lang.*;
                    // Any number of import statements
                    interface NameOfInterface
                    {
                           // Any number of final, static fields
                           // Any number of abstract method declarations
                    }
Example:

//Filename : Animal.java

interface Animal
{
   public void eat();
   public void travel();
}


Reasons For Using Interfaces in Java


◉ It allows us to achieve a complete abstraction.

◉ Interfaces are mainly designed to support dynamic method resolution at run time.

◉ Interfaces allow us to achieve loose coupling.

◉ It also helps us to separate the definition of a method from the inheritance hierarchy.

Implementing Interfaces


A class implementing an interface can be thought of as the class assigning a contract. This means that the class agrees to perform the specific behaviors of the Interface. Unless a class is declared as abstract, it should perform all the behaviors of the Interface.

In order to implement an Interface in Java, a class uses the implements keyword. The implements keyword appears in the class declaration after the extends portion of the declaration.

Code to understand Interfaces in Java:

package com.oraclejavacertified.interfaces;
interface Polygon
{
  //declaring variables of the interface
  public static final int length = 4,breadth = 8;
  //declaring interface methods(without a method body)
  public void getName();
  public void getNumberOfSides();
  public void getArea();
  public void getPerimeter();
}
// Rectangle class "implements" the Polygon interface
class Rectangle implements Polygon
{
  public void getName()
  {
    // The body of getName() is provided here
    System.out.println("The name of the Polygon is: Rectangle");
  }
  public void getNumberOfSides()
  {
    // The body of getNumberOfSides() is provided here
    System.out.println("There are 4 sides in a Rectangle");
  }
  public void getArea()
  {
    // The body of getArea() is provided here
    System.out.println("The Area of Rectangle is: " +length*breadth);
  }
  public void getPerimeter()
  {
    // The body of getPerimeter() is provided here
    System.out.println("The Perimeter of Rectangle is: " +2*(length + breadth));
  }
}
class InterfaceDemo
{
  public static void main(String[] args)
  {
    Rectangle rectangle = new Rectangle(); // Create a Rectangle object
    //calling methods of class Rectangle
    rectangle.getName();
    rectangle.getNumberOfSides();
    rectangle.getArea();
    rectangle.getPerimeter();
  }
}

Output:

The name of the Polygon is: Rectangle
There are 4 sides in a Rectangle
The Area of Rectangle is: 32
The Perimeter of Rectangle is: 24

Rules to be followed for Interface


◉ The class that implements the Interface should implement all the methods defined in the Interface.

◉ An Interface can also contain final variables.

Abstract Class vs Interface in Java


We will compare Abstract Class vs Interface on the basis of following parameters:

S.No Parameter  Abstract Class   Interfaces 
1 Keyword Used An abstract keyword is used to create an abstract class. An interface keyword is used to create an interface.
Type of variables  Abstract class in Java can have both final, non-final, static and non-static variables.  An interface can only have final and static variables that are declared by default.
final variables  An abstract class may or may not have variables declared as final   In interfaces, variables are by default declared as final. 
Access Modifiers  Abstract classes can have all access modifiers: public, protected, private and default.  No other access modifiers are allowed except the public access modifier. 
Type of Methods  An abstract class can have both abstract and non-abstract or concrete methods.  An interface can only have abstract methods. From version 8 of Java, the interface supports static and non-static methods too. 
Constructors  An abstract class can have constructors  An interface can not have constructors 
Multiple Inheritance  Abstract classes do not support Multiple Inheritance. A class can extend only a single abstract class but can implement multiple Java interfaces.  Interfaces support Multiple Inheritance. 
Implementation  We can extend an abstract class using the extends keyword.  We can implement an interface using the implements keyword. 
Speed  Fast  Slow as it requires extra indirection. 
10  When to use  To avoid independence  For Future enhancement 

When to use Abstract Class?


Consider using abstract classes in the following cases:

◉ If you have some related classes that need to share the same lines of code, then we put these classes in abstract classes.

◉ If there is a requirement of using access modifiers other than public such as protected and private for methods or fields.

◉ When there is a need for defining a state of an object because we need to define a non-static or non-final field.

When to use Interface?


Consider using an interface in the following cases:

◉ When you want to achieve 100% abstraction.

◉ If you want to achieve multiple inheritance, that is, implementing more than one interface.

◉ When you want to specify the behavior of a particular data type irrespective of who implements its behavior.

Thursday, March 19, 2020

Java Comparator Interface

Java Comparator Interface, Oracle Java Study Materials, Oracle Java Tutorial and Material, Oracle Java Certification

There are many situations when we often need to compare two values in our Java programs. Comparing primitive values like int, char, float, boolean, etc., is very easy and we can compare them using the comparison operators like <, >, ==, etc. But what if we want to compare objects? For example, How would you compare two Employees? For this purpose, Java provides two interfaces, which are Comparable and Comparator Interface in Java.

Comparator Interface is one of the most useful topics in Java. The Comparator interface is an example of the Java library. We will also cover how to sort a collection with Java comparator with the example along with the working of Collections.Sort().

So, let’s start learning about Comparator Interface in Java.

Java Comparator Interface


Comparator Interface in Java is used to arrange or sort the objects of user-defined classes. For example, for a list of students’ objects, the natural order may be the order of employee unique id. But in real-life applications, we may want to sort the list of students by their first name, date of birth, year of admission, or simply any other such criteria. In such conditions, there is a need for the Comparator interface.

The Comparator interface of Java is present in java.util package. This interface contains 2 methods compare(Object obj1, Object obj2) and equals(Object element).

By default, we can not compare the objects of a user-defined class. To make an object of a user-defined class comparable, the class must implement the Comparable interface.

We can use the Comparator interface in the following situations:

◉ Use to sort or arrange the list or array of objects, other than the natural order.

◉ To arrange the array or list of objects where we can not modify the source code of an object to implement a Comparable interface.

◉ Use to sort the same array or list of objects in different fields.

◉ To use the group by sorting on a list or array of objects in different fields.

◉ Now, let’s understand the various methods of Java Comparator.

Methods of Java Comparator Interface


There are two methods of the Comparator Interface in Java, namely:

Methods Description
compare(Object obj1,Object obj 2) Compares the first object with another. 
equals(Object obj)   Compares the current object with the specified object. 

Comparator.compare() Method

The compare method is used to compare two objects.

Its syntax is:

public int compare(Object obj1, Object obj2)

This method compares its two arguments in order. It returns –

◉ a negative integer if the first argument is smaller than the second argument.
◉ zero, if the first argument is equal to the second argument.
◉ a positive integer, if the first argument is larger than the second argument.

For Example:

Suppose we have a Java array or an array list of our own class that contains fields like unique id, name, age, gender, etc., and we have to sort the list in the order of name or age. For this we can follow two approaches:

Approach 1:

One obvious approach is to compose our own method sort() by writing standard calculations in it. This will require going through the entire code for various basis like id, name, etc.

Approach 2:

Using this approach we can utilize the comparator interface – Java Comparator interface sorts the objects of a user-defined class. This interface in Java is available in java.util bundle package and contains 2 functions compare (Object obj1, Object obj2) and equals (Object obj).

Code to understand Collections.sort()

package com.oraclejavacertified.comparators;
import java.util.*;
// A class to represent an employee
class Employee
{
  int id, salary;
  String name;
  // Constructor
  public Employee(int id,int salary , String name)
  {
    this.id = id;
    this.salary= salary;
    this.name = name;
  }
  // Used to print student details in main()
  public String toString()
  {
    return this.id + " " + this.name+
        " " + this.salary;
  }
}
class SortById implements Comparator<Employee>
{
  // Used for sorting in ascending order of id
  public int compare(Employee a, Employee b)
  {
    return a.id - b.id;
  }
}
class SortByName implements Comparator<Employee>
{
  // Used for sorting in ascending order of name
  public int compare(Employee a, Employee b)
  {
    return a.name.compareTo(b.name);
  }
}
class SortBySalary implements Comparator<Employee>
{
  //Used for sorting in ascending order of roll salary
  public int compare(Employee a, Employee b)
  {
    return a.salary - b.salary;
  }
}
// Driver class
public class ComparatorInterfaceDemo
{
  public static void main (String[] args)
  {
    ArrayList<Employee> list = new ArrayList<Employee>();
    list.add(new Employee(111, 150000,"Rajeev"));
    list.add(new Employee(131, 100000,"Amit"));
    list.add(new Employee(121,250000, "Minie"));
    System.out.println("Unsorted List");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
    Collections.sort(list, new SortById());
    System.out.println("\nSorted by ID");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
    Collections.sort(list, new SortByName());
    System.out.println("\nSorted by Name");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
    Collections.sort(list, new SortBySalary());
    System.out.println("\nSorted by Salary");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
  }
}

Output:

Unsorted List
111 Rajeev 150000
131 Amit 100000
121 Minie 250000
Sorted by ID
111 Rajeev 150000
121 Minie 250000
131 Amit 100000
Sorted by Name
131 Amit 100000
121 Minie 250000
111 Rajeev 150000
Sorted by Salary
131 Amit 100000
111 Rajeev 150000
121 Minie 250000

Rules for Java Comparator Interface


There are certain rules for using Java Comparator Interface, they are as follows –

◉ You need to implement a Comparator interface if you want to sort the elements of a collection.

◉ You will need to mention the type of the parameter as Object when you override the compare() method. Because, if you do not specify any type of object in your Comparator interface, then, by default, it assumes that you are going to sort the objects of type Object.

◉ If you want to sort the elements of a user-defined type, then you need to specify the user-defined type generically while implementing the Comparator interface. When you do not specify the user-defined type while implementing the interface, then by default, it assumes them of type Object.

Java 8 Comparator Example: nullsFirst() and nullsLast() method


Here, we sort the list of elements that also contains null.

package com.oraclejavacertified.comparators;
import java.util.*;
class Employee
{
  int id;
  String name;
  int salary;
  public Employee(int id,String name,int salary)
  {
    this.id=id;
    this.name=name;
    this.salary=salary;
  }
  public int getID()
  {
    return id;
  }
  public void setID(int id)
  {
    this.id = id;
  }
  public String getName()
  {
    return name;
  }
  public void setName(String name)
  {
    this.name = name;
  }
  public int getSalary()
  {
    return salary;
  }
  public void setSalary(int age)
  {
    this.salary = age;
  }
}
// Driver class
public class ComparatorInterfaceDemo
{
  public static void main(String args[]){
    ArrayList<Employee> list=new ArrayList<Employee>();
    list.add(new Employee(101,"Rajeev",26000));
    list.add(new Employee(106,"Anil",21000));
    list.add(new Employee(105,null,30000));
                                 Comparator<Employee>cm1=Comparator.comparing(Employee::getName,Comparator.nullsFirst(String::compareTo));
    Collections.sort(list,cm1);
    System.out.println("Considers null to be less than non-null");
    for(Employee emp: list)
    {
      System.out.println(emp.id+" "+emp.name+" "+emp.salary);
    }
    Comparator<Employee>cm2=Comparator.comparing(Employee::getName,Comparator.nullsLast(String::compareTo));
    Collections.sort(list,cm2);
    System.out.println("\nConsiders null to be greater than non-null");
    for(Employee emp: list){
      System.out.println(emp.id+" "+emp.name+" "+emp.salary);
    }
  }
}

Output:

Considers null to be less than non-null
105 null 30000
106 Anil 21000
101 Rajeev 26000
Considers null to be greater than non-null
106 Anil 21000
101 Rajeev 26000
105 null 30000

Comparator vs Comparable in Java


Comparator Comparable
The Comparator sorts the attributes of different objects. Comparable interface sorts the objects with the natural order.
A Comparator interface compares the objects of two different classes. A Comparable interface compares “this” reference of the specified object.
The Comparator is present in the java.util package. The Comparable is present in java.lang package.
Comparator does not affect the original class. Comparable affects or modifies the original class.
Comparator provides compare() and equals() methods to sort the elements. Comparable provides a compareTo() method to sort the elements.

Wednesday, March 18, 2020

Java Garbage Collection

Java Garbage Collection

Garbage Collection is one of the most important features in Java which makes it popular among all the programming languages. The process of garbage collection is implicitly done in Java. Therefore, it is also called Automatic Garbage Collection in Java. The programmer does not need to explicitly write the code to delete the objects.

Let’s start discussing the concept of the Garbage Collection in Java.

Garbage Collection in Java


Garbage collection is the technique used in Java to deallocate or remove unreachable objects and unused memory. From the name itself, we can understand that Garbage Collection deals with tracking and deleting the garbage from the memory area.

However, in reality, Garbage Collection tracks each and every object available in the JVM heap space and removes the unused ones.

We know that all the objects that we dynamically create are allocated in the heap memory of the application. Normally, it is the duty of the programmer to both create and delete the objects in the program, but the programmer usually ignores the deletion of the object. This creates a problem of OutOfMemoryErrors due to insufficient memory because of not deleting the unwanted objects.

In Java, the programmer does not have to worry about the problem of releasing the memory of these unused or unwanted objects, as the garbage collection system always runs in the background, and its main aim is to free the memory heap by deleting unreachable objects.

Java Garbage Collection
Essentially, Garbage Collection is the process of tracking down all the objects that are still in use and marking the rest of them as garbage. The Garbage Collection process in Java is considered an automatic memory management schema because programmers do not have to explicitly deallocate the objects. The garbage collection in Java runs on low-priority threads.

The implementation of the Garbage Collection is present in the JVM (Java Virtual Machine). Each JVM can implement garbage collection. But there is only one requirement; that it should meet the JVM specification. Oracle’s HotSpot is one of the most common JVMs that offers a robust and mature set of garbage collection options.

Object Life Cycle in Java


The object life cycle in Java can be divided into 3 stages:

1. Object Creation

To create an object, generally, we use a new keyword. For example:

MyClass obj = new MyClass();

We created the object obj of class MyClass. When we create the object, a specific amount of memory is allocated for storing that object. The amount of memory allocated for objects can vary on the basis of architecture and JVM.

2. Object Usage

In this stage, the Object is in use by the other objects of the application in Java. During its usage, the object resides in memory and may refer to or contain references to other objects.

3. Object Destruction

The garbage collection system monitors objects and keeps a count on the number of references to each object. There is no need for such objects in our programs if there are no references to this object, so it makes perfect sense to deallocate this unused memory.

Unreachable Objects in Java


When an object does not contain any “reachable” reference to it, then we call it an unreachable object. These objects can also be known as unreferenced objects.

Example of unreachable objects: 

Double d = new Double(5.6);
// the new Double object is reachable via the reference in 'd'
d = null;
// the Integer object is no longer reachable. Now d is an unreachable object.

Eligibility for Garbage Collection in Java


An object can be eligible for garbage collection in Java if and only if it is unreachable. In the above program, after declaring d as null; double object 4 in the heap area becomes eligible for garbage collection.

Object Eligibility

Though Java has automatic garbage collection, an object should be made unreachable manually. There are different ways to know whether the object is eligible for Garbage Collection in Java.

There are generally four ways in Java to make an object eligible for garbage collection:

◉ Nullifying the reference variable
◉ Reassigning the reference variable
◉ Island of isolation
◉ Creating objects inside a class

Ways of requesting JVM to run Garbage Collector


Even if we make an object eligible for Garbage Collection in Java, it may or may not be eligible for Java Virtual Machine (JVM) to destroy. So there are some ways to request JVM to destroy this object and perform garbage collection.

There are two ways to request JVM for Garbage collection in Java which are:

◉ Using System.gc() method
◉ Using Runtime.getRuntime().gc() method

Code to understand the above two methods:

package com.oraclejavacertified.garbagecollection;
public class Demo
{
  public static void main(String[] args) throws InterruptedException
  {
    Demo obj1 = new Demo();
    Demo obj2= new Demo();
    // requesting JVM for running Garbage Collector
    System.gc();
    // Nullifying the reference variable
    obj2 = null;
    // requesting JVM for running Garbage Collector
    Runtime.getRuntime().gc();
  }
  @Override
  // finalize method is called on object once before garbage collecting it
  protected void finalize() throws Throwable
  {
    System.out.println("Garbage Collector ");
    System.out.println("Garbage collected object: " + this);
  }
}

Output:

Garbage Collector
Garbage collected object: com.oraclejavacertified.garbagecollection.Demo@17f18626

Before removing an object from memory, the garbage collection thread invokes the finalize() method of that object and gives an opportunity to perform any sort of cleanup required.

A Real-life Example of Garbage Collection


Let’s take a real-life example of a garbage collector.

Suppose you go for an internship at a particular company and you have to write a program that counts the number of employees working in the company, excluding interns. To implement this task, you have to use the concept of a garbage collector.

The actual task given by the company:

Question. Write a program to create a class Employee having the following data members.

1. An ID for storing unique id for every employee.

And, the class will have the following methods:

1. A default constructor to initialize the id of the employee.
2. A method show() to display ID.
3. A method showNextId() for displaying the ID of the next employee.

Any beginner, who doesn’t know the concept of garbage collector will write the following code to count the number of employees:

Code to count the number of employees in the company without using garbage collection:

class Employee
{
  private int ID;
  private static int nextId=1;
  //we make it static because it should be common among all and shared by all the objects
  public Employee()
  {
    this.ID = nextId++;
  }
  public void show()
  {
    System.out.println("Id=" +ID);
  }
  public void showNextId()
  {
    System.out.println("Next employee id will be="+nextId);
  }
}
public class CountEmployees
{
  public static void main(String args[])
  {
    Employee A=new Employee();
    Employee B=new Employee();
    Employee C=new Employee();
    A.show();
    B.show();
    C.show();
    A.showNextId();
    B.showNextId();
    C.showNextId();
    {
      //It is a sub block to keep all those interns.
      Employee X=new Employee();
      Employee Y=new Employee();
      X.show();
      Y.show();
      X.showNextId();
      Y.showNextId();
    }
    //After this brace, X and Y will be removed.
    //Therefore, now it should show nextId as 4.
    A.showNextId();
    //Output of this line should be 4 but the output we will get is 6.
  }
}

Output:

Id=1
Id=2
Id=3
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Id=5
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6

Now to get the correct output:

If we write the same code using the garbage collection technique, the garbage collector will see that the two objects are free. To decrement the value of the variable nextId, the garbage collector will call the finalize() method only when the programmers override it in their class.

And as we know that we have to request a garbage collector, and to do this, we have to write the following three steps before closing the brace of sub-block.

1. Set references to null (that is, X = Y = null;)
2. Call System.gc();
3. Call System.runFinalization();

Correct Code to count the number of employees (excluding interns) using garbage collection

//Correct code to count the number of employees excluding interns.
class Employee
{
  private int ID;
  private static int nextId=1;
  //we declare it static because it should be common among all and shared by all the objects
  public Employee()
  {
    this.ID = nextId++;
  }
  public void show()
  {
    System.out.println("Id="+ID);
  }
  public void showNextId()
  {
    System.out.println("Next employee id will be="+nextId);
  }
  protected void finalize()
  {
    --nextId;
    //In this case,
    //gc will call finalize()
    //for 2 times for 2 objects.
  }
}
public class CountEmployees
{
  public static void main(String args[])
  {
    Employee A=new Employee();
    Employee B=new Employee();
    Employee C=new Employee();
    A.show();
    B.show();
    C.show();
    A.showNextId();
    B.showNextId();
    C.showNextId();
    {
      //It is a sub-block to keep all those interns.
      Employee X=new Employee();
      Employee Y=new Employee();
      X.show();
      Y.show();
      X.showNextId();
      Y.showNextId();
      X = Y = null;
      System.gc();
      System.runFinalization();
    }
    E.showNextId();
  }
}

Output:

Id=1
Id=2
Id=3
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Id=5
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4


Garbage Collection Algorithms in Java


Garbage Collection Algorithms in Java helps to remove the unreferenced or unreachable objects. These algorithms always run in the background. There are several different types of Garbage Collection Algorithms in Java that run in the background. And among them, one of the algorithms is a Mark and Sweep algorithm.

Mark and Sweep Algorithm

Mark and Sweep algorithm is a fundamental and initial algorithm for Garbage Collection in Java. This algorithm basically performs two primary functions: mark and sweep. Firstly, it should track and detect unreachable objects and, secondly, it should release these objects from the memory heap area so that the programmer can use it again.

1. Mark phase – Mark live objects


It is the first phase of the algorithm in which there is the detection of all the objects that are still alive. It is a stage where the garbage collector identifies which parts of memory are in use and which are not in use.

In this phase when the condition is made, its check bit is set to 0 or false. We set the marked bit to 1 or true for all the reachable objects.

Here we can consider each object as a node and then we visit all the objects or nodes that are reachable from this object/node, and it repeats until we have visited all the reachable nodes.

◉ The root is a variable that refers to an object and is directly accessible by a local variable. We will assume that we have only one root.

◉ We can use markedBit(obj) to access the mark bit for an object.

Mark Phase Algorithm:

Mark(root)
If markedBit(root) = false then
    markedBit(root) = true
    For each v referenced by a root
         Mark(v)

Note: We can call Mark() for all the root variables if we have more than one root.

2. Sweep phase – Get rid of dead objects


The sweep phase algorithm “clears” all the inaccessible or unreachable objects that is, it releases the stored memory area for all the inaccessible objects. Each of the items whose check value is set to false is removed from the stack memory, for every single other reachable object, we set the value of the stamped bit to false.

Presently the check bit for all the reachable objects is set to false.

Sweep Collection Algorithm:

Sweep()
For each object p in a heap
    If markedBit(p) = true then
       markedBit(p) = false
    else
       heap.release(p)

‘Mark and Sweep’ algorithm is also called a tracing garbage collector because this algorithm is used to trace the objects. For example

◉ Marked bits set to false.
◉ Reachable objects are set to true.
◉ Non-reachable objects get clear from the heap.


Advantages of the Mark and Sweep Algorithm



◉ It is a cyclic process.
◉ There are no additional overheads that occur during the execution of an algorithm.

Disadvantages of the Mark and Sweep Algorithm


◉ While the Java garbage collection algorithm runs, normal program execution stops.
◉ It runs differently several times on a program.

Implementations or Types of Garbage Collection


JVM has four types of Garbage Collector implementations which are –

◉ Serial Garbage Collector
◉ Parallel Garbage Collector
◉ CMS Garbage Collector
◉ G1 Garbage Collector

Now, we will briefly discuss each type of garbage collector.

1. Serial Garbage Collector


It is the simplest Garbage Collector implementation as it basically works with a single thread and all the garbage collection events are conducted serially in one thread. As this collector can work on a single thread, it freezes all application threads when it runs. Hence, it is not preferred to use it in multi-threaded applications like server environments.

We can use the following argument to enable Serial Garbage Collector:

java -XX:+UseSerialGC -jar Application.java

2. Parallel Garbage Collector


It is the default Garbage Collector of the JVM and sometimes called Throughput Collectors. Unlike the Serial Garbage Collector, the Parallel Garbage Collector uses multiple threads to manage heap space. But at the same time, it also suspends other application threads while performing garbage Collection. Using this Garbage Collector, we can specify the maximum garbage collection threads throughput and footprint (heap size) and, pause time.

We can use the following argument to enable Parallel Garbage Collector,

java -XX:+UseParallelGC -jar Application.java

3. CMS (Concurrent Mark Sweep) Garbage Collector


The CMS Garbage Collection implementation uses multiple threads for garbage collection. This Garbage Collector is designed for applications that can afford to share processor resources with the garbage collector while the application is running and that prefer shorter garbage collection pauses. Simply we can say that applications using CMS respond slower on average but do not stop responding to perform garbage collection.

We can use the following flag to enable the CMS Garbage Collector:

java -XX:+UseParNewGC -jar Application.java

4. G1(Garbage First) Garbage Collector


G1 (Garbage First) Garbage Collector is the newest garbage collector which is designed as a replacement for CMS. It performs more efficiently as compared to CMS Garbage Collector. It is similar to CMS and is designed for applications running on multiprocessor machines with large memory space.

To enable the G1 Garbage Collector, we can use the following argument:

java -XX:+UseG1GC -jar Application.java

Advantages of Garbage Collection:


◉ There is no need to manually handle the memory allocation/deallocation because the JVM automatically performs the Garbage Collection for unused space in Java.

◉ There is no overhead of handling the Dangling Pointer.

◉ Garbage Collection takes care of a good portion of Automatic Memory Leak management.

Disadvantages of Garbage Collection:


◉ There is a more requirement of CPU power besides the original application, as JVM has to keep track of object reference creation/deletion. This may affect the performance of requests which require a huge memory.

◉ Programmers do not have any control over the scheduling of CPU time dedicated to freeing the unreachable objects.

◉ Using some Garbage Collection implementations an application may stop unpredictably.

◉ Automatic memory management is not much efficient proper manual memory allocation/deallocation.