Tuesday, July 26, 2022

Compact Strings in Java

In this post we’ll learn about a new feature Compact Strings in Java, added in Java 9, which adopts a more space-efficient internal representation for strings.

Motivation for Compact Strings in Java

Implementation of Java String class before Java 9 stored characters in a char array, using two bytes for each character - UTF-16 encoding. Since String is one of the most used class, String instances constitute a major component of heap usage. It has been observed that most String objects contain only Latin-1 characters which requires only one byte of storage. So internal storage always as UTF-16 means half of the storage is going unused.

Changes for Compact Strings

In order to make Strings more space efficient Java 9 onward internal representation of the String class has been modified from a UTF-16 char array to a byte array plus an encoding-flag field.

As per the Java Compact String feature, based upon the contents of the string characters are stored either as-

  • ISO-8859-1/Latin-1 (one byte per character), or
  • UTF-16 (two bytes per character)

The encoding-flag field indicates which encoding is used.

In the String class you can see the changes for the same-

Storage from char[] array, before Java 9

/** The value is used for character storage. */
 private final char value[]; 

has been changed to byte[] array

private final byte[] value;

Encoding-flag field is named as coder and is of type byte-

private final byte coder;

coder can have either of these two values-

@Native static final byte LATIN1 = 0;
@Native static final byte UTF16  = 1;

Based on whether the storage is Latin-1 or UTF-16 methods of the String class have different implementations too. In fact even the String class has two variants-

final class StringLatin1

final class StringUTF16

Based on the value of the encoding-flag field (coder) specific implementation is called by the methods of the String class.

public int compareTo(String anotherString) {
  byte v1[] = value;
  byte v2[] = anotherString.value;
  if (coder() == anotherString.coder()) {
    return isLatin1() ? StringLatin1.compareTo(v1, v2)
                        : StringUTF16.compareTo(v1, v2);
  }
  return isLatin1() ? StringLatin1.compareToUTF16(v1, v2)
                    : StringUTF16.compareToLatin1(v1, v2);
}

That's all for this topic Compact Strings in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Java join() Method - Joining Strings
  2. StringBuilder Class in Java With Examples
  3. Java String charAt() Method With Examples
  4. Check String Null or Empty in Java
  5. Find All Permutations of a Given String Java Program

You may also like-

  1. final Keyword in Java With Examples
  2. Race Condition in Java Multi-Threading
  3. Convert Numbers to Words Java Program
  4. Binary Tree Implementation in Java - Insertion, Traversal And Search
  5. Reduction Operations in Java Stream API
  6. Spring MVC Form Example With Bean Validation
  7. Python for Loop With Examples
  8. Data Compression in Hadoop

Monday, July 25, 2022

Matrix Addition Java Program

When you add two matrices addition is done index wise you add the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

As example– If you are adding two matrices of order 3X3

matrix addition java program

Thus the resultant matrix is-

matrix addition

