Java String

What is String in Java?

Java String is a sequence of characters.

Java String variable contains a collection of characters surrounded by double quotes.

An array of characters works same as Java String.

Java Strings are used for storing text.

In Java, Strings are immutable or final or constant which means each time when we are creating or editing or performing any method to change string, one string created in "String Constant Pool"

How to create a String in Java?

There are two ways to create a String object:

  1. By string literal
  2. By new keyword

1- String literal

String str1 = "Hello World!";
String str2 = "Hello World!";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool.

In other words, we don't create any String object using new keyword above. The JVM does that task for us, it create a String object. If the String object exist in the memory, it doesn't create a new String object rather it assigns the same old object to the new instance, that means even though we have two String instances above(str1 and str2) compiler only created one String object and assigned the same to both the instances.

For example there are 5 String instances that have same value, it means that in memory there is only one String object having the value and all the 5 String instances would be pointing to the same String object.

What if we want to have two different String object with the same String. For that we would need to create Strings using new keyword

2- Using new keyword

String str1 = new String("Hello World!");
String str2 = new String("Hello World!");

In such case, the JVM will create a new String object in normal (non-pool) heap memory.

Notice that JVM handles allocation of memory space for string variables efficiently, whenever we create a String variable and assign a String value with String Literal(double quotes) , JVM check value of String variable in String pool, if found, it returns reference of String object, if not found then it creates a new String object in String pool and return reference of it.

I found some images from google to represent. So, there are three images below.

Continue reading

How to install Java with Jabba

Runtime version managers make developers life easier. So, I tested different Java version managers. But, Jabba is the easiest one for me.

You can read previously posted How to install java articles.

Installing Jabba

Click Jabba link to see more detailed information about Jabba

$ curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | bash && . ~/.jabba/jabba.sh

Make sure to source jabba.sh in your environment if you skip it:

$ [ -s "$JABBA_HOME/jabba.sh" ] && source "$JABBA_HOME/jabba.sh"

If you don't have JAVA_HOME environment variable, run the following code:

$ echo 'export JAVA_HOME=$HOME/.jabba/jdk/openjdk@1.14.0-1/Contents/Home' >> ~/.bash_profile
$ echo 'export JAVA_HOME=$HOME/.jabba/jdk/openjdk@1.14.0-1/Contents/Home' >> ~/.bashrc
$ echo 'export JAVA_HOME=$HOME/.jabba/jdk/openjdk@1.14.0-1/Contents/Home' >> ~/.zshrc
Continue reading

How to install Java with brew and jenv

jenv is a tool that helps you switch between different java versions in your development machine. But, Jenv doesn't install Java for you.

Use your platform appropriate package manager to install Java. On macOS, brew is recommended.

Install Java with Homebrew

First, ensure that you have Homebrew installed in your system. Homebrew is a package manager for Mac OS. So if you want to learn more details about it, visit my blog below.

I also posted how to install Java JDK manually in the following post.

Actually I already mentioned how to install Java JDK in the above post, but I will shortly show one more time

$ brew tap adoptopenjdk/openjdk
$ brew search jdk

==> Formulae
openjdk                                                                              openjdk@11

==> Casks
adoptopenjdk
adoptopenjdk12
adoptopenjdk13-openj9
adoptopenjdk14-openj9-jre-large
adoptopenjdk9
adoptopenjdk10
adoptopenjdk12-jre
adoptopenjdk13-openj9-jre
adoptopenjdk14-openj9-large
jdk-mission-control
adoptopenjdk11
adoptopenjdk12-openj9
adoptopenjdk13-openj9-jre-large
adoptopenjdk8
oracle-jdk
adoptopenjdk11-jre
adoptopenjdk12-openj9-jre
adoptopenjdk13-openj9-large
adoptopenjdk8-jre
oracle-jdk-javadoc
adoptopenjdk11-openj9
adoptopenjdk12-openj9-jre-large
adoptopenjdk14
adoptopenjdk8-openj9
sapmachine-jdk
adoptopenjdk11-openj9-jre
adoptopenjdk12-openj9-large
adoptopenjdk14-jre
adoptopenjdk8-openj9-jre
adoptopenjdk11-openj9-jre-large
adoptopenjdk13
adoptopenjdk14-openj9
adoptopenjdk8-openj9-jre-large
adoptopenjdk11-openj9-large
adoptopenjdk13-jre
adoptopenjdk14-openj9-jre
adoptopenjdk8-openj9-large
$ brew cask install adoptopenjdk
$ java --version

