How to create immutable class in java

  • In Java String and all wrapper classes are immutable classes.
  • So how to create custom immutable class in java?
  • Lets see how to make a class object immutable.

  Immutable class:

  • Make class final so that it should not be inherited.
  • All the variables should be private so should not be accessible outside of class. 
  • Make all variables final so that value can not be changed.
  • A constructor to assign values to variables in class.
  • Do not add any setter methods.

1. Java Program to create custom immutable class object in java.

  1. package com.instaceofjava;

  2.  
  3. public final class ImmutableClass{
  4.   
  5. private final int a;
  6. private final int b;
  7.  
  8. ImmutableClass( int x, int y){
  9.  
  10.  a=x;
  11.  b=y; 

  12.  
  13. public getA(){
  14.  
  15.  return a;

  16. }
  17.  
  18. public getB(){
  19.  
  20.  return b;

  21. }
  22.  
  23. public static void main(String[] args) {
  24.  
  25. ImmutableClass obj= new ImmutableClass(10,20);
  26.  
  27. System.out.println("a="+obj.getA());
  28.  
  29. System.out.println("b="+obj.getB());
  30.  
  31. }
  32. }
Output:

  1. a=10
  2. b=20


String class in java: Immutable


  1. public final class String
  2.         implements java.io.Serializable, Comparable<String>, CharSequence
  3. {  
  4.   
  5. //String class variables

  6.   private final char value[];
  7.   private final int offset;
  8.   private final int count;
  9.   private int hash; // Default to 0
  10.   private static final ObjectStreamField[] serialPersistentFields =
  11.       new ObjectStreamField[0];
  12.   
  13. //String class constructor
  14. public String(String original) {
  15.  
  16.             int size = original.count;
  17.              char[] originalValue = original.value;
  18.              char[] v;
  19.              if (originalValue.length > size) {
  20.                 // The array representing the String is bigger than the new
  21.               // String itself.  Perhaps this constructor is being called
  22.                 // in order to trim the baggage, so make a copy of the array.
  23.                  int off = original.offset;
  24.                 v = Arrays.copyOfRange(originalValue, off, off+size);
  25.             } else {
  26.                  // The array representing the String is the same
  27.                  // size as the String, so no point in making a copy.
  28.                  v = originalValue;
  29.            }
  30.             this.offset = 0;
  31.              this.count = size;
  32.             this.value = v;
  33.         } 

  34. }



Java Program to find Sum of Digits


1. Java Program to find sum of digits without using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. int number;
  9. Scanner in = new Scanner(System.in);
  10.  
  11. System.out.println("Please Enter a number");
  12.  
  13. number=in.nextInt(); 
  14.  
  15. int sum=0 ;
  16.  
  17. while(number!=0){
  18.  
  19. sum=sum+(number%10);
  20. number=number/10;
  21. }
  22.  
  23. System.out.println("Sum of Digits ="+sum);
  24.  
  25. }
  26. }
Output:

  1. Please Enter a number
  2. 123
  3. Sum of Digits=6


2. Java Program to find sum of digits using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. int sum;

  7. public int CalRecSum(int n){
  8.  
  9. if(n==0){
  10. return sum;
  11. }
  12. else{
  13.  
  14.  sum+=n%10;
  15.  CalRecSum(n/10);
  16.  
  17.  
  18. return sum;
  19. }

  20. public static void main(String[] args) {
  21.  
  22. int number;
  23. Scanner in = new Scanner(System.in);
  24.  
  25. System.out.println("Please Enter a number");
  26.  
  27. number=in.nextInt(); 
  28.  
  29. SumOfDigits   ob= new SumOfDigits();
  30. System.out.println("Sum of Digits ="+ob.CalRecSum(number));
  31.  
  32. }
  33.  
  34. }


Output:

  1. Please Enter a number
  2. 326
  3. Sum of Digits=11

Swap two numbers without using third variable

1. Java Interview Program to Swap two numbers without using third variable in java



  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=20;
  8. int number2=30;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1+number2;
  15. number2=number1-number2;
  16. number1=number1-number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }
Output:

  1. Before Swapping
  2. Value of number1 is :20
  3. Value of number2 is :30
  4. After Swapping
  5. Value of number1 is :30
  6. Value of number2 is :20

2. Java Program to Swap two numbers by using division and multiplication.


  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=20;
  8. int number2=30;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1*number2;
  15. number2=number1/number2;
  16. number1=number1/number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }


Output:

  1. Before Swapping
  2. Value of number1 is :20
  3. Value of number2 is :30
  4. After Swapping
  5. Value of number1 is :30
  6. Value of number2 is :20


3. Java Program to Swap two integers by using bit wise operators


  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=2;
  8. int number2=4;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1^number2;
  15. number2=number1^number2;
  16. number1=number1^number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }
