Variable arguments or varargs methods in java

Java variable arguments was introduced in java 5 and it allows methods to take as many number of arguments you want.

Syntax:

We use three dots (...) also known as ellipsis to define variable arguments.
public  void method (String a,int ... b)
 {
  
 }
There are some points which you need to keep in mind while using varargs methods:
  1. You can have only one variable arguments (ellipsis) in one method
  2. varargs should be last parameter in the method, otherwise method won't compile.

Why to use variable arguments or varargs methods: 

There are two alternatives which can be used which developers used before java 1.5
  1. Method overloading
  2. Passing array to the method
Method overloading may not be good idea because you don't know number of methods you need to overload.You can pass arguments in the array but why don't we can directly use varargs method and let compiler create array for us.

How varargs works internally.

While invoking varargs method, compiler matches argument from left to right, Once fixed number of arguments are matched, rest all arguments are created as array and passed to method.

For example:
Lets say you have method signature as below:
public  void method (String a,int b,int ... c)
 {
  
 }
and you invoke this method as
method("test",1,2,3,4)
then "test" and 1 will be passed as normal parameters and 2,3 and 4 will be passed as array.

Java variable arguments or varargs example:

package org.arpit.java2blog;

public class VarArgsMainJava {

 public static void main(String[] args) {
 
  method("test",1,2,3,4,5);
  anotherMethod(10,20,30,40,50);
 }
 
 public  static void method (String a,int b,int ... c)
 {
  System.out.println("Method arguments are");
  System.out.print(a);
  System.out.print(" "+b);
  for (int i = 0; i < c.length; i++) {
   System.out.print(" "+c[i]);
  }
  System.out.println();
 }
 
 public  static void anotherMethod (int b,int ... c)
 {
  System.out.println("Method arguments are");
  System.out.print(b);
  for (int i = 0; i < c.length; i++) {
   System.out.print(" "+c[i]);
  }
 }

}

When you run above program, you will get below output:
Method arguments are
test 1 2 3 4 5
Method arguments are
10 20 30 40 50

Java String compareTo example

String's compareTo method compares two String lexicographically. Both String get converted to unicode value and then compares.

If you call str1.compareTo(str2)

then if it returns
positive number : str1 is greater than str2
0: str1 is equal to str2
negative number : str1 is smaller than str2

Java String compareTo example

package org.arpit.java2blog;

public class StringCompareToExampleMain {
 public static void main(String[] args) {
  String str1="java2blog";
     String str2="hello";
    String str3="world";
    String str4="java2blog";
    String str5="JAVA2BLOG";
    
    System.out.println("comparing java2blog with hello : "+str1.compareTo(str2));
    System.out.println("comparing hello with world : "+str2.compareTo(str3));
  System.out.println("comparing java2blog with java2blog : "+str1.compareTo(str4));
  System.out.println("comparing java2blog with JAVA2BLOG : "+str1.compareTo(str5));
 }
 
}

When you run above program, you will get below output:
comparing java2blog with hello : 2
comparing hello with world : -15
comparing java2blog with java2blog : 0
comparing java2blog with JAVA2BLOG : 32

How to convert String to Byte array in java

Sometimes, we need to convert String to byte array. We can use getBytes() method of String to do it,

Method syntax:

public byte[] getBytes()

String getBytes Example:

package org.arpit.java2blog;

public class StringBytesExample {
	public static void main(String[] args) {
		String str1 = "java2blog";
		byte[] bytes=str1.getBytes();
		
		System.out.println(str1.length());
		System.out.println(bytes.length);
		System.out.println(bytes.toString());
		
	}
}