openjdk 14.0.1 2020-04-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.1+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 14.0.1+7, mixed mode, sharing)
Continue reading

How to install Maven

Downloading and Installing Maven

if you want to download Maven manually, download it from http://maven.apache.org/download.cgi

But you can download Maven programmatically as the following. So, run below script in your terminal.

wget https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz

tar -xzvf apache-maven*bin.tar.gz

# Fix the permissions:
# chown -R root:wheel Downloads/apache-maven*

mkdir /usr/local/apache-maven

mv apache-maven* /usr/local/apache-maven

rm apache-maven*

Setting environment variables in zsh

If you are using zsh, then run the following script in your terminal.

nano ~/.zshrc

export M2_HOME=/usr/local/apache-maven/apache-maven-3.6.3
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

source ~/.zshrc

Setting environment variables in bash

nano ~/.bashrc

# add these three lines at the end of file and CTRL+X and Y and click enter :)

export M2_HOME=/usr/local/apache-maven/apache-maven-3.6.3
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

source ~/.bashrc

Check Maven Version

# Verify if Maven is running
mvn -version

How to install Java

Downloading and Installing Java from OpenJDK

if you want to download OpenJDK manually, download it from https://jdk.java.net/

But you can download JDK programmatically as the following. Java SE 7, 8, 9, 10, 11, 12, 13 are included below script. So, run below script in your terminal.

# Java SE 7
wget https://download.java.net/openjdk/jdk7u75/ri/openjdk-7u75-b13-linux-x64-18_dec_2014.tar.gz

# Java SE 8
wget https://download.java.net/openjdk/jdk8u40/ri/openjdk-8u40-b25-linux-x64-10_feb_2015.tar.gz

# Java SE 9
wget https://download.java.net/java/GA/jdk9/9.0.4/binaries/openjdk-9.0.4_linux-x64_bin.tar.gz

# Java SE 10
wget https://download.java.net/java/GA/jdk10/10.0.2/19aef61b38124481863b1413dce1855f/13/openjdk-10.0.2_linux-x64_bin.tar.gz

# Java SE 11
wget https://download.java.net/java/GA/jdk11/9/GPL/openjdk-11.0.2_linux-x64_bin.tar.gz

# Java SE 12
wget https://download.java.net/java/GA/jdk12.0.2/e482c34c86bd4bf8b56c0b35558996b9/10/GPL/openjdk-12.0.2_linux-x64_bin.tar.gz

# Java SE 13
wget https://download.java.net/java/GA/jdk13/5b8a42f3905b406298b72d750b6919f6/33/GPL/openjdk-13_linux-x64_bin.tar.gz


mkdir /usr/lib/jvm


# Extract all downloaded jdk files
tar -xvzf openjdk-7u75-b13-linux-x64-18_dec_2014.tar.gz -C /usr/lib/jvm

tar -xvzf openjdk-8u40-b25-linux-x64-10_feb_2015.tar.gz -C /usr/lib/jvm

tar -xvzf openjdk-9.0.4_linux-x64_bin.tar.gz -C /usr/lib/jvm

tar -xvzf openjdk-10.0.2_linux-x64_bin.tar.gz -C /usr/lib/jvm

tar -xvzf openjdk-11.0.2_linux-x64_bin.tar.gz -C /usr/lib/jvm

