Saturday 30 September 2023

Difference between PermGen(Permanent Generation) and Metaspace in Java

        In this post, we will discuss the difference between PermGen i.e Permanent Generation and Metaspace in java 8(feature).

        Before java 8, static methods and variables are stored in PermGen space but in java 8 they have introduced new memory space called Metaspace. The default allocation size of PermGen is 64MB, if it exceeds it should throw an OutOfMemoryError. As if we need to fix this issue need to increase the PermGen space using JVM parameter –XX:MaxPermSize.

       Metaspace memory space introduced in java 8 to resolve the above issue. Internally it will automatically increases the size when allocation memory size increases. No need to increase the memory size manually.

PermGen and Metaspace difference

Thank you for visiting the blog.

Wednesday 27 September 2023

Difference between equals method and == operator in java

      In this post, we can discuss one of the important java interview questions i.e difference between equals() and == operator and sample examples.

equals and == operator in java

The equals() method compares the content of two objects but == opeator checks the objects references of two objects for equality.

Let me see few examples to check both equals and == operator,

  • Created two string objects using new operator and applied equals and == operator to check the equality.
public class DemoClass {

     public static void main(String[] args) {

	  String s1 = new String("A");
	  String s2 = new String("A");

	  if (s1.equals(s2)) {
		System.out.println("s1 equals s2 are equal");
	  } else {
		System.out.println("s1 equals s2 are not equal");
	  }

	  if (s1 == s2) {
	       System.out.println("s1 == s2 are equal");
	  } else {
	       System.out.println("s1 == s2 are not equal");
	  }

      }
}

Output:- 
s1 equals s2 are equal
s1 == s2 are not equal

Used new operator to create String objects and those objects will store in heap memory of JVM and will create two different objects in the heap even the contents are same. So == operator result will return false.
  • Created two string objects using literal and applied equals and == operator to check the equality.
public class DemoClass {

     public static void main(String[] args) {

	  String s1 = "A";
	  String s2 = "A";

	  if (s1.equals(s2)) {
		System.out.println("s1 equals s2 are equal");
	  } else {
		System.out.println("s1 equals s2 are not equal");
	  }

	  if (s1 == s2) {
	       System.out.println("s1 == s2 are equal");
	  } else {
	       System.out.println("s1 == s2 are not equal");
	  }

      }
}

Output:-

s1 equals s2 are equal
s1 == s2 are equal

Youtube Video:-


Thank you for visiting blog.

Thursday 7 September 2023

Sort List In Ascending & Descending Order Using Java 8 stream API

        In one of the previous post, listed all the java 8 stream coding questions and answers(blog post). Today's post we will discuss one of the important coding questions i.e to sort the list in ascending and descending order using java 8 stream api.

1) Sort the string of list object in ascending order using java 8 stream

import java.util.Arrays;
import java.util.List;

public class SortExample {

    public static void main(String[] args) {

	 List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");

         listOfStrings.stream().sorted().forEach(s -> System.out.println(s));
    }

}

Output:- A
              B
              C
              E

2) Sort the string of list object in descending order using java 8 stream

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SortExample {

     public static void main(String[] args) {

	  List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");

          listOfStrings.stream().sorted(Comparator.reverseOrder())
                                              .forEach(s -> System.out.println(s));
     }

}

Output:-   E
                C
                B
                A

3) Sort the custom(Employee class) java object of list in ascending or descending order using java 8 stream

Employee.java,
public class Employee {
	
	private Long id;
	private String firstName;
	private String lastName;
	private String address;
      
        //constructor, setter and getter
       // and toString metghod
}

SortExample.java,
package com.main;

import java.util.ArrayList;
import java.util.List;

public class SortExample {

     public static void main(String[] args) {
		
	 Employee e1 = new Employee(1L, "Anil", "Nivargi", "XYZ");
	 Employee e2 = new Employee(2L, "Mahesh", "Nivargi", "XYZ");

	 List<Employee> employeeList = new ArrayList<>();
	 employeeList.add(e1);
	 employeeList.add(e2);
		
	  System.out.println("Sort a list in ascending order using firstName -");
		
	  //sort a list in ascending order using firstName
	  employeeList.stream().sorted((s1,s2) -> 
                        s1.getFirstName().compareTo(s2.getFirstName())).forEach(
                                 s -> System.out.println(s));
		
	  System.out.println("Sort a list in descending order using firstName -");
		
	    //sort a list in descending order using firstName
	  employeeList.stream().sorted((s1,s2) -> 
                        s2.getFirstName().compareTo(s1.getFirstName())).forEach(
                                 s -> System.out.println(s));

     }

}

Output:- 
Sort a list in ascending order using firstName -
Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]
Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
Sort a list in descending order using firstName -
Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]



Thank you reading the blog post.

Reference Posts:-

Friday 1 September 2023

Difference Between @Resource, @Autowired and @Inject in Spring Injection

         In this post, we will learn the difference between Resource, Autowired and Inject annotation. All these annotations are used to inject the bean dependencies. Resource and Inject annotations are defined in Java and Autowired annotation defined in Spring framework.

@Resource – It's defined in the javax.annotation package and it's part of java.

@Inject – It's defined in the javax.inject package and it's part of Java

@Autowired – It's defined in the package org.springframework.bean.factory and part of Spring framework.

          Internally @Inject and @Autowired annotations use the AutowiredAnnotationBeanPostProcessor to inject the dependencies. But @Resource annotation internally use CommonAnnotationBeanPostProcessor to inject the dependencies. Execution path/step is same for both Inject and Autowired annotations, Resource annotation execution paths also same but order of execution paths are not same.

  • @Inject and @Autowired
         1) Matches by Type
         2) Restricts by Qualifiers
         3) Matches by Name
  • @Resource
         1) Matches by Name
         2) Matched by Type
         3) Restricts by Qualifiers

Let us discuss with example of each Annotation execution path,

Notification.java,
public interface Notification {
    // some methods
}

Email.java,
import org.springframework.stereotype.Component;
@Component
public class Email implements Notification {
    // some methods
}

SMS.java,
import org.springframework.stereotype.Component;
@Component
public class SMS implements Notification {
    // some methods
}

Inject the above beans into the caller java class,

@Resource
@Qualifier("invalid")
private Notification email;
 
@Autowired
@Qualifier("invalid")
private Notification email;
 
@Inject
@Qualifier("invalid")
private Notification email;

when we execute above code, the @Resource annotation will work fine without any error but @Autowired and @Inject will fail and through an exception like below,

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.prj.basics.notification.Notification]

           The Resource annotation checks by field name and it found the bean definition using name i.e email and will create the bean object internally but other two annotations checks by qualifier i.e by bean name mentioned in the component and there is no bean name with invalid and throw an exception.

Below code should works for all three annotations without fail.
 
@Resource
@Qualifier("email")
private Notification email;
 
@Autowired
@Qualifier("email")
private Notification email;
 
@Inject
@Qualifier("email")
private Notification email;

OR 

@Resource
private Email email;
 
@Autowired
private Email email;
 
@Inject
private Email email;

Thank you for visiting the blog.

Reference posts:-