When you run above program, you will get below output:
9
9
[B@e1641c0

There is one more overloaded method for getBytes 

Method syntax:
public byte[] getBytes(String charSetName)

It encodes String to specified charset format. You can read about charset from http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html

Lets encode above String in charSet UTF-16LE and UTF-16BE
package org.arpit.java2blog;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class StringBytesExample {
	public static void main(String[] args) {
		String str1 = "java2blog";
		byte[] bytesDef=str1.getBytes();
		byte[] bytesUTFLE = null;
		byte[]  bytesUTFBE = null;
		try {
			bytesUTFLE = str1.getBytes("UTF-16LE");
			bytesUTFBE=str1.getBytes("UTF-16BE");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		System.out.println("Encoding using default charSet");
		for (int i = 0; i < bytesDef.length; i++) {
			System.out.print(bytesDef[i]);
		}
		System.out.println("\n----------------------------------");
		System.out.println("\nEncoding using UTF-16LE charset");
		for (int i = 0; i < bytesUTFLE.length; i++) {
			System.out.print(bytesUTFLE[i]);
		}
		System.out.println("\n----------------------------------");
		System.out.println("\nEncoding using UTF-16BE charset");
		for (int i = 0; i < bytesUTFBE.length; i++) {
			System.out.print(bytesUTFBE[i]);
		}	
	}
}
When you run above program, you will get below output:
Encoding using default charSet
10697118975098108111103
----------------------------------

Encoding using UTF-16LE charset
10609701180970500980108011101030
----------------------------------

Encoding using UTF-16BE charset
01060970118097050098010801110103

log4j xml configuration example

Logging is essential part of programming. It helps developer to track code workflow and fix bugs efficiently. If we get any issue in the code, we check logs for that workflow or functionality.

Log4j is fast , reliable logging framework and can be easily integrated with the code. It is possible to enable logging at run time without using

There are two ways, you can do logging using log4j.
  1. log4j.properties
  2. log4j.xml
In this post, we will see how to configure using log4.xml

1) Create simple maven java project.

2) Put log4j entry in pom.xml .

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>

3) Update maven project to download require jar

Right click on project-> Maven -> update project

4) Create log4j.xml file

This file is main file for log4j configuration. It has information about log levels, log appenders.

Log to console:

If you want to log to console, you need to have following lines in log4j.xml.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
 xmlns:log4j='http://jakarta.apache.org/log4j/'>

 <appender name="console" class="org.apache.log4j.ConsoleAppender">
     <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" 
    value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
     </layout>
 </appender>

 <root>
  <level value="DEBUG" />
  <appender-ref ref="console" />
 </root>

</log4j:configuration>

Log to file :

If you want to log to console, you need to have following lines in log4j.xml and also you need to provide log file name too.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
 xmlns:log4j='http://jakarta.apache.org/log4j/'>

 <appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="10MB" />
    <param name="maxBackupIndex" value="5" />
    <!-- For Tomcat -->
    <param name="file" value="appLogs.log" />
    <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" 
   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
 </appender>

 <root>
  <level value="DEBUG" />
  <appender-ref ref="file" />
 </root>

</log4j:configuration>

Log to console and file both :

If you want to log on both to console and file, you can use below code:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

 <appender name="console" class="org.apache.log4j.ConsoleAppender">
     <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" 
   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
     </layout>
 </appender>

 <appender name="file" class="org.apache.log4j.RollingFileAppender">
     <param name="append" value="false" />
     <param name="maxFileSize" value="10MB" />
     <param name="maxBackupIndex" value="10" />
     <param name="file" value="appLogs.log" />
     <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" 
   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
     </layout>
 </appender>

 <root>
  <level value="DEBUG" />
  <appender-ref ref="console" />
  <appender-ref ref="file" />
 </root>

</log4j:configuration>

5) Sample class for Logger 

Create a class called "LoggingMain.java" in src/main/java in package org.arpit.java2blog
package org.arpit.java2blog;

import org.apache.log4j.xml.DOMConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class LoggingMain {

  private static final Logger logger = LogManager.getLogger(LoggingMain.class);
 public static void main(String[] args) {
 
  DOMConfigurator.configure("log4j.xml");
  logger.info("Hello world");
  logger.info("we are in logger info mode");

 }

}

6) Run program:

When you run above program , you will get below output to console and file(appLogs.log)
0 [main] INFO org.arpit.java2blog.LoggingMain  - Hellow world
1 [main] INFO org.arpit.java2blog.LoggingMain  - we are in logger info mode
Bingo!! we have successfully configured log4j using xml file in maven project.

Difference between PATH and CLASSPATH in java

In this post , we will see differences between PATH and CLASSPATH in java.

Let me provide simple definition about PATH and CLASSPATH.

PATH :

This is environment variable which operating system uses to locate executable such as javac, java, javah,jar etc.
For example: bin directory of jdk has all the executable such as javac,java so we can set upto bin folder.
"C:\Program Files\Java\jdk1.7.1\bin"

CLASSPATH:

This is environment variable which java virtual machine (JVM) uses to locate all classes which is used by the program.
For example: jre/lib/rt.jar has all java classes and you also need to include jar files or class file which is being used by program.
"C:\Program Files\Java\jre1.7.1\jre\lib\rt.jar"

PATH vs CLASSPATH:

Parameter
Path
classpath
Locate
It allows operating system to locate executable such as javac, java

It allows classloader to locate all .class file used by program
Overriding
You can not override path variable with java setting

You can override classpath by using -cp with java,javac or class-path in manifest file.
Inclusion
You need to include bin folder of jdk (For example jdk1.7.1/bin)
You need to include all the classes which is required by program
Used by
Operating system
java classloaders

log4j properties file example

Logging is essential part of programming. It helps developer to track code workflow and fix bugs efficiently. If we get any issue in the code, we check logs for that workflow or functionality.

Log4j is fast , reliable logging framework and can be easily integrated with the code. It is possible to enable logging at run time without using

There are two ways, you can do logging using log4j.
  1. log4j.properties
  2. log4j.xml
In this post, we will see how to configure using log4.properties

1) Create simple maven java project.

2) Put log4j entry in pom.xml .

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>

3) Update maven project to download require jar

Right click on project-> Maven -> update project

4) Create log4j.properties file

This file is main file for log4j configuration. It has information about log levels, log appenders.

Log to console:

If you want to log to console, you need to have following lines in log4j.properties.
log4j.rootLogger=DEBUG, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

Log to file :

If you want to log to console, you need to have following lines in log4j.properties and also you need to provide log file name too.
log4j.rootLogger=DEBUG, console
log4j.rootLogger=DEBUG,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.file.File=applicationLogs.log

Log to console and file both :

If you want to log on both to console and file, you can use below code:
l
log4j.rootLogger=DEBUG, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.file.File=applicationLogs.log

5) Sample class for Logger 

Create a class called "LoggingMain.java" in src/main/java in package org.arpit.java2blog
package org.arpit.java2blog;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class LoggingMain {

  private static final Logger logger = LogManager.getLogger(LoggingMain.class);
 public static void main(String[] args) {
 
  PropertyConfigurator.configure("log4j.properties");
  logger.info("Hello world");
  logger.info("we are in logger info mode");

 }

}

6) Run program:

When you run above program , you will get below output to console and file(applicationLogs.log)
0 [main] INFO org.arpit.java2blog.LoggingMain  - Hello world
1 [main] INFO org.arpit.java2blog.LoggingMain  - we are in logger info mode
Bingo!! we have successfully configured log4j using properties file in maven project.

jQuery Keypress enter example

In this post, we will see how to detect if enter key is pressed or not in jQuery.

To capture enter keypress, we will bind dom element with keypress event and if ascii value is 13, then enter key is pressed.

So basically code will look something like this.
$('#textBox').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }
});
If you want to catch keypress event in whole web page, you can simply use:
$('#document').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }
});

JQuery keypress enter example:

<html>
<head>
 
<script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
 
</head>
<body>
  <h1>Detect if Enter key is pressed</h1>
 
<label>TextBox : </label>
<input id="textbox" type="text" size="40" />
 
<script type="text/javascript">
 
$('#textbox').keypress(function(event){
 
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }

});

</script>
</body>
</html>

Output:


Live demo: jQuery keypress enter example