Also remember these points when adding one matrix with another-

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix added with (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix addition Java program

 
import java.util.Scanner;

public class MatrixAddition {
  public static void main(String[] args) {
    int rowM, colM;
    Scanner in = new Scanner(System.in);
    
    System.out.print("Enter Number of Rows and Columns of Matrix : ");
    rowM = in.nextInt();
    colM = in.nextInt();
    
    int M1[][] = new int[rowM][colM];
    int M2[][] = new int[rowM][colM];
    int resMatrix[][] = new int[rowM][colM];
        
    System.out.print("Enter elements of First Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter elements of Second Matrix : ");    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
        
    // Addition logic 
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        resMatrix[i][j] = M1[i][j] + M2[i][j];
      }
    }
        
    // Printing the result matrix 
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

Enter Number of Rows and Columns of Matrix :  3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1

Result Matrix : 
 3   10  5 
 2   9   12 
 13  11  3 

That's all for this topic Matrix Addition Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Multiplication Java Program
  2. Array in Java
  3. Remove Duplicate Elements From an Array in Java
  4. Find Largest and Second Largest Number in Given Array Java Program
  5. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program

You may also like-

  1. Java Program to Display Prime Numbers
  2. Factorial program in Java
  3. Count Number of Times Each Character Appears in a String Java Program
  4. Encapsulation in Java
  5. Java Variable Types With Examples
  6. How HashMap Works Internally in Java
  7. AtomicInteger in Java With Examples
  8. Dependency Injection in Spring Framework

Tuesday, July 19, 2022

Java Program to Check Prime Number

In this post we'll see a Java program to check whether given number is a prime number or not.

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example- 2, 3, 5, 7, 11, 13, 17 ….

First thing that may come to mind, while writing Java program for checking prime number, is to have a variable in a for loop that starts from 2 (as 1 will always divide the number) and increment it by one until it reaches the number that is checked for being prime number or not. In every iteration of the loop divide the number by variable, if remainder is zero at any time then the checked number is not a prime number.

That loop would look something like this-

for(int i = 2; i < num; i++){
  if(num % i == 0){
    flag = false;
    break;
  }
}

But that logic can be made more efficient. To check if a number is prime or not you need to run a loop starting from 2 till number/2 to check if number has any divisor.

As example- If number is 8 then you just need to check till 4 (8/2) to see if it divides by any number or not. Same way if you have a number 15 you just need to check till 7 to see if it divides completely by any number or not. We'll use the same logic to write our program to check for prime number.

Java program to check prime number or not

import java.util.Scanner;

public class PrimeCheck {
  public static void main(String[] args) {
    // take input from the user
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number - ");

    int num = sc.nextInt();
    boolean flag = isPrime(num);
    if(flag){
      System.out.println(num + " is a prime number.");
    }else{
      System.out.println(num + " is not a prime number.");
    }
  }
    
  private static boolean isPrime(int num){
    boolean flag = true;
    // loop from 2, increment it till number/2
    for(int i = 2; i < num/2; i++){
      // no remainder, means divides 
      if(num % i == 0){
        flag = false;
        break;
      }
    }
    return flag;
  }
}

Output

Enter number - 
16
16 is not a prime number.

Enter number - 
31
31 is a prime number.

Here scanner class is used to get input from the user.

That's all for this topic Java Program to Check Prime Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Program to Display Prime Numbers
  2. How to Display Pyramid Patterns in Java - Part1
  3. Armstrong Number or Not Java Program
  4. Fibonacci Series Program in Java
  5. Converting int to String in Java

You may also like-

  1. Reading File in Java Using BufferedReader
  2. Count Number of Words in a String Java Program
  3. Abstraction in Java
  4. Inheritance in Java
  5. static Keyword in Java With Examples
  6. Difference Between ReentrantLock and Synchronized in Java
  7. Dependency Injection in Spring Framework
  8. Difference Between Checked And Unchecked Exceptions in Java

Monday, July 18, 2022

How to Find Common Elements Between Two Arrays Java Program

This post is about writing a Java program to find common elements between two given arrays. It is a common interview question where it is asked with a condition not to use any inbuilt method or any inbuilt data structure like list or set.

Steps for solution

A simple solution to find common elements between two arrays in Java is to loop through one of the array in the outer loop and then traverse through the other array in an inner loop and compare the element of the outer array with all the elements of the inner array. If similar element is found print it and break from the inner loop.

Find common elements between two given arrays of integers

 
public class FindCommonElement {
 public static void main(String[] args) {
  int[] numArray1 = {1, 4, 5};
  int[] numArray2 = {6, 1, 8, 34, 5};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i] == numArray2[j]){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }  
 }
}

Output

 
1
5

Find common elements between two arrays of strings

Logic to find common elements between two arrays remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.

 
public class FindCommonElement {
 public static void main(String[] args) {
  String[] numArray1 = {"Java", "Scala", "Python"};
  String[] numArray2 = {".Net", "Scala", "Clojure", "Java", 
    "Java Script", "Python"};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i].equals(numArray2[j])){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
 }
}

Output

 
Java
Scala
Python