tar -xvzf openjdk-12.0.2_linux-x64_bin.tar.gz -C /usr/lib/jvm

tar -xvzf openjdk-13_linux-x64_bin.tar.gz -C /usr/lib/jvm



# Remove downloaded jdk files
rm openjdk*


# Install Java and Java Compiler to Environment
update-alternatives --install /usr/bin/java java /usr/lib/jvm/java-se-7u75-ri/bin/java 1

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/java-se-7u75-ri/bin/javac 1

update-alternatives --install /usr/bin/java java /usr/lib/jvm/java-se-8u40-ri/bin/java 2

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/java-se-8u40-ri/bin/javac 2

update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-9.0.4/bin/java 3

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-9.0.4/bin/javac 3

update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-10.0.2/bin/java 4

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-10.0.2/bin/javac 4

update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-11.0.2/bin/java 5

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-11.0.2/bin/javac 5

update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-12.0.2/bin/java 6

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-12.0.2/bin/javac 6

update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-13/bin/java 7

update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-13/bin/javac 7



# Verify Java and Java Compiler Installation
# check if java command is pointing to correct path in system
update-alternatives --display java
update-alternatives --display javac

# List all environment variables
update-alternatives --get-selections
# or
update-alternatives --get-selections | grep java
# or
update-alternatives --get-selections | grep ^java

Check Java Version

# Verify if Java is running
java -version

# Verify if Java Compiler is running
javac -version

Java – Difference between equals() method and == operator

"==" operator compares 2 objects memory reference. Now, lets have a look at the simple example below:

Example 1:

String str1 = "test";

String str2 = "test";

if (str1 == str2) {
System.out.println("str1 == str2 is TRUE");
} else {
System.out.println("str1 == str2 is FALSE");
}

Output:

str1 == str2 is TRUE

Example 2:

String str1 = new String("test");

String str2 = new String("test");

if (str1 == str2) {
System.out.println("str1 == str2 is TRUE");
} else {
System.out.println("str1 == str2 is FALSE");
}

Output:

str1 == str2 is FALSE

In the code above, Outputs of Example 1 and Example 2 are different. Because, when you create String, JVM searches that literal in String pool, if it matches, same reference will be given to that new String. So, Example 1 output is TRUE.

In Example 2, the output is FALSE. Because, 2 objects refer to different memory location.

Continue reading

Java Method Reference

Method reference is supported in Java 8. A method reference is described using :: (double colon) symbol.

Types of Method Reference
There are four types of method references:

  1. A method reference to a static method.
  2. A method reference to an instance method of an object of a particular type.
  3. A method reference to an instance method of an existing object.
  4. A method reference to a constructor.

Static Method Reference

Notice that below code between System.out and println, the :: operator is used instead of the . operator. And we don't pass arguments to the method reference. So, you can refer to static method defined in the class with interfaces that contain only one abstract method in addition to one or more default or static methods.

Consumer<?> is a functional interface. Lambda expression and Static method references that implement Consumer<String> functional interface are passed to the accept() method to be executed. Actually, Lambda expression  can be replaced with Method reference.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class Program {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("name1", "name2", "name3", "name4");


        //1. way: using Anonymous Inner Class
        Consumer<String> action1 = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };

        names.forEach(action1);

        System.out.println("*******************");

        //2. way: using Lambda Expression
        Consumer<String> action2 = (x) -> System.out.println(x);

        names.forEach(action2);

        System.out.println("*******************");


        //3. way: using Static Method Reference
        Consumer<String> action3 = System.out::println;

        names.forEach(action3);

        System.out.println("*******************");


        //4. way: pass Lambda Expression as argument
        names.forEach((x) -> System.out.println(x));


        System.out.println("*******************");


        //5. way: pass Static Method Reference as argument
        names.forEach(System.out::println);

    }
}

Output:

name1
name2
name3
name4
*******************
name1
name2
name3
name4
*******************
name1
name2
name3
name4
*******************
name1
name2
name3
name4

Continue reading