Java transient keyword with example

Transient variable is the variable whose value is not serialized during serialization. You will get default value for these variable when you deserialize it.

Lets say you have Country class and you don't want to Serialize population attribute as it will change with time, so you can declare population attribute as transient and it won't serialized any more. 
Create a classed called Country.java as below:
package org.arpit.java2blog;

import java.io.Serializable;

public class Country implements Serializable {  
  
 String name;  
 transient long population;  
   
 
 public Country() {
 super();
}
public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }
    
}  

Create serializationMain.java as below:
package org.arpit.java2blog;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  Country india = new Country();
 india.setName("India");
 india.setPopulation(100000);
  try
  {
   FileOutputStream fileOut = new FileOutputStream("country.ser");
   ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
   outStream.writeObject(india);
   outStream.close();
   fileOut.close();
  }catch(IOException i)
  {
   i.printStackTrace();
  }
  
  System.out.println("serialized");
 }
}
When you run above program, you will get below output:
serialized

Now Create a classed called DeserializeMain.java as below:
package org.arpit.java2blog;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeMain {
 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
  
  Country india = null;
       try
       {
          FileInputStream fileIn =new FileInputStream("country.ser");
          ObjectInputStream in = new ObjectInputStream(fileIn);
          india = (Country) in.readObject();
          in.close();
          fileIn.close();
       }catch(IOException i)
       {
          i.printStackTrace();
          return;
       }catch(ClassNotFoundException c)
       {
          System.out.println("Country class not found");
          c.printStackTrace();
          return;
       }
       System.out.println("Deserialized Country...");
       System.out.println("Country Name : " + india.getName());
       System.out.println("Population : " + india.getPopulation());
       
 }
}
When you run above program, you will get below output:
Deserialized Country...
Country Name : India
Population : 0
As you can see in above example, we have declared population as trasient,so after deserialization, its value became 0 (Default value for long)

Java static import example

If any class which is not in same package, we need to import it. If we import that class we can directly access static variables and methods with the class name.

If you use static import,  you do not need to use class name any more.

Lets understand with the help of example

Without using static import :

package org.arpit.java2blog;

public class StaticImportMain {

	public static void main(String[] args) {
		System.out.println("With Static import");
		System.out.println("Value of PI : "+Math.PI);
	}

}

With using static import :

package org.arpit.java2blog;
import static java.lang.System.out;
import static java.lang.Math.PI;

public class StaticImportMain {

	public static void main(String[] args) {
		out.println("With Static import");
		out.println("Value of PI : "+PI);
	}

}
As you can see, we have directly used out.println and PI without using class name because  we have used static import here. 

Advantages:

If you have lot of static variables, you have to write less code.

Disadvantages:

It is very hard to read and unmaintainable.



ArrayList in java with Example

ArrayList is most common Collections data structure along with HashMap which we use very often.

Why to choose ArrayList vs Array:

  1. Array is fixed length data structure If array is full , you can not add element to it, where as ArrayList can dynamically grow and shrink as per our need.
  2. You can use generics with ArrayList but not with Array 
  3. ArrayList have predefined methods which can be used to perform operations.

Some important points about ArrayList are:

  1. ArrayList is implementation of list interface.
  2. ArrayList is not synchonized(so not thread safe)
  3. ArrayList is implemented using array as internal data structure.It can be dynamically resized .
  4. ArrayList increases half of its size when its size is increased.

Java ArrayList Example: 

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class JavaArrayListExampleMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("Amit");
  
  System.out.println("Employee list:");

  for (String empName : employeeNameList) {

   System.out.println(empName);

  }

 }
}
When you run above program, you will get below output:
Employee list:
John
Ankit
Rohan
Amit

Iterate over list : 

We have used foreach loop to iterate over list in above example: There are many ways to iterate over list. Some of them are:
  1. Using for loop
  2. Using Iterator