That's all for this topic How to Find Common Elements Between Two Arrays Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Remove Duplicate Elements From an Array in Java
  2. How to Remove Elements From an Array Java Program
  3. Array in Java
  4. Matrix Addition Java Program
  5. If Given String Sub-Sequence of Another String in Java

You may also like-

  1. Convert String to Byte Array Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Lambda Expression Comparator Example
  4. Java Program to Create Your Own BlockingQueue
  5. AtomicInteger in Java With Examples
  6. New Date And Time API in Java With Examples
  7. How HashMap Works Internally in Java
  8. Spring MessageSource Internationalization (i18n) Support

Sunday, July 17, 2022

Type Wrapper Classes in Java

As explained in the post primitive data types in Java there are eight primitive data types and most of the time you will use the primitive types in your code as it reduces the object creation overhead making it more efficient to use primitive types. But there are scenarios when you would want to use objects in place of primitives for that Java platform provides wrapper classes for each of the 8 primitive data types. These classes "wrap" the primitive in an object thus the name wrapper classes. Note that all the wrapper classes in Java are immutable.

Java Wrapper Classes

Eight wrapper classes used to wrap primitive data types are as given below-

Primitive TypeType Wrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

Note that 6 of these are numeric and numeric wrapper classes are subclasses of the abstract class Number class in Java:

Wrapper classes in Java

When do we need wrapper classes in Java

You need to use wrapper classes when you want an object holding primitive data, some of the scenarios where you will need wrapper classes are–

  1. You want to add primitive value in an Object[] array.
  2. You want to add primitive type to any collection like ArrayList, HashMap as you can add only objects to collection classes.
  3. You want to use any of the utility function provided by the wrapper classes for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

Java Wrapper classes examples

  1. If you want to convert int to a float number.

    In Integer class there is a floatValue() method that can be used for the purpose.

    int num = 25;
    Integer i = new Integer(num);
    float fNum = i.floatValue();
    System.out.println("float Value " + fNum);
  2. If you want to convert double value to a string.
    double d = 25.67;
    String str = Double.toString(d);
    System.out.println("string " + str);
    
  3. If you want to know the min and max range of any type, like for integer
    System.out.println("Integer min value " + Integer.MIN_VALUE);
    System.out.println("Integer max value " + Integer.MAX_VALUE);
    

    Output

    Integer min value -2147483648
    Integer max value 2147483647
    

    For double

    System.out.println("Double min value " + Double.MIN_VALUE);
    System.out.println("Double max value " + Double.MAX_VALUE);
    

    Output

    Double min value 4.9E-324
    Double max value 1.7976931348623157E308
    

Autoboxing and unboxing

Here autoboxing and unboxing in Java should get an honorable mention; autoboxing and unboxing feature was added in Java 5 and it converts primitive into object and object into primitive automatically. In many cases now you don’t need to convert using utility methods as it will happen automatically.

As example you can directly assign int value to an Integer object–

Integer i = 25;

Now conversion and method call (valueOf()) in this case will be done by compiler.

Equivalent code if you were converting yourself–
int num = 25;
Integer i = Integer.valueOf(num);

That's all for this topic Type Wrapper Classes in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Primitive Data Types in Java
  2. Object Creation Using new Operator in Java
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. Convert String to float in Java
  5. Convert int to String in Java

You may also like-

  1. Type Casting in Java With Conversion Examples
  2. static Reference to The Non-static Method or Field Error
  3. Constructor Overloading in Java
  4. Java Exception Handling And Method Overriding
  5. How HashMap Works Internally in Java
  6. Fail-Fast Vs Fail-Safe Iterator in Java
  7. Factorial Program in Java
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Saturday, July 16, 2022

Unmodifiable or Immutable Map in Java

An unmodifiable Map in Java is one whose keys and values cannot be added, removed, or updated once the unmodifiable instance of a Map is created. In this post we’ll see how Unmodifiable Map was created before Java 9 and how it can be created Java 9 onward using Immutable Map Static Factory Methods.


Creating Unmodifiable Map before Java 9

Till Java 8 in order to create unmodifiable Map Collections.unmodifiableMap() method was used.

Collections.unmodifiableMap(Map<? extends K,? extends V> m)- Returns an unmodifiable view of the specified map. Attempt to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.