Output:

  1. Before Swapping
  2. Value of number1 is :2
  3. Value of number2 is :4
  4. After Swapping
  5. Value of number1 is :4
  6. Value of number2 is :2


HashSet class


Hierarchy of HashSet class:


 

 public class HashSet<E>
        extends AbstractSet<E>
           implements Set<E>, Cloneable, java.io.Serializable

Key points:

  • HashSet is sub class of AbstractSet class.
  • Underlying data structure of HashSet is HashTable.
  • HashSet implements Serializable and Cloneable interfaces
  • HashSet does not allow duplicate elements.
  • Insertion order is not preserved. No order(Based on hashcode of objects)



Constructors of HashSet:

1.HashSet( )
  • Creates an empty HashSet object with default initial capacity 16.  Fill ratio or load factor 0.75
2.HashSet(Collection obj)
  • This constructor initializes the hash set by using the elements of the collection obj.
3.HashSet(int capacity)
    • Creates an empty HashSet object with given capacity.
      4.HashSet(int capacity, float fillRatio)
      • This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments (fill ratio 0.1 to 1.0)

      Reverse words in a String

      1. Java Interview Program to Reverse words in a string


      1. package com.instaceofjava;
      2.  
      3. public class ReverseString {
      4.  
      5. public static void main(String[] args) {
      6.  
      7. String strng= "Instance of Java ";
      8.  
      9. String str[] =strng.split(" ");
      10.  
      11. String result="";
      12.  
      13. for(int i=str.length()-1;i>=0;i--){
      14.  
      15. result += str[i]+" ";
      16.  
      17. }
      18.  
      19. System.out.println(result );
      20. }
      21. }
      Output:

      1. Java of Instance



      2. Java Interview Program to Reverse words in a string


      1. package com.instaceofjava;
      2.  
      3. public class ReverseString {
      4.  
      5. public static void main(String[] args) {
      6.  
      7. String strng= "Instance of Java ";
      8.  
      9. StringBuilder sb = new StringBuilder(strng.length() + 1);
      10.  
      11.   String[] words = strng.split(" ");
      12.  
      13.   for (int i = words.length - 1; i >= 0; i--) {
      14.          sb.append(words[i]).append(' ');
      15.    }
      16.     
      17.     sb.setLength(sb.length() - 1); 
      18.  
      19.    String result= sb.toString();  
      20.  
      21.     System.out.println(result);

      22. }
      23. }
      Output:

      1. Java of Instance

      Introducton to Spring



      Spring Framework history:

      • Spring was developed in June,2003
      • Initially developed by Rod Johnson.
      • Latest version of  Spring Framework version 4.1.6 released in Mar 2015.

      What is Spring:
      • Spring is  Open Source Framework.
      • Spring is Lightweight Application Framework. 
      • Spring is  Simple framework.
      • Spring is loosely coupled. 
      • Spring is a complete and a modular framework,because spring can be used in all layers of applications means front end(Spring MVC),Database(Spring JDBC,Spring ORM).

      Why Spring:
      • Why Spring come in to picture is because of EJB fails,EJB having multiple configuration files,it is affected on performance.so spring came up.
      • Struts designed for Web Layer,like Other Frameworks also addressed specific layer,But Spring Framework provides solution to support all layers of application.
      • Spring is non invasive framework,means Spring doesn't force to implement or extend any class from predefined class from Spring API.

      Advantages of Spring:
      • Spring is open source and lightweight framework.
      • Spring is supports all layers including web layer.
      • Easy for testing.
      • Spring Supports POJO Model.
      • POJO-Plain Old Java Object. 
      • Spring works in simple Java environment,because it is non,invasive.
      • Spring can be integrated with any Application Server
      • Spring simplifies J2EE development. 



      Spring Modules:
       spring 1.x have seven modules,but in 2.x on wards we have 6 modules.
      • Spring Core
      • Spring DAO(Spring JDBC)
      • Spring AOP(Ascept Orient Programming)
      • Spring ORM(Spring Hibernate)
      • Spring MVC
      • Spring WEB
      • Spring Context(J2EE)  
      Spring 2.x Modules:
      from Spring 2.x ,Spring -WEB and Spring-MVC is combined.
      • Spring Core
      • Spring DAO(Spring JDBC)
      • Spring AOP(Ascept Orient Programming)
      • Spring ORM(Spring Hibernate)
      • Spring WEB-MVC
      • Spring Context(J2EE


      spring tutorial



      • Spring is combination of various modules Seven well defined modules,Most of them are reasonably independent.
      • Spring modules built using modular approach,you can use only required modules Each module is set of one or more JAR files
      • Spring’s core module is “Inversion of Control”(IoC) also known as “Dependency Injection”.
      • All other Spring modules are built on top of IoC.IoC is a Foundation or Container of Spring Framework.
      • Spring core module is the base module for all modules.
      Select Menu