We have already seen SOAP web services and RESTful web services in detail before. In this post, we are going to see differences between SOAP and REST web services.

SOAP vs REST web services

Parameter
SOAP
REST
Acronym
SOAP stands for simple object access protocol
REST stands for REpresentational State Transfer
Protocol vs Architectural style
 SOAP is a standard protocol to create web services
Rest is architectural style to create web services.
Contract
Client and Server are bind with WSDL contract
There is no contract between client and Server.
Format Support
SOAP supports only XML format
REST web services supports XML, json and plain text etc.
Maintainability
SOAP web services are hard to maintain as if we do any changes in WSDL , we need to create client stub again
REST web services are generally easy to maintain.
Service interfaces vs URI
SOAP uses Service interfaces to expose business logic
Rest uses URI to expose business logic
Security
SOAP has its own security : WS-security
Rest inherits its security from underlying transport layer.
Bandwidth
SOAP requires more bandwidth and resources as it uses XML messages to exchange information
REST requires less bandwith and resources. It can use JSON also.
Learning curve
SOAP web services are hard to learn as you need to understand WSDL , client stub
REST web services are easy to understand as you need to annotate plain java class with JAX-RS annotations to use various HTTP methods.

Web services questions are most asked questions if you are applying for software developer role.
In this post, we will see multiple web services questions.

1. What are web services?

Web services are ways of communication between two application over network. It allows you to expose business logic using API.
For example:
Lets say you are java developer, you can create web service and expose API over internet and any other developer (lets say .net developer ) can access it.

2. What are features of web services?

  • Interoperability
  • Reuse already developed(old) functionality into new software:
  • Loosely Coupled 
  • Extensibility

3. What are different types of web services?

  • SOAP
  • Restful web services

4. What is SOAP?

SOAP stands for Simple object access protocol. It is protocol to exchange information using request and response in XML format over transport protocol such as HTTP, SMTP etc.

5. What are important components for SOAP?

  • Simple access object protocol (SOAP)
  • Web Services Description Language (WSDL)
  • Universal Description, Discovery and Integration(UDDI)

6. What is WSDL?

WSDL stands for Web Service Description Language. It is an XML file that describes the technical details of how to implement a web service, more specifically the URI, port, method names, arguments, and data types. You can understand following details using WSDL
  •     Port / Endpoint – URL of the web service
  •     Input message format
  •     Output message format
  •     Security protocol that needs to be followed
  •     Which protocol the web service uses

7. What is UDDI?

UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web service provider can register themselves with a UDDI and make themselves available through it for discovery.

8. What is JAX-WS?

JAX-WS stands for Java API for XML Web Services. JAX-WS is standard XML baed java API which is used to create SOAP web services.

9. What are some important annotations for JAX-WS?

  • @WebService
  • @WebMethod
  • @SOAPBinding

10. What do you mean by end point in terms of SOAP?

End point is nothing but URL which other application can use to access it.
for example:
end  point:http://localhost:8080/WS/HelloWorld

11. How can you access WSDL for web service?

You just need to put ?wsdl at the end of end point URL.
for example:
end  point:http://localhost:8080/WS/HelloWorld
WSDL url: http://localhost:8080/WS/HelloWorld?wsdl

12. What is wsimport?

wsimport is utility which generates java classes from WSDL. It is part of JDK 6.

13.What is sun-jaxws.xml file? 

This file provides endpoint details about JAX-WS web service which is deployed on tomcat.It is available at WEB-INF directory.
For example:
<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
  <endpoint
     name="HelloWorldWS"
     implementation="org.arpit.javapostsforlearning.webservice.HelloWorldImpl"
     url-pattern="/HelloWorldWS"/>
</endpoints> 

14. What are Restful web services?

In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web services client uses that URI to access the resource.

15.What are HTTP methods that can be used with Restful web services?

Mainly used HTTP methods are GET, POST, PUT ,DELETE, HEAD and OPTIONS

16. What is JAX-RS?

Java API for RESTful Web Services (JAX-RS), is a set if APIs to develop REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

17. What are some important annotations which you use to create Restful web services?