Drawback of this method is that the underlying Map is still modifiable let’s try to see it with an example.

public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = new HashMap<String, String>();
    alphaMap.put("1", "a");
    alphaMap.put("2", "b");
    alphaMap.put("3", "c");
    alphaMap.put("4", "d");
    Map<String, String> aMap = Collections.unmodifiableMap(alphaMap);
    // still mutable
    alphaMap.put("5", "e");
    System.out.println("alphaMap- " + alphaMap);
    //error as this Map is an unmodifiable view
    aMap.put("6", "f");
  }
}

Output

alphaMap- {1=a, 2=b, 3=c, 4=d, 5=e}
Exception in thread "main" 
java.lang.UnsupportedOperationException
 at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1455)
 at org.netjs.Programs.UnmodifiableMap.main(UnmodifiableMap.java:20)

As you can see original map alphaMap can still be modified, though the unmodifiable Map view can’t be modified.

Creating Unmodifiable Map in Java 9

The Map.of (Java 9), Map.ofEntries (Java 9), and Map.copyOf (Java 10) static factory methods provide a convenient way to create unmodifiable maps. The Map instances created by these methods have the following characteristics:

  1. They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method results in UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  2. Immutable maps don't allow null keys and values. Attempts to create them with null keys or values result in NullPointerException.
  3. Duplicate keys are rejected at creation time itslef. Passing duplicate keys to a static factory method result in IllegalArgumentException.
  4. Immutable maps are serializable if all keys and values are serializable.
  5. The iteration order of mappings is unspecified and is subject to change.

Java Map.of() methods for creating unmodifiable Map

Map.of() static factory method is a convenient way to create unmodifiable maps Java 9 onward. This method is overloaded to have up to 10 elements and the form of the method is as follows.

Map.of()- Returns an unmodifiable map containing zero mappings. 
Map.of(K k1, V v1)- Returns an unmodifiable map containing a single mapping.
..
..
Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9)- Returns an unmodifiable map containing nine mappings. 
Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)- Returns an unmodifiable map containing ten mappings.

Map.of() method Java example

public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = Map.of("1","a", "2","b", "3","c", "4","d");
    System.out.println("alphaMap- " + alphaMap);
    // Error
    alphaMap.put("5", "e");
  }
}

Output

alphaMap- {2=b, 1=a, 4=d, 3=c}
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
 at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:731)
 at org.netjs.Programs.UnmodifiableMap.main(UnmodifiableMap.java:13)

As you can see trying to modify the immutable Map results in UnsupportedOperationException.

Java Map.ofEntries() method for creating unmodifiable Map

  • Map.ofEntries(Map.Entry<? extends K,? extends V>... entries)- Returns an unmodifiable map containing keys and values extracted from the given entries. The entries themselves are not stored in the map.
import java.util.Map;
import static java.util.Map.entry;

public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = Map.ofEntries(entry("1", "a"), entry("2", "b"),
                     entry("3", "c"), entry("4", "d"));
    System.out.println("alphaMap- " + alphaMap);
  }
}

Output

alphaMap- {3=c, 2=b, 1=a, 4=d}

Map.copyOf() method in Java

If you want to create an unmodifiable Map using an existing collection then you can use copyOf() method.

  • Map.copyOf(Map<? extends K,? extends V> map)- Returns an unmodifiable Map containing the entries of the given Map. The given Map must not be null, and it must not contain any null keys or values. If the given Map is subsequently modified, the returned Map will not reflect such modifications.
public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = new HashMap<String, String>();
    alphaMap.put("1", "a");
    alphaMap.put("2", "b");
    alphaMap.put("3", "c");
    alphaMap.put("4", "d");
    Map<String, String> aMap = Map.copyOf(alphaMap);
    System.out.println(" aMap- " + aMap);
  }
}

Output

 aMap- {1=a, 4=d, 3=c, 2=b}

