ArrayList's indexOf method is used to find out first index of object in arraylist.
indexOf method takes object as argument and returns first occurrence of specified element.

Methods:

public int indexOf(Object o)
returns index of first occurrence of element in the ArrayList.
indexOf method return -1 if object is not present in the ArrayList

ArrayList indexOf Example:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;
class IndexOfArrayListMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList employeeNameList = new ArrayList();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("Amit");
  
  System.out.println("Index of Ankit: "+employeeNameList.indexOf("Ankit"));
  System.out.println("*******************************");
  
  System.out.println("Index of John: "+employeeNameList.indexOf("John"));
  System.out.println("*******************************");
 // Arpit is not present in the list
  System.out.println("Index of Arpit: "+employeeNameList.indexOf("Arpit"));
 }
}
When you run above program, you will get below output
Index of Ankit: 1
*******************************
Index of John: 0
*******************************
Index of Arpit: -1


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

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

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

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.

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

You can go through top 50 core java interview questions for more such questions.

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

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)

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 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


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

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


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.

You can go through core java interview questions for beginners and experienced for more such questions. 

No, Once you have started a thread, it can not be started again. If you try to start thread again , it will throw IllegalThreadStateException

Lets understand with the help of example:
package org.arpit.java2blog;

class FirstThread extends Thread {

 public void run() {
  System.out.println("Thread is running");
 }

}

public class StartThreadAgainMain {

 public static void main(String[] args) {
  FirstThread ft = new FirstThread();
  ft.start();
  ft.start();

 }

}

When you run above program , you will get below output:
Thread is runningException in thread "main" 
java.lang.IllegalThreadStateException
 at java.lang.Thread.start(Thread.java:705)
 at org.arpit.java2blog.StartThreadAgainMain.main(StartThreadAgainMain.java:16)

As you can see when we started thread twice, it threw IllegalThreadStateException.
If you try to start thread again , it will throw IllegalThreadStateException

You can go through core java interview questions for beginners and experienced for more such questions.

String's compareToIgnoreCase method is similar to compareTo method. Only difference with compareTo is that it ignores cases.It also compares Strings lexigraphically. Both String get converted to unicode value and then compares.