Some of important annotations which are used for creating web services are:
@Path : This is used to set path for URI at class level or method level
@GET,@POST,@PUT,@DELETE  : There are annotations corresponds to HTTP methods
@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method
@PathParam: Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Cosumes defines which MIME type will be consumed by the method .

18.  What are ways to test SOAP web services?

For testing SOAP :
SOAPUI
For testing Restful web services:
  • Postman for chrome browser
  • poster for firefox

19. How to choose between REST and SOAP web services?

  • If you want to implement web services in less time, go with REST
  • If you know your client beforehand , then you can choose SOAP. If you are not aware about clients then go with REST.
  • If you want to work with different format other than XML, go with REST. SOAP only supports XML format.

20. What are differences between SOAP and REST web services.

Parameter
SOAP
REST
Acronym
SOAP stands for simple object access protocol
REST stands for REpresentational State Transfer
Protocol vs Architectural style
 SOAP is a standard protocol to create web services
Rest is architectural style to create web services.
Contract
Client and Server are bind with WSDL contract
There is no contract between client and Server.
Format Support
SOAP supports only XML format
REST web services supports XML, json and plain text etc.
Maintainability
SOAP web services are hard to maintain as if we do any changes in WSDL , we need to create client stub again
REST web services are generally easy to maintain.
Service interfaces vs URI
SOAP uses Service interfaces to expose business logic
Rest uses URI to expose business logic
Security
SOAP has its own security : WS-security
Rest inherits its security from underlying transport layer.
Bandwidth
SOAP requires more bandwidth and resources as it uses XML messages to exchange information
REST requires less bandwith and resources. It can use JSON also.
Learning curve
SOAP web services are hard to learn as you need to understand WSDL , client stub
REST web services are easy to understand as you need to annotate plain java class with JAX-RS annotations to use various HTTP methods.

Restful web services are very popular now a days because it is very simple to implement and less time consuming. In this post, we are going to see restful web services interview questions with answers.

1. What is REST?

REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis.

In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.REST isn't protocol specific, but when people talk about REST they usually mean REST over HTTP.

2. What are Restful web services?

In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web services client uses that URI to access the resource.
It consists of two components REST server which provides access to the resources and a REST client which accesses and modify the REST resources.

3. What are important features of Restful web services?

Some important features of Restful web services are:
Resource identification through URI:Resources are identified by their URIs (typically links on internet). So, a client can directly access a RESTful Web Services using the URIs of the resources (same as you put a website address in the browser’s address bar and get some representation as response).
Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE.
Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.
Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
Named resources - the system is comprised of resources which are named using a URL.
Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.

4. What are HTTP methods that can be used in Restful web services?

RESTful web services use HTTP protocol methods for the operations they perform.
Some important Methods are:
GET : It defines a reading access of the resource without side-effects.This operation is idempotent i.e.they can be applied multiple times without changing the result
PUT : It is generally used for updating resource. It must also be idempotent.
DELETE : It removes the resources. The operations are idempotent i.e. they can get repeated without leading to different results.
POST : It is used for creating a new resource. It is not idempotent.

5. What do you mean by Idempotent and which HTTP methods are idempotent?

Idempotent means result of multiple successful request will not change state of resource after initial application
For example : Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted. Get, put and delete are HTTP Idempotent methods.

6. What are differences between Post and Put Http methods?

POST :It is used for creating a new resource. It is not idempotent.
PUT : It is generally used for updating resource. It is idempotent.
Idempotent means result of multiple successful request will not change state of resource after initial application

7. What happens if resources are shared by multiple clients? Do you need to make it thread safe explicitly?

New resource instance is created for each request, so you don't need to implement thread safety or synchronization aid. It is by default thread safe.

8. What is JAX-RS?

Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

9. What are REST frameworks that you are aware of and which can be used to create Restful webservices?

There are multiple Rest framework that can be used to create Restful web services such as
  • Jersey
  • RestEasy
  • Restlet
  • CFX
  • Spring Rest webservices

10. What are some important annotations which you use to create Restful web services?