That's all for this topic Unmodifiable or Immutable Map in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Loop Through a Map in Java
  2. Unmodifiable or Immutable Set in Java
  3. Difference Between HashMap And ConcurrentHashMap in Java
  4. TreeMap in Java With Examples
  5. Difference Between ArrayList And LinkedList in Java

You may also like-

  1. ConcurrentSkipListMap in Java With Examples
  2. Java ReentrantLock With Examples
  3. Java Lambda Expression And Variable Scope
  4. Map Operation in Java Stream API
  5. Java Abstract Class and Abstract Method
  6. Java Program to Convert a File to Byte Array
  7. Autowiring in Spring Using @Autowired and @Inject Annotations
  8. Python count() method - Counting Substrings

Wednesday, July 6, 2022

String Pool in Java

String in Java is one of the most used class so there are certain optimizations done to make Strings more efficient, one of that optimization is String pool in Java which reduces the memory usage of the String objects. Use of the string pool is possible because of another design decision; making String immutable in Java.

Java String pool

As the name itself suggests String pool is a pooling of String objects. So, the question is on what basis Strings are pooled and how does it reduces memory usage?

In more technical term it can be explained as when JVM sees a String literal it interns the created String object i.e. stores it in a pool that has only one such copy of that String.

To explain it in detail we’ll have to start from the beginning!

As you must be knowing there are two ways to create a String in Java–

  • Using String literal
  • Using new keyword
When you create a String using String literal, for example-
String str = “abc”

Memory allocation for this string object happens in an area knows as string pool in Java which is part of the heap memory.

Java String pool

When you create any String literal, JVM searches the String pool for any String having the same value, if such a value is found reference to the same memory is returned. So, new memory is not allocated for the same string rather the reference is shared among the String literals having the same value.

If String with same value is not found in the pool the new value is added to the pool and its reference is returned.

For example, if two Strings are created as follows-

String str1 = “abc”;
String str2 = “abc”;

Then the reference is shared by both the objects.

You can also check it using a Java program by creating two String literal having same value and then compare their references using equality ‘==’ operator, if true is returned that means both have the same reference.

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
 }
}

Output

str1 and str2 are same

String created using new operator

Where as when you create a String object using new operator, it always creates a new object in heap memory.

For example, if three Strings are created as follows-

String str1 = “abc”;
String str2 = new String(“abc”);
String str3 = new String(“abc”);

Then str1 is stored in a pool where as new objects are created for str2 and str3.

string interning

Here is a Java example to check the same. If we create two more strings using new operator and then compare reference those references should be different.

public class StringDemo {
 public static void main(String[] args) {
  // Literals
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
  // Using new operator
  String str3 = new String("abc");
  String str4 = new String("abc");
  if(str3 == str4){
   System.out.println("str3 and str4 are same");
  }else{
   System.out.println("str3 and str4 are not same");
  }
  
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str2 are same
str3 and str4 are not same
str1 and str4 are not same

Here it can be seen that str3 and str4 are having separate reference as those strings are created using new operator.

Explicitly interning a String

You can explicitly intern a string using intern() method in Java.

As per Java docs- “When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.”

In the previous example if str4 is changed and uses intern() method then str4 should also return a reference a similar to str1 and str2.

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
  String str3 = new String("abc");
  String str4 = new String("abc").intern();
  if(str3 == str4){
   System.out.println("str3 and str4 are same");
  }else{
   System.out.println("str3 and str4 are not same");
  }
  
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str2 are same
str3 and str4 are not same
str1 and str4 are same

It can be seen that str1 and str4 are having the same reference now.

String pool values are garbage collected

Strings in the Java string pool are eligible for garbage collection if there are no references to them.

That's all for this topic String Pool in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. How to Create Immutable Class in Java
  2. Java String Interview Questions And Answers
  3. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Java Program to Find The Longest Palindrome in a Given String

You may also like-

  1. Java for Loop With Examples
  2. Java Abstract Class and Abstract Method
  3. TreeSet in Java With Examples
  4. Thread States (Thread Life Cycle) in Java Multi-Threading
  5. Java Stream API Tutorial
  6. DataSource in Java-JDBC
  7. Spring Web MVC Tutorial
  8. Class And Object in Python