If you call str1. compareToIgnoreCase(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

package org.arpit.java2blog;

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

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

String's equalsIgnoreCase method is similar to equals method but it ignores case. So if Strings have different cases, then also it will considered as equals.

For example:
String str1="Java2blog.com"
String str2="JAVA2BLOG.COM"

str1.equalsIgnoreCase(str2) will return true.

Method Signature:

public boolean equalsIgnoreCase(Object anObject)

String equalsIgnoreCase Example:

package org.arpit.java2blog;

public class StringEqualsExamplesMain {
 public static void main(String[] args) {
  String str1 = "Hello world from java2blog.com";
  String str2 = new String("Hello world from java2blog.com");
  String str3 = "Hello world from JAVA2BLOG.COM";

  if (str1.equalsIgnoreCase(str2)) {
   System.out.println("1st and 2nd Strings are equal");
  } 
  else {
   System.out.println("1st and 2nd Strings are not equal");
  }

  if (str1.equalsIgnoreCase(str3)) {
   System.out.println("1st and 3rd Strings are equal");
  } 
  else {
   System.out.println("1st and 3rd Strings are not equal");
  }
 }
}

When you run above program, you will get below output:
1st and 2nd Strings are equal
1st and 3rd Strings are equal

String's equals method compares String with specified object. It checks if both have same character sequence. It is generally used to compare two Strings.

Method Signature:

public boolean equals(Object anObject)

String equals Example:

package org.arpit.java2blog;

public class StringEqualsExamplesMain {
 public static void main(String[] args) {
  String str1 = "Hello world from java2blog.com";
  String str2 = new String("Hello world from java2blog.com");
  String str3 = "Hello world from JAVA2BLOG.COM";

  if (str1.equals(str2)) {
   System.out.println("1st and 2nd Strings are equal");
  } 
  else {
   System.out.println("1st and 2nd Strings are not equal");
  }

  if (str1.equals(str3)) {
   System.out.println("1st and 3rd Strings are equal");
  } 
  else {
   System.out.println("1st and 3rd Strings are not equal");
  }
 }
}


When you run above program, you will get below output:
1st and 2nd Strings are equal
1st and 3rd Strings are not equal

String's contentEquals method is used to compare String with StringBuffer. It returns boolean datatype.

Method syntax:

public boolean contentEquals(StringBuffer sb)

String contentEquals Example:

package org.arpit.java2blog;

public class StringContentEqualsExample {
 public static void main(String[] args) {
  String str1 = "java2blog";
  String str2="Hello world from java2blog";
  String str3="JAVA2BLOG";
  
  StringBuffer sb=new StringBuffer("java2blog");
  
  System.out.println(str1.contentEquals(sb));
  System.out.println(str2.contentEquals(sb));
  System.out.println(str3.contentEquals(sb));
  
 }
}


When you run above program, you will get below output:
true
false
false
Please note that contentEquals method is case sensitive as you can see in above example

String's endWith method checks if String ends with specific suffix. It returns boolean datatype.

Method syntax:

public boolean endsWith(String suffix)

String endsWith Example:

package org.arpit.java2blog;

public class StringEndsWithExample {

 public static void main(String[] args) {
  String str = "java2blog";

  if (str.endsWith("blog")) {
   System.out.println("String ends with blog");
  } 
  else {
   System.out.println("String does not end with blog");
  }

  if (str.endsWith("BLOG")) {
   System.out.println("String ends with BLOG");
  } 
  else {
   System.out.println("String does not end with BLOG");
  }
 }

}

When you run above program, you will get below output:
String ends with blog
String does not end with BLOG
Please note that endsWith method is case sensitive as you can see in above example

String's startsWith method checks if String starts with specific prefix. It returns boolean datatype.

Method Signature:

public boolean startsWith(String prefix)

String startsWith Example:

package org.arpit.java2blog;

public class StringStartsWithExample {

 public static void main(String[] args) {
  String str = "java2blog";

  if (str.startsWith("java")) {
   System.out.println("String starts with java");
  } 
  else {
   System.out.println("String does not start with java");
  }

  if (str.startsWith("JAVA")) {
   System.out.println("String starts with JAVA");
  } 
  else {
   System.out.println("String does not start with JAVA");
  }
 }

}

When you run above program, you will get below output:
String starts with java
String does not start with JAVA

Please note that startsWith method is case sensitive as you can see in above example

String's charAt method returns char value present at specified index. String is nothing but Sequence of char values and it starts with index 0.

Method Signature:

public char charAt(int index)

String charAt Example:

package org.arpit.java2blog;

public class StringCharAtMain {

  /*
   * @Author : Arpit Mandliya
   */
 public static void main(String args[])
 {
  String str="java2blog";
  
  System.out.println("char at index 5 :"+str.charAt(5));
  System.out.println("char at index 7 :"+str.charAt(7));
 }
}


When you run above program, you will get below output:
char at index 5 :b
char at index 7 :o

String's trim method is used to remove leading and trailing space. Sometimes, you get extra leading or trailing space and your program does not work as expected. It returns String object after removing leading and trailing spaces.
String's trim method does not remove middle spaces.

String trim example:

package org.arpit.java2blog;

public class StringTrimExample {

 public static void main(String[] args) {
  String str = "     Hello world from    ";

  //without trim()
  System.out.println("Without trim");
  System.out.println("----------------------");
  System.out.println(str+"java2blog.com");
  System.out.println("----------------------");
  // with trim()
  System.out.println("\nWith trim");
  System.out.println("----------------------");
  System.out.println(str.trim()+"java2blog.com");
 
 }
}

When you run above program, you will get below output:
Without trim
----------------------
     Hello world from    java2blog.com
----------------------

With trim
----------------------
Hello world fromjava2blog.com


In this post, we will see how to check if two Strings are Anagrams in java.

Anagrams means if two String have same characters but in different order.
For example:  Angel and Angel are anagrams

There are many ways to check if Strings are anagrams. Some of them are:
  1. Using String methods
  2. Using array.sort

Using String methods:

Approach :
  1. If index of any character is -1, then two strings are not anagrams
  2. If index of character is not equal to -1, then remove the character from the String.
  3. If you get empty String in the end, then two Strings are anagrams of each other.
package org.arpit.java2blog;

public class StringAnagramMain {

 public static void main(String[] args) {
  
  String word="java2blog";
  String anagram="aj2vabgol";
  
  System.out.println("java2blog and aj2vabgol are anagrams :"+ isAnagramUsingStringMethods(word, anagram));

 }
 
 public static boolean isAnagramUsingStringMethods(String word,String anagram)
 {
  if(word.length()!=anagram.length())
   return false;
  
  for (int i = 0; i < word.length(); i++) {
   char c=word.charAt(i);
   int index=anagram.indexOf(c);
   // If index of any character is -1, then two strings are not anagrams
   // If index of character is not equal to -1, then remove the chacter from the String
   if(index !=-1)
   {
    anagram=anagram.substring(0,index)+anagram.substring(index+1,anagram.length());
   }
   else
    return false;
  }
  return anagram.isEmpty();
 }

}

When you run above program, you will get below output:
java2blog and aj2vabgol are anagrams :true

Using Array.sort

package org.arpit.java2blog;

import java.util.Arrays;

public class StringAnagramMain {

 public static void main(String[] args) {
  
  String word="java2blog";
  String anagram="aj2vabgol";
  
  System.out.println("java2blog and aj2vabgol are anagrams :"+ isAnagramUsingArraySort(word, anagram));

 }
 
 
 public static boolean isAnagramUsingArraySort(String word,String anagram)
 {
  
  String sortedWord=sortChars(word);
  String sortedAnagram=sortChars(anagram);
  
  return sortedWord.equals(sortedAnagram) ;
 }
 
 public static String sortChars(String word)
 {
  char[] wordArr=word.toLowerCase().toCharArray();
  Arrays.sort(wordArr);
  return String.valueOf(wordArr);
 }
}

When you run above program, you will get below output:
java2blog and aj2vabgol are anagrams :true

Other String Programs:

    How to reverse String in java How to check if two Strings are angrams Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String Why String is immutable in java Find duplicate characters in String

String's regionMatches is used to compare substring of one string to substring of another.Here region may be refer to substring of String, so we are comparing regions of one string with another.

Method Syntax: 

 There are two overloaded version of regionMatches:
 // Case sensitive
public boolean regionMatches(int toffset, String other, int ooffset, int len):

// It has extra option to ignore the case
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

Parameters: 

ignoreCase: It is boolean field to indicate whether to ignore case or not.
toffset : It is start index of sub String of String on which this method is being called.
other: It is other String by which this String will compare.
ooffset: It is start index of substring of other argument String
len : Number of characters to compare

Lets understand with the example:

You have two Strings and you want to match String java in both str1 and str2.
// 1st
String str1= "Hello world from java2blog.com";
//2nd
String str2= "Core java programming tutorials";
str1.regionMatches(17, str2, 5, 4) will do it. This expression will return true.

How?

17 is starting index of String java in str1.
str2 is our 2nd String
5 is starting index for String java in str2
4 is number of characters in String java

String regionMatches example :

package org.arpit.java2blog;

public class StringRegionMatchesExample {

 public static void main(String[] args) {
  // 1st
  String str1= "Hello world from java2blog.com";
  //2nd
  String str2= "Core java programming tutorials";
  // 3rd
  String str3= "JAVA PROGRAMMING TUTORIALS";
  
  System.out.println("Comparing 1st and 2nd (java in both String): "+ str1.regionMatches(17, str2, 5, 4));
  
  // Ignoring case
  System.out.println("Comparing 2nd and 3nd (programming in both string): "+ str2.regionMatches(true,10, str3, 5, 4));
 }
}

When you run above program, you will get below output:
Comparing 1st and 2nd (java in both String): true
Comparing 2nd and 3nd (programming in both string): true

String's isEmpty method checks if length of string is 0 or not. It returns true if length of String is 0 else return false.

Method Signature:

public boolean isEmpty()

String isEmpty Example:

package org.arpit.java2blog;

public class StringIsEmptyExample {

 /*
  * @Author : Arpit Mandliya
  */
 public static void main(String[] args)
 {
  String str1="";
  String str2="java2blog";
  String str3=null;
  
  System.out.println("str1 isEmpty: "+str1.isEmpty() );
  System.out.println("str2 isEmpty: "+str2.isEmpty() );
  // str3.isEmpty will throw NullPointerException
  //System.out.println("str3 isEmpty: "+str3.isEmpty() );
 }
}

When you run above program, you will get below output:
str1 isEmpty: true
str2 isEmpty: false

String's length method is used to calculate length of String. It returns number of character in the String.

Method Signature:

public int length()

String length Example:

package org.arpit.java2blog;

public class StringLengthExample {
 /*
  * @Author: Arpit Mandliya
  */
 public static void main(String[] args) {

  // 1st
  String str1 = "Hello world from java2blog.com";
  // 2nd
  String str2 = "Core java programming tutorials";
  // 3rd
  String str3 = "JAVA PROGRAMMING TUTORIALS";
  //4th
  String str4="";
  
  System.out.println("str1's length : "+str1.length());
  System.out.println("str2's length : "+str2.length());
  System.out.println("str3's length : "+str3.length());
  System.out.println("str4's length : "+str4.length());
 }

}
When you run above program, you will get below output:
str1's length : 30
str2's length : 31
str3's length : 26
str4's length : 0

In this post, we will see how to find duplicate Characters in a String.

Approach:

  1. Create a HashMap and character of String will be inserted as key and its count as value.
  2. If Hashamap already contains char,increase its count by 1, else put char in HashMap
  3. If value of Char is more than 1, that means it is duplicate character in that String

Java Program to find duplicate Characters in a String

package org.arpit.java2blog;

import java.util.HashMap;
import java.util.Set;

public class StringFindDuplicatesMain {

 public static void main(String[] args) {
  String str = "java2blog.com ";
  HashMap charCountMap = new HashMap();
  for (int i = 0; i < str.length(); i++) {
   char c = str.charAt(i);

   if (charCountMap.containsKey(c)) {
    charCountMap.put(c, charCountMap.get(c) + 1);
   } else {
    charCountMap.put(c, 1);
   }

  }
  for (Character c : charCountMap.keySet()) {
   if (charCountMap.get(c) > 1)
    System.out.println("duplicate character : " + c + " ====== " + " count : " + charCountMap.get(c));

  }

 }

}


When you run above program, you will get below output:
duplicate character : a ======  count : 2
duplicate character : o ======  count : 2

Other String Programs :

    How to reverse String in java How to check if two Strings are angrams Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String Why String is immutable in java Find duplicate characters in String

String's join method can be used to join various String by delimiter. It is introduced in java 8.

For example: We need to join various Strings by ",". You can use join method as
String.join(",","java","blog","tutorials");
// Output
"java,blog,tutorial"
There are two overloaded variants of String's join method:
public static String join(CharSequence delimiter, CharSequence... elements)  
and  
public static String join(CharSequence delimiter, Iterable elements)  

String join example:

package org.arpit.java2blog;

public class StringJoinExample {

 public static void main(String[] args) {
  
  System.out.println(String.join(",","java","blog","tutorials"));
  System.out.println(String.join("-","java","blog","tutorials"));
 }

}

When you run above program, you will get below output:
java,blog,tutorials
java-blog-tutorials

String class is immutable in java. If you take dictionary meaning of immutable, it means unable to be changed or unchanging over time, so String is unchangeable or unmodifiable in java.

Let's understand with example.
String str1="Hello";
str1.concat("java2blog");
System.out.println(str1);
  
// Output will be 
Hello
As you can see, value of str1 did not change. It created another String object with value "Hellojava2blog" but did not change String str1
This explains that String is immutable in nature.

Now let's understand what are potential reasons to make string immutable in java

String pool :

If you simply assign a Value to String using double quotes, it is stored in area called string literal pool and one string can be referenced by many reference variables and if String Is mutable,  then it will affect all reference variables.

Thread safe :

Immutable objects are by default thread safe,  so you don't need to put synchronisation for it and String instance can be safely shared among multiple threads.

Security :

If String is not immutable then it may cause multiple security issue.
For example, while connecting to database,  you provide username, password, Port and host name etc as String,  if String is mutable, any hacker can change the reference value and cause security threats to application.

Cache hash value :

When you use String as key in HashMap or HashSet or any other collection,  you can cache it's hash value.  As String is immutable in nature, you don't need to calculate each time as it will be constant. It greatly improve performance for this hash based collections.

Class loading :

String is used as class loading mechanism.  It is passed as a parameter.  If String is mutable,  it is a security threat as any hacker could have changed it.

String's lastIndexOf method is used to find out last index of any character or sub string.

lastIndexOf method can take char or string as argument and also you can provide fromIndex also.

Methods:

public int lastIndexOf(int ch)
returns index of last occurrence of character within String

public int lastIndexOf(int ch,int fromIndex)
returns index of last occurrence of character within String, going backward from specific index "fromIndex"

public int lastIndexOf(String)
returns index of last occurrence of substring within String

public int lastIndexOf(int ch,int fromIndex)
returns index of last occurrence of substring within String, going backward from specific index "fromIndex"

All lastIndexOf methods return -1 if char or substring is not present in the String

String indexOf Example:

package org.arpit.java2blog;

public class StringLastIndexOfExample {
 /*
  * @ Author : Arpit Mandliya
  */
 public static void main(String args[]) {
  
  String str="Hello world from java2blog";
  // Using lastIndexOf method with character
  System.out.println("---------------------------------------------------");
  System.out.println("Using lastIndexOf method with character");
  System.out.println("---------------------------------------------------");
  
  System.out.println("Last index of character l in \"Hello world from java2blog\" is : "+str.lastIndexOf('l'));
  System.out.println();
  
  String str1="from";
  System.out.println("---------------------------------------------------");
  System.out.println("Using lastIndexOf method with fromIndex with character");
  System.out.println("---------------------------------------------------");
  System.out.println("Last index of character o from index 6 in \"Hello world from java2blog\" is : "+str.lastIndexOf('o',6));
  System.out.println();
  
  // Using lastIndexOf method with String
  System.out.println("---------------------------------------------------");
  System.out.println("Using lastIndexOf method with String");
  System.out.println("---------------------------------------------------");
  
  System.out.println("Last index of String \"from\" in \"Hello world from java2blog\" is : "+str.lastIndexOf(str1));
  System.out.println();
  
  String howDo="How do you do";
  System.out.println("---------------------------------------------------");
  System.out.println("Using lastIndexOf method with fromIndex with String");
  System.out.println("---------------------------------------------------");
  System.out.println("Last index of String \"do\" from index 9 in \"How do you do\" is : "+howDo.lastIndexOf("do",9));
  System.out.println();
  
  System.out.println("---------------------------------------------------");
  System.out.println("If String or char is not available");
  System.out.println("---------------------------------------------------");
  System.out.println("Last index of \"from\" in \"How do you do\" is : "+howDo.lastIndexOf("from"));
  
  
 }
}

When you run above program, you will get below output:
--------------------
---------------------------------------------------
Using lastIndexOf method with character
---------------------------------------------------
Last index of character l in "Hello world from java2blog" is : 23

---------------------------------------------------
Using lastIndexOf method with fromIndex with character
---------------------------------------------------
Last index of character o from index 6 in "Hello world from java2blog" is : 4

---------------------------------------------------
Using lastIndexOf method with String
---------------------------------------------------
Last index of String "from" in "Hello world from java2blog" is : 12

---------------------------------------------------
Using lastIndexOf method with fromIndex with String
---------------------------------------------------
Last index of String "do" from index 9 in "How do you do" is : 4

---------------------------------------------------
If String or char is not available
---------------------------------------------------
Last index of "from" in "How do you do" is : -1


String's indexOf method is used to find out index of any character or sub string.

indexOf method can take char or string as argument and also you can provide fromIndex(Index after which you want to use indexOf method) also.

Methods:

public int indexOf(int ch)
returns index of first occurrence of character within String

public int indexOf(int ch,int fromIndex)
returns index of first occurrence of character within String, starting from specific index "fromIndex"

public int indexOf(String)
returns index of first occurrence of substring within String

public int indexOf(int ch,int fromIndex)
returns index of first occurrence of substring within String, starting from specific index "fromIndex"

All indexOf methods return -1 if char or substring is not present in the String

String indexOf Example:

package org.arpit.java2blog;

public class StringIndexOfExample {
 /*
  * @ Author : Arpit Mandliya
  */
 public static void main(String args[]) {
  
  String str="Hello world from java2blog";
  // Using index of method with character
  System.out.println("---------------------------------------------------");
  System.out.println("Using indexOf method with character");
  System.out.println("---------------------------------------------------");
  
  System.out.println("Index of character b in \"Hello world from java2blog\" is : "+str.indexOf('b'));
  System.out.println();
  
  String str1="from";
  System.out.println("---------------------------------------------------");
  System.out.println("Using indexOf method with fromIndex with character");
  System.out.println("---------------------------------------------------");
  System.out.println("Index of character o from index 6 in \"Hello world from java2blog\" is : "+str.indexOf('o',6));
  System.out.println();
  
  // Using index of method with String
  System.out.println("---------------------------------------------------");
  System.out.println("Using indexOf method with String");
  System.out.println("---------------------------------------------------");
  
  System.out.println("Index of String \"from\" in \"Hello world from java2blog\" is : "+str.indexOf(str1));
  System.out.println();
  
  String howDo="How do you do";
  System.out.println("---------------------------------------------------");
  System.out.println("Using indexOf method with fromIndex with String");
  System.out.println("---------------------------------------------------");
  System.out.println("Index of String \"do\" from index 9 in \"How do you do\" is : "+howDo.indexOf("do",9));
  System.out.println();
  
  System.out.println("---------------------------------------------------");
  System.out.println("If String or char is not available");
  System.out.println("---------------------------------------------------");
  System.out.println("Index of \"from\" in \"How do you do\" is : "+howDo.indexOf("from"));
  
  
 }
}

When you run above program, you will get below output:
--------------------
Using indexOf method with character
--------------------
Index of character b in "Hello world from java2blog" is : 22

--------------------
Using indexOf method with fromIndex with character
--------------------
Index of character o from index 6 in "Hello world from java2blog" is : 7

--------------------
Using indexOf method with String
--------------------
Index of String "from" in "Hello world from java2blog" is : 12

--------------------
Using indexOf method with fromIndex with String
--------------------
Index of String "do" from index 9 in "How do you do" is : 11

--------------------
If String or char is not available
--------------------
Index of "from" in "How do you do" is : -1


String's substring method is used to fetch part of a String.It returns a new String which is substring of given String. substring is nothing but subset of given String.

There are two overloaded methods for substring.

Method Signature:

public String substring(int startIndex)
It returns a new String which is substring of given String from specified startIndex(Inclusive)
public String substring(int startIndex, int endIndex)
It returns a new String which is substring of given String from specified startIndex(Inclusive) to endIndex(Exclusive)
String's index always starts with 0. In case of substring method, startIndex is always inclusive and endIndex is exclusive

String substring Example:

package org.arpit.java2blog;

public class StringSubStringExample {

 public static void main(String[] args) {
  
  String str1= "java2blog.com";
  
  // using beginIndex
  System.out.println(str1.substring(5));
  // using beginIndex and endIndex
  System.out.println(str1.substring(5,9));
 }
}

When you run above program, you will get below output:
blog.com
blog

String's contains method checks if sequence of characters can be found in String. It returns true if character sequence is present in String else return false.

Method Signature:

public boolean contains(CharSequence s)

String contains Example:

package org.arpit.java2blog;

public class StringContainsMethodExample {

 public static void main(String[] args) {
  String str = "Hello world from java2blog.com";

  if (str.contains("world")) {
   System.out.println("String contains with world");
  } 
  else {
   System.out.println("String does not contain world");
  }

  if (str.contains("WORLD")) {
   System.out.println("String contains WORLD");
  } 
  else {
   System.out.println("String does not contain WORLD");
  }
 }
}
When you run above program, you will get below output:
String contains with world
String does not contain WORLD


Please note that contains method is case sensitive as you can see in above example

String concatenate is a way to join multiple Strings to create large String. There are many places where we use to do String concatenate.
For example: When you override toString() method of object, you concatenate multiple attributes to create a big String that represent that object.

3 ways to concatenate String

  1. Using + operator
  2. Using String's concat method
  3. Using StringBuffer or StringBuilder

+ Operator:

Although java does not support operator overloading but you can concatenate two String using + operator.
String str1= "Hello";
String str2="Java2blog"
String result= str1+str2;
Here result will be "HelloJava2blog" .

String's concat method:

You can use String 's concat method to concatenate two String.
String str1= "Hello";
String str2="Java2blog"
String result= str1.concat(str2);
Here result will be "HelloJava2blog" .

StringBuilder or StringBuffer:

You can use StringBuilder or StringBuffer's append method to concatenate two String.
String str1= "Hello";
String str2="Java2blog"
String result= new StringBuffer(str1).append(str2).toString();
It is fastest way to concatenate two String.

Performance Comparison:

  1. + Operator is not recommended for large String concatenation as it creates lots of temporary object and also some what slow.
  2. If you have lot of concatenation, StringBuffer or StringBuilder is recommended as it is fastest of all.

Java program for String concatenation:
package org.arpit.java2blog;

public class StringConcatenateExample {
 /*
  * @ Author : Arpit Mandliya
  */
 public static void main(String args[]) {
  
  String str1="hello";
  String str2="java2blog";
  // Using String's constructor
  System.out.println("--------------------");
  System.out.println("Using + operator");
  System.out.println("--------------------");
  
  // Below statement internally calls:
  // new StringBuffer().append(str1).append(str2)
  String resultUsingPlus=str1+str2;
  System.out.println(resultUsingPlus);
  System.out.println();

  // Using String's valueOf method
  System.out.println("--------------------");
  System.out.println("Using String's conat method");
  System.out.println("--------------------");
  String resultUsingConcat=str1.concat(str2);
  System.out.println(resultUsingConcat);
  System.out.println();

  // Using iterating char Array
  System.out.println("--------------------");
  System.out.println("Using StringBuffer or StringBuilder");
  System.out.println("--------------------");
  String resultUsingbuilder=new StringBuffer(str1).append(str2).toString();
  System.out.println(resultUsingbuilder);
 }
}

When you run above program, you will get below output
--------------------
Using + operator
--------------------
hellojava2blog

--------------------
Using String's conat method
--------------------
hellojava2blog

--------------------
Using StringBuffer or StringBuilder
--------------------
hellojava2blog

In this post, we will see how to split a String by delimiter in java. Sometimes, we need to split a String by delimiter
for example: while reading a csv file, we need to split string by comma(,).

We will use String class's split method to split a String. This split(regex)  takes a regex as a argument,  so we need to escape some regex special character for example dot(.).  Split method returns a array of String.

Example:

package org.arpit.java2blog;

public class StringSplitMain {
 public static void main(String args[])
 {
  // Splitting String separated by comma
  System.out.println("--------------------");
  System.out.println("Splitting by comma");
  System.out.println("--------------------");
  String str= "India,Delhi,200400";
  String[] strArr=str.split(",");
  for (int i = 0; i < strArr.length; i++) {
  System.out.println(strArr[i]);
 }
  
 // Splitting String by dot(.)
 // We need to put escape character in case of . as it is regex special character
  System.out.println("--------------------");
  System.out.println("Splitting by Dot");
  System.out.println("--------------------");
  String strDot= "India.Delhi.200400";
  String[] strArrDot=strDot.split("\\.");
  for (int i = 0; i < strArrDot.length; i++) {
  System.out.println(strArrDot[i]);
 } 
  
 }
}

When you run above progrm, you will get following output:
--------------------
Splitting by comma
--------------------
India
Delhi
200400
--------------------
Splitting by Dot
--------------------
India
Delhi
200400


There are multiple ways to convert Char Array to String in java.

Some of them are:
  • Using String class's constructor (By passing Char array to contructor)
  • Using String class's valueOf method
  • Using iterating char array

Example:

package org.arpit.java2blog;

public class CharArrToStringMain {
 /*
  * @ Author : Arpit Mandliya
  */
 public static void main(String args[]) {
  char[] charArr = { 'J', 'a', 'v', 'a', '2', 'b', 'l', 'o', 'g' };

  // Using String's constructor
  System.out.println("--------------------");
  System.out.println("Using String's contructor");
  System.out.println("--------------------");
  String str = new String(charArr);
  System.out.println(str);
  System.out.println();

  // Using String's valueOf method
  System.out.println("--------------------");
  System.out.println("Using String's valueOf");
  System.out.println("--------------------");
  String strV = String.valueOf(charArr);
  System.out.println(strV);
  System.out.println();

  // Using iterating char Array
  System.out.println("--------------------");
  System.out.println("Using iterating char Array");
  System.out.println("--------------------");
  String strT = "";
  for (int i = 0; i < charArr.length; i++) {
   strT += charArr[i];
  }
  System.out.println(strT);
 }
}

When you run above program, you will get below output
--------------------
Using String's contructor
--------------------
Java2blog

--------------------
Using String's valueOf
--------------------
Java2blog

--------------------
Using iterating char Array
--------------------
Java2blog

Other String Programs are :

    How to convert String to char Array in java How to reverse String in java Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String


Java String's toCharArray() method can be used to convert String to char Array in java. It is simplest method to convert String to char Array.

Example:
package org.arpit.java2blog;

public class StringToCharArrayMain {
/*
 * @Author: Aprit Mandliya
 */
 public static void main(String[] args) {
  String str="java2blog";
  char[] charArr=str.toCharArray();
  for (int i = 0; i < charArr.length; i++) {
   System.out.println(charArr[i]);
  }  
 }
}

When you run above program, you will get below output:
j
a
v
a
2
b
l
o
g

Other String Programs are :

String :

    How to reverse String in java How to check if two Strings are angrams Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String Why String is immutable in java Find duplicate characters in String


Spring autowiring byType means autowiring on the basis of datatype. if any bean property datatype matches with exact one other bean's datatype declaration then spring will automatically takes care of dependency. If more than one bean property matches, then it throws fatal exception.

Below diagram will make it clear:
Spring autowiring by Type


For example:
I am taking example of autowire "byType" here.It will be almost same as Dependency injection via setter method with some changes in XML configuration file.

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.java2blog.Copy following content into Country.java.
package org.arpit.java2blog;

public class Country {

    String countryName;
   
    Capital capitalObj;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
 public Capital getCapitalObj() {
  return capitalObj;
 }
 public void setCapitalObj(Capital capitalObj) {
  this.capitalObj = capitalObj;
 }
   
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.java2blog.java.Above Country class contains object of this class.Copy following content into Capital.java
package org.arpit.java2blog;

public class Capital {

       String capitalName;

       public String getCapitalName() {
              return capitalName;
       }

       public void setCapitalName(String capitalName) {
              this.capitalName = capitalName;
       }
}

3.BeanAutowiringByTypeMain.java

This class contains main function.Create BeanAutowiringByTypeMain.java under package org.arpit.java2blog.Copy following content into BeanAutowiringByTypeMain.java

package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanAutowiringByTypeMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        Country countryObj = (Country) appContext.getBean("country");
        String countryName=countryObj.getCountryName();
        String capitalName=countryObj.getCapitalObj().getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}

You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.java2blog.Country" autowire="byType">
  <property name="countryName" value="India"/>
 </bean>
 <bean id="capital" class="org.arpit.java2blog.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>

Here in <bean>,we have used autowire attribute and set it to "byType".So now spring container will match Capital datatype in Country class with type of other beans in XML configuration file. So here you can see we have bean with class as Capital.

5.Run it

When you will run above application,you will get following as output.
Delhi is capital of India

What if two properties of class have same datatype: 

Change ApplicationContext.xml as below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.java2blog.Country" autowire="byType">
  <property name="countryName" value="India"/>
 </bean>
 <bean id="capital1" class="org.arpit.java2blog.Capital">
  <property name="capitalName" value="Delhi1" />
 </bean>
 
 <bean id="capital2" class="org.arpit.java2blog.Capital">
  <property name="capitalName" value="Delhi2" />
 </bean>
</beans>

In above xml, we have declared two capital beans,now how it will autowire.
Answer: It won't.
When you run above program, it will give you below exception:

It will give you below exception.
 

Java tutorial for beginners Copyright © 2012