Some of important annotations which are used for creating web services are:
@Path : This is used to set path for URI at class level or method level
@GET,@POST,@PUT,@DELETE  : There are annotations corresponds to HTTP methods
@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method
@PathParam: Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Cosumes defines which MIME type will be consumed by the method .

11. Can you use get method to create Resources rather than post?

No, Get should be used only for resource retrieval and not for resource creation.

12.  What are ways to test Restful web services?

You require a restful client to test restful web services. You can use:
  • Postman for chrome browser
  • poster for firefox

Please share more questions on restful web services and I will add it to the list.

Yes,  we can have try without catch block by using finally block.
You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit().

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

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  try
  {
   System.out.println("Executing try block"); 
  }
  finally
  {
   System.out.println("Executing finally block"); 
  }
 }
}

When you execute above program, you will get following output:
Executing try block
Executing finally block

What happens when you have return statement in try block:

If you have return statement in try block, still finally block executes.
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static String print()
 {
  try
  {
   System.out.println("Executing try block"); 
   return "Return from try block";
  }
  finally
  {
   System.out.println("Executing finally block"); 
  }
 }
}


When you execute above program, you will get following output:
Executing try block
Executing finally block
Return from try block

What happens if you have return statement in finally block too: 

It overrides whatever is returned by try block. Lets understand with the help of example:
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static String print()
 {
  try
  {
   System.out.println("Executing try block"); 
   return "Return from try block";
  }
  finally
  {
   System.out.println("Executing finally block"); 
   return "Return from finally block";
  }
 }
}

When you execute above program, you will get following output:
Executing try block
Executing finally block
Return from finally block

What if exception is thrown in try block :

If exception is thrown in try block, still finally block executes.
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static int  print()
 {
  try
  {
   throw new NullPointerException();
   
  }
  finally
  {
   System.out.println("Executing finally block"); 
   
  }
 }
}


When you execute above program, you will get following output:
Executing finally block
Exception in thread "main" java.lang.NullPointerException
 at org.arpit.java2blog.TryWithoutCatchMain.print(TryWithoutCatchMain.java:14)
 at org.arpit.java2blog.TryWithoutCatchMain.main(TryWithoutCatchMain.java:7)


Spring autowiring by constructor is similar to autowiring by type but it is applied to constructor argument. If more than one bean property matches, then it throws fatal exception.

Below digram will make it clear:

For example:
I am taking example of autowire by "constructor" 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 Country(String countryName, Capital capitalObj) {
  super();
  this.countryName = countryName;
  this.capitalObj = 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.BeanAutowiringByContructorMain.java

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

package org.arpit.javapostsforlearning;

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

public class BeanAutowiringByConstructorMain{

    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="constructor">
    <constructor-arg index="0" type="java.lang.String" value="India" />
 </bean>
 <bean id="capitalObj" class="org.arpit.java2blog.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>

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="constructor">
    <constructor-arg index="0" type="java.lang.String" 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.

Daemon threads are low priority background threads which provide services to user threads. It's life depends on user threads. If no user thread is running then JVM can exit even if daemon threads are running. JVM do not wait for daemon threads to finish.

Daemon threads perform background tasks such as garbage collection, finalizer  etc.
The only purpose of daemon thread is to serve user thread so if there are no user threads, there is no point of JVM to run these threads, that's why JVM exits once there are no user threads.

Two method related to daemon thread

Public void setDaemon(boolean status) :
This method can be used to mark thread as user  or daemon thread. If you put setDaemon(true), it makes thread as daemon.

Public boolean isDaemon()
This method can be used to check if thread is daemon or not.

Daemon Thread example:

package org.arpit.java2blog;


class SimpleThread implements Runnable{

 public void run()
 {
  if(Thread.currentThread().isDaemon())
   System.out.println(Thread.currentThread().getName()+"  is daemon thread");
  else
   System.out.println(Thread.currentThread().getName()+"  is user thread");
 }
 
}

public class DaemonThreadMain {
 public static void main(String[] args){  
  SimpleThread st=new SimpleThread();
    Thread th1=new Thread(st,"Thread 1");//creating threads
    Thread th2=new Thread(st,"Thread 2");  
    Thread th3=new Thread(st,"Thread 3");  
    
    th2.setDaemon(true);//now th2 is daemon thread  
      
    th1.start();//starting all threads  
    th2.start();  
    th3.start();  
   }  
}

When you run above program, you will get below output:
Thread 1  is user thread
Thread 3  is user thread
Thread 2  is daemon thread
Please note that you can not convert user thread to daemon thread once it is started otherwise it will throw IllegalThreadStateException.
package org.arpit.java2blog;


class SimpleThread implements Runnable{

 public void run()
 {
  if(Thread.currentThread().isDaemon())
   System.out.println(Thread.currentThread().getName()+"  is daemon thread");
  else
   System.out.println(Thread.currentThread().getName()+"  is user thread");
 }
 
}

public class DaemonThreadMain {
 public static void main(String[] args){  
  SimpleThread st=new SimpleThread();
    Thread th1=new Thread(st,"Thread 1");//creating threads
    Thread th2=new Thread(st,"Thread 2");  
    Thread th3=new Thread(st,"Thread 3");  
    
    
      
    th1.start();//starting all threads  
    th2.start();  
    th3.start();  
                  th2.setDaemon(true);//now converting user thread to daemon thread after starting the thread. 
   }  
}

When you run above program, you will get below output:
Thread 1  is user threadException in thread "main" 
Thread 2  is user thread
Thread 3  is user thread
java.lang.IllegalThreadStateException
 at java.lang.Thread.setDaemon(Thread.java:1388)
 at org.arpit.java2blog.DaemonThreadMain.main(DaemonThreadMain.java:28)




In this post, we will see how to remove non ascii character from a string in java.
Sometimes, you get non-ascii characters in String and you need to remove them. We will use regular expressions to do it.

Java program to remove non-ascii characters:

package org.arpit.java2blog;

public class StringRemoveASCIIMain {
   
     public static void main(String a[]){
         String str = "jå∫∆avµa2bl√øog";
         System.out.println("Before removing non ASCII characters:");
         System.out.println(str);
         System.out.println("------------------------------------");
         // Using regular expressions to remove non ascii characters
         str = str.replaceAll("[^\\p{ASCII}]", "");
         System.out.println("After removing non ASCII characters:");
         System.out.println(str);
     }
 }


When you run above program, you will get below output:
Before removing non ASCII characters:
jå∫∆avµa2bl√øog
------------------------------------
After removing non ASCII characters:
java2blog

In this post, we will see how to convert HashMap to ArrayList in java. Many a times, you need to store keys or values into ArrayList or Store HashMap's Entry objects in ArrayList.

Java HashMap tutorial:

    HashMap in javaHashMap internal workinghash and indexfor method in HashMaphashcode and equals in javasort HashMap by keys and valuesDifference between HashMap and HashSetDifference between HashMap and HashtableHow to iterate over HashMap
Lets take an example:
1. HashMapToArrayListConversionMain.java
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class HashMapToArrayListConversionMain {

 public static void main(String args[])
 {
  // HashMap with Country as key and capital as value
  HashMap<String,String> countryCapitalMap=new HashMap<String,String>();
  countryCapitalMap.put("India","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");


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

  // Creating  ArrayList from Keys
  
  ArrayList<String> keysArrayList=new ArrayList<String>(countryCapitalMap.keySet());
  System.out.println("Keys are: ");
  for (String country:keysArrayList) {
 System.out.println(country);
}
 
  System.out.println("-----------------------------");

  //Creating  ArrayList from Values
  ArrayList<String> valuesArrayList=new ArrayList<String>(countryCapitalMap.values());
  System.out.println("Values are: ");
  for (String capital:valuesArrayList) {
 System.out.println(capital);
}
  System.out.println("-----------------------------");

  //Creating  ArrayList from Entry set
  ArrayList<Entry<String,String>> entryArrayList=new ArrayList<Entry<String,String>>(countryCapitalMap.entrySet());
  for (Entry<String,String> entry:entryArrayList) {
   System.out.println("Country:"+ entry.getKey() +" and  Capital:"+entry.getValue());

  }
 
  System.out.println("-----------------------------");

 }

}

Run it and you will get following output:
-----------------------------
Keys are: 
France
Russia
Japan
India
-----------------------------
Values are: 
Paris
Moscow
Tokyo
Delhi
-----------------------------
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------


In this post, we will see if String has all unique characters or not.

There are multiple ways to find if String has all unique characters or not.

By Using HashSet:

  1. You can add each character to HashSet.
  2. If HashSet's add method returns false then it does not have all unique characters.

Java Program to check if String has all unique characters Using HashSet:

package org.arpit.java2blog;

public class StringAllUniqueCharMain {

 public static void main(String[] args) {
  
  System.out.println("java2blog has all unique chars : "+ hasAllUniqueChars("java2blog"));
  System.out.println("Apple has all unique chars : "+ hasAllUniqueChars("apple"));
  System.out.println("index has all unique chars : "+ hasAllUniqueChars("index"));
  System.out.println("world has all unique chars : "+ hasAllUniqueChars("world"));
 }
 
 
 public static boolean hasAllUniqueChars (String word) {

     HashSet alphaSet=new HashSet();


     for(int index=0;index < word.length(); index ++)   {
      
         char c =word.charAt(index);

         // If Hashset's add method return false,that means it is already present in HashSet
         if(!alphaSet.add(c))
              return false;
     }

     return true;
 }
}

When you run above program, you will get below output:
java2blog has all unique chars : false
Apple has all unique chars : false
index has all unique chars : true
world has all unique chars : true

By using indexOf and lastIndexOf methods.

If indexOf and lastIndexOf returns same value for the character, then it is not repeated in that String.

Java Program to check if String has all unique characters Using indexOf and lastIndexOf:

package org.arpit.java2blog;

public class StringAllUniqueCharMain {

 public static void main(String[] args) {
  
  System.out.println("java2blog has all unique chars : "+ hasAllUniqueChars("java2blog"));
  System.out.println("Apple has all unique chars : "+ hasAllUniqueChars("apple"));
  System.out.println("index has all unique chars : "+ hasAllUniqueChars("index"));
  System.out.println("world has all unique chars : "+ hasAllUniqueChars("world"));
 }
 
 
 public static boolean hasAllUniqueChars (String word) {

     for(int index=0;index < word.length(); index ++)   {
      
         char c =word.charAt(index);
         if(word.indexOf(c)!=word.lastIndexOf(c))
              return false;
     }

     return true;
 }
}

When you run above program, you will get below output:
java2blog has all unique chars : false
Apple has all unique chars : false
index has all unique chars : true
world has all unique chars : true

By using ascii value of character

It is most efficient of all.
Approach:
  1. Create a boolean array of 26 length
  2. Convert char to uppercase and get its ascii value
  3. Subtract 64 to ascii value to get index between 0 to 25.
  4. If character is not repeated then we should have false in the boolean array

Java Program to check if String has all unique characters:


package org.arpit.java2blog;

public class StringAllUniqueCharMain {

 public static void main(String[] args) {
  
  System.out.println("java2blog has all unique chars : "+ hasAllUniqueChars("java2blog"));
  System.out.println("Apple has all unique chars : "+ hasAllUniqueChars("apple"));
  System.out.println("index has all unique chars : "+ hasAllUniqueChars("index"));
  System.out.println("world has all unique chars : "+ hasAllUniqueChars("world"));
 }
 
 
 public static boolean hasAllUniqueChars (String word) {

     boolean[] charMap = new boolean[26];


     for(int index=0;index < word.length(); index ++)   {
      // we are substracting char's ascii value to 64, so we get all index
      // from 0 to 25.
         int asciiCode = (int) word.toUpperCase().charAt(index) - 64;

         // If char is not present, it should have false at that index
         if(!charMap[asciiCode])
          charMap[asciiCode] = true;
          else
             return false;
     }

     return true;
 }

}

When you run above program, you will get below output:
java2blog has all unique chars : false
Apple has all unique chars : false
index has all unique chars : true
world has all unique chars : true


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
 

Java tutorial for beginners Copyright © 2012