Iterator example:
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class JavaArrayListExampleMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("Amit");
  
  System.out.println("Employee list:");

  Iterator<string> iter = employeeNameList.iterator();
  while (iter.hasNext()) {
   System.out.println(iter.next());
  }


 }
}
When you run above program, you will get below output:
Employee list:
John
Ankit
Rohan
Amit

Methods of ArrayList: 

I am explaining below method in context of String list, but you can put any object in the list.

add( Object o): This method adds an object o to end of the arraylist.
employeeNameList.add("Amit")
This statement would add a string Amit in the ArrayList at last position.

add(int index, Object o): This adds the object o to the arraylist at the specified index.
employeeNameList.add(5,"Ankit")
It will add the string Ankit to the 5th index (6rd position as the array list starts with index 0) of ArrayList.

Object get(int index): It returns the object of list which is present at the specified index.
String str= employeeNameList.get(2);
It is used to get element from ArrayList and this is most used method. Here we are getting element from ArrayList and assigning it to String object

remove(Object o): Removes the object o from the ArrayList.
employeeNameList.remove("Arpit");
This code will remove the string “Arpit” from the ArrayList.

remove(int index): Removes element which is present at specified index
employeeNameList.remove(3);
It would remove the element of index 3 (4th element of the list as list always starts with 0).

set(int index, Object o): It is mainly used for updating an element. It replaces the element present at the specified index with the object o.
employeeNameList.set(2, "Ankit");
It would replace element which is present at index 2(3rd element in arrayList)with the value Tom.

int indexOf(Object o): It is used to find index of object o. If object is not present, this method returns -1
int index = employeeNameList.indexOf("Ankit");
This would give the index (position) of the string Ankit in employeeNameList.

int size(): It gives the size of the ArrayList
int sizeOfArrayList = employeeNameList.size();
boolean contains(Object o): 
It checks whether the given object o is present in the ArrayList or not. If not present, it returns false
employeeNameList.contains("Amit");
It would return true if the string “Amit” is present in the list else it will return false

clear():
employeeNameList.clear()
It will remove all the object of ArrayList, so above statement will remove all String object from employeeNameList

addAll(Collection c)

If you want to merge two ArrayList, you can use this method.

Example:
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class JavaArrayListExampleMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("Amit");
  
  ArrayList<String> otherList = new ArrayList<String>();
  
  otherList.add("abc");
  otherList.add("xyz");
  
  // Adding otherList to employeeList
  employeeNameList.addAll(otherList);
  
  System.out.println("Employee list:");

  for (String empName : employeeNameList) {

   System.out.println(empName);

  }

 }
}

When you run above program, you will get below output:
Employee list:
John
Ankit
Rohan
Amit
abc
xyz

removeAll(Collection c)

If you want to remove list of elements which is present in other list, you can use this method.

Example:
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class JavaArrayListExampleMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("Amit");
  
  ArrayList<String> otherList = new ArrayList<String>();
  
  otherList.add("John");
  otherList.add("Rohan");
  
  // removing otherList's element from ArrayList
  employeeNameList.removeAll(otherList);
  
  System.out.println("Employee list:");

  for (String empName : employeeNameList) {

   System.out.println(empName);

  }

 }
}

When you run above program, you will get below output:
Employee list:
Ankit
Amit

retainAll(Collection)

If you want to retain only those elements which are present in Collection, you can use this method.

Example:

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class JavaArrayListExampleMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("Amit");
  
  ArrayList<String> otherList = new ArrayList<String>();
  
  otherList.add("John");
  otherList.add("Rohan");
  
  // removing otherList's element from ArrayList
  employeeNameList.retainAll(otherList);
  
  System.out.println("Employee list:");

  for (String empName : employeeNameList) {

   System.out.println(empName);

  }

 }
}

When you run above program, you will get below output:
Employee list:
John
Rohan


How to remove all white spaces from String in java

In this post, we will see how to remove all white spaces from String in java.

There are multiple ways to remove spaces from String.
  1. Using ReplaceAll
  2. Using Iteration

Using ReplaceAll :

You can simply call ReplaceAll method to remove white spaces as shown below.
String result1 = str.replaceAll("\\s", "");

Using iteration :

You can iterate over String using charAt and check if Character is whitespace or not.

Java Program to remove all white spaces from String

package org.arpit.java2blog;

public class StringRemoveSpacesAllMain {

 public static void main(String[] args) {
  String str = "     Hello world from   java2blog.com  ";
  System.out.println("------------------------------");
  System.out.println("Using replaceAll");
  System.out.println("------------------------------");

                // Using replaceAll
  String result1 = str.replaceAll("\\s", "");
  System.out.println(result1);

  String result2 = "";
  // Using iteration
  System.out.println("\n------------------------------");
  System.out.println("Using Iteration");
  System.out.println("------------------------------");
  for (int i = 0; i < str.length(); i++) {
   if (!Character.isWhitespace(str.charAt(i))) {
    result2 += str.charAt(i);
   }
  }
  System.out.println(result2);
 }
}

When you run above program, you will get below output:
------------------------------
Using replaceAll
------------------------------
Helloworldfromjava2blog.com

------------------------------
Using Iteration
------------------------------
Helloworldfromjava2blog.com

How to check if one String is rotation of another String in java

In this post, we will see how to check if one String is rotation of another or not.

For example:
java2blog and blogjava2 are rotation of each other.

java2blog and avablog2j are not rotation of each other.

Approach:

Lets say you need to check whether str1 and str2 is rotation of one another or not.
  1. Create a new String with str3= str1 + str1
  2. Check if str3 contains str2 or not.
  3. if str3 contains str2 then str2 is rotation of str1 else it is not
Java Program to check if one String is rotation of another.

package org.arpit.java2blog;

public class StringRotationMain {

 public static void main(String[] args) {
  
  System.out.println("java2blog and blogjava2 are rotation of each other : "+isRotation("java2blog","blogjava2"));
  System.out.println("java2blog and avablog2j are rotation of each other : "+isRotation("java2blog","avablog2j"));

 }
 
 public static boolean isRotation(String str,String rotation)
 {
   String str2=str+str;
  
   if(str2.contains(rotation))
   {
    return true;
   }
   return false;
  
 }

}

When you run above program, you will get below output:
java2blog and blogjava2 are rotation of each other : true
java2blog and avablog2j are rotation of each other : false


Can we call run() method directly to start a new thread

No, you can not directly call run method to start a thread. You need to call start method to create a new thread.

If you call run method directly , it won't create a new thread and it will be in same stack as main.

Lets understand with the help of example:

package org.arpit.java2blog;

class CustomThread extends Thread {

 public void run() {
  for (int i = 0; i < 5; i++) {
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
   System.out.println("Thread is running :"+i);
  }
  
 }

}

public class StartThreadAgainMain {

 public static void main(String[] args) {
  CustomThread ct1 = new CustomThread();
  CustomThread ct2 = new CustomThread();
  ct1.run();
  ct2.run();

 }

}


When you run above program , you will get below output:
Thread is running :0
Thread is running :1
Thread is running :2
Thread is running :3
Thread is running :4
Thread is running :0
Thread is running :1
Thread is running :2
Thread is running :3
Thread is running :4

As you can see when we are directly calling run method, it is not creating new threads.

If you use start instead of run in above example:


package org.arpit.java2blog;

class CustomThread extends Thread {

 public void run() {
  for (int i = 0; i < 5; i++) {
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
   System.out.println("Thread is running :"+i);
  }
  
 }

}

public class StartThreadAgainMain {

 public static void main(String[] args) {
  CustomThread ct1 = new CustomThread();
  CustomThread ct2 = new CustomThread();
  ct1.start();
  ct2.start();

 }

}

When you run above program , you will get below output:
Thread is running :0
Thread is running :0
Thread is running :1
Thread is running :1
Thread is running :2
Thread is running :2
Thread is running :3
Thread is running :3
Thread is running :4
Thread is running :4
You can not directly call run method to create a thread, you need to call start method to create a new thread.