SOAP Web Service in Java (JAX-WS)

In this tutorial, we will show you how to develop a simple SOAP based Web Service in Java using JAX-WS, called as "CalculatorService" in NetBeans 7.3. In order to demonstrate development of this application we begin with:

1. Create a Web Application named as "Calculator" in NetBeans.
2. Creating a SOAP Web Service called as "CalculatorService"
3. Creating a simple operation called as "sum".
4. Deploy and Test the Web Service.

Create a Web Application named as "Calculator" in NetBeans.

Step 1 :- Open NetBeans IDE (See fig below)



and Select in the menu bar File ---> New Project or press Ctrl + Shift + N. (See fig below)


New Project dialog box gets open.

Step 2 :- Under Categories: select Java Web.
Step 3 :- Under Projects: select Web Application.
Step 4 :- Click Next > . (See fig below)































New Web Application dialog box gets open.

Step 5 :- Under Name and Location tab, enter Project Name: as "Calculator".
Step 6 :- Click Next > . (See fig below)



Under the same New Web Application, Server and Settings dialog box gets open.

Step 7:- Choose Server: as "GlassFish Server 4.0". You can also choose "GlassFish v3 Domain" as server if you are using old version of NetBeans other than 7.3.1, which comes bundled with "GlassFish v3 Domain".

Step 8:- Choose Java EE 6 Web as Java EE Version:. Keep rest as default. 
Step 9:- Click Finish. (See fig below)



Creating a SOAP Web Service called as "CalculatorService"

Step 1:- Right click on Calculator project and Select New ---> Web Service... (see fig below) 



Step 2:- New Web Service dialog box gets open. In the Web Service Name: textfield enter name as "CalculatorService".

Step 3:- Enter the package name for the CalculatorService Web Service.

Step 4:- Click Finish. (see fig below)




Creating a simple operation called as "sum".

Step 5:- After creating Web Service by name "CalculatorService". Under Web Services directory of the project, right click on the CalculatorService created and click on "Add Operation". (see fig below)
































Add Operation dialog box gets open.

Step 6:- Enter name of the operation to expose as Web Service method. Here provide as "sum".

Step 7:- Enter the return type for the method. Here sum method will calculate sum of two numbers "number1" and "number2" and return it as a int value.

Step 8, 9 and 10:- Enter two parameters by clicking add button as "number1" and "number2" of type int, whose sum is to be calculated in the method sum. Click OK. (see fig below)




















































Open Web Service class by name "CalculatorService". Operation by name sum gets created having return type as int. It gets in two parameters as number1 and number2 of the type int. The java class is now a Web Service as it is annotated by @javax.jws.WebService. The operation sum becomes the exposed method of the Web Service as it is annotated by @javax.jws.WebMethod. This method takes in two SOAP request parameters of type int annotated as @javax.jws.WebParam. (see java class below)

package com.hubberspot.webservice;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

// @WebService annotation makes a class a Web Service
@WebService(serviceName = "CalculatorService")
public class CalculatorService {

    // @WebMethod annotation expose a method as a service.
    @WebMethod(operationName = "sum")
    // @WebParam annotation indicates parameters to method coming from SOAP request.
    public int sum(@WebParam(name = "number1") int number1, 
                   @WebParam(name = "number2") int number2) {
        
        int sum = 0;
        
        sum = number1 + number2;
        
        return sum;
    }    
}



Deploy and Test the Web Service. 

Step 1:- Right click on the "Calculator" project directory and click "Deploy". The Web Service gets deployed on the GlassFish Server.(see fig below)




























Step 2:- Under Web Services directory of the project, right click on the CalculatorService created and click on "Test Web Service". It opens a browser window to test the CalculatorService Web Service (see fig below)

































A browser window gets open and GlassFish Server creates a Tester client on the URL "http://localhost:8080/Calculator/CalculatorService?Tester". The Tester client has a link to the WSDL file created for the Web Service. The link to WSDL file is at : "http://localhost:8080/Calculator/CalculatorService?WSDL" (see fig and WSDL file below).

Step 3:- In order to test sum method exposed as Web Service. Enter number1 parameter value on the Tester client say 5.

Step 4:- Enter number2 parameter value on the Tester client say 10.

Step 5:- After the entering the value for number1 and number2 variables click sum button.

WSDL file for the CalculatorService Web Service -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<definitions targetNamespace="http://webservice.hubberspot.com/" 
             name="CalculatorService" xmlns="http://schemas.xmlsoap.org/wsdl/" 
             xmlns:wsp="http://www.w3.org/ns/ws-policy" 
             xmlns:tns="http://webservice.hubberspot.com/" 
             xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
             xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" 
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
             xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" 
             xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <types>
    <xsd:schema>
      <xsd:import namespace="http://webservice.hubberspot.com/" 
                  schemaLocation="CalculatorService_schema1.xsd"/>
    </xsd:schema>
  </types>
  <message name="sum">
    <part name="parameters" element="tns:sum"/>
  </message>
  <message name="sumResponse">
    <part name="parameters" element="tns:sumResponse"/>
  </message>
  <portType name="CalculatorService">
    <operation name="sum">
      <input wsam:Action="http://webservice.hubberspot.com/CalculatorService/sumRequest" 
             message="tns:sum"/>
      <output wsam:Action="http://webservice.hubberspot.com/CalculatorService/sumResponse" 
              message="tns:sumResponse"/>
    </operation>
  </portType>
  <binding name="CalculatorServicePortBinding" type="tns:CalculatorService">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
    <operation name="sum">
      <soap:operation soapAction=""/>
      <input>
        <soap:body use="literal"/>
      </input>
      <output>
        <soap:body use="literal"/>
      </output>
    </operation>
  </binding>
  <service name="CalculatorService">
    <port name="CalculatorServicePort" binding="tns:CalculatorServicePortBinding">
      <soap:address location="http://localhost:8080/Calculator/CalculatorService"/>
    </port>
  </service>
</definitions>


On clicking sum button, "CalculatorService" Web Service method called as sum gets executed taking in 5 and 10 as int parameters and returns sum as 15.

Step 6:- It shows method parameters as 5 and 10 of type int.
Step 7:- The return value after execution of sum method.
Step 8:- It shows the SOAP request for the "CalculatorService" Web Service which is been send in the form of xml. It is sending the values for number1 and number2 for the sum method.
Step 9:- It shows the SOAP response coming from the "CalculatorService" Web Service, returning the output of sum of number1 and number2.(see fig below)




ICSE Java Programs

  1. Write a menu‐driven class to accept a number from the user and check whether it is a Palindrome number or not in Java.
  2. Write a menu‐driven class to accept a number from the user and check whether it is a Perfect number or not in Java.
  3. Write a program to calculate and print the sum of the following series:  Sum(x) = 2 – 4 + 6 – 8 + 10 - 12 … - 100
  4. Write a program to calculate and print the sum of the following series: Sum(x) = x/2 + x/5 + x/8 + … + x/100.
  5. Write a menu‐driven class to accept a number from the user and check whether it is a Automorphic number or not in Java.
  6. Write a Java program to print Jacobsthal Sequence.
  7. Write a Java program to print Padovan Sequence.
  8. Write a program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero.
  9. Pattern problems : Write a Java program to print same character on each line and having character increment with each line.
  10. Pattern problems : Write a Java program to print different character on each line and having character increment with each line.
  11. Pattern problems : Write a Java program to print same character on each line and having character printed in diagonal form.
  12. Pattern problems : Write a Java program to print same character on each line and having character printed in V shape form.
  13. Pattern problems : Write a Java program to print same character on each line and having character printed in Inverted V shape form.
  14. Pattern problems : Write a Java program to print same character on each line and having character printed in Square shape form.
  15. Write a Java program to calculate sum of the digits of a number entered by the user.

How to create a Java client for consuming SOAP Web Service ?.

After deploying CalculatorService Web Service in GlassFish Server, refer post : How to create your first SOAP based Web Service in Java using JAX-WS ? , the next step is to make a Java client that can consume it. In above article, CalculatorService had a method as sum. In this post we will create a Java client for consuming sum by passing in two numbers and getting back the sum of it. The steps involved in creating Java client are as follows :

1. Creating a Java application as CalculatorServiceClient.
2. Adding Web Service client to the Java application.
3. Creating a Java client class for consuming CalculatorService Web Service.
4. Build and Run the Java client.


Creating a Java application as CalculatorServiceClient.


Step 1 :- Open NetBeans IDE (See fig below)



and Select in the menu bar File ---> New Project or press Ctrl + Shift + N. (See fig below)


New Project dialog box gets open.

Step 2 :- Under Categories: select Java.
Step 3 :- Under Projects: select Java Application.
Step 4 :- Click Next > . (See fig below)



Step 5 :- Under Name and Location, provide Project Name: as "CalculatorServiceClient".
Step 6 :- Select check box for (Create Main Class) as it creates a main class which will be our Web Service Java Client.
Step 7 :- Click Finish. (see fig below)



Adding Web Service client to the Java application.

Step 1:- Right click CalculatorServiceClient project directory and browse to New ---> Other. (see fig below)




Step 2:- New File dialog box gets open. Under Categories: select Web Services.
Step 3:- Under File Types: select Web Service Client
Step 4:- Click Next >. (see fig below)



Step 5:- New Web Service Client dialog box gets open. Under WSDL and Client Location , specify the WSDL file location for the CalculatorService Web Service by following options as Project: , Local File: , WSDL URL: , IDE Registered:. Select WSDL URL and provide the url for the deployed CalculatorService WSDL on the localhost. As we have deployed CalculatorService on the GlassFish Server in the above mentioned post, here it is pointing at "http://localhost:8080/Calculator/CalculatorService?WSDL", localhost is the ip address for it. If Web Service is deployed on another server provide the ip address for it on the WSDL url.

Step 6:- Enter the package name.
Step 7:- Click Finish. (see fig below)



Step 8:- It creates client side artifacts for the Service Endpoint Interface (SEI), which acts as a Proxy for the SOAP Web Service. (see fig below)




Creating a Java client class for consuming CalculatorService Web Service.

Open the CalculatorServiceClient.java and add the following code to it.

package calculatorserviceclient;

import com.hubberspot.webservice.client.CalculatorService;
import com.hubberspot.webservice.client.CalculatorService_Service;

public class CalculatorServiceClient {

    public static void main(String[] args) {

        int number1 = 6;
        int number2 = 12;

        // Create the proxy Web Service and call the sum method
        // using the port of the proxy service.
        CalculatorService_Service service = new CalculatorService_Service();
        CalculatorService port = service.getCalculatorServicePort();

        // retrieve the sum of number1 and number2
        int sum = port.sum(number1, number2);

        System.out.println("The Sum of two numbers : " + number1
                + " and " + number2 + " is " + sum);
    }
}



Build and Run the Java client

Step 1:- Right click CalculatorServiceClient project directory and select Build.
Step 2:- Run the CalculatorServiceClient.java class

  

Output of the program : 

 

Browse All Java Examples

Java EE

  1. Java Server Pages (JSP) : Advantages over Servlets and other technologies
  2. How to create simple Hello World Servlet application in Java ?
  3. What is a Web Application in Java programming language?
  4. A Simple HTML and JSP Email Subscription List Application
  5. How to get real path for a file in JSP and Servlet ?.
  6. How to use various types of JSP tags in a JSP page ?
  7. How to set and get an attribute to/from request object in JSP and Servlets ?
  8. How to redirect responses to a different JSP or Servlets ?.
  9. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  10. How to destroy a session in JSP and Servlets using Session Management API ?
  11. How to expire and destroy Cookies in JSP and Servlets ?
  12. A simple application demonstrating Request, Session, Context differences and usages in JSP and Servlets
  13. How to check whether which Web-Browser have been used to run JSP and Servlets ?.
  14. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  15. How to destroy a session in JSP and Servlets using Session Management API ?
  16. How to perform create sql query in JSP and Servlets using JDBC ?
  17. How to perform insert sql query in JSP and Servlets using JDBC ?
  18. How to perform update sql query in JSP and Servlets using JDBC ?
  19. How to create a Filter that adds url and time of request to a database in JSP and Servlets ?.
  20. How to perform delete sql query in JSP and Servlets using JDBC ?
  21. How to create error page in a JSP and Servlet to handle exceptions ?
  22. How to use filters in JSP and Servlets for logging information in ServletContext logs ?
  23. How to include JSP page dynamically into another JSP page?
  24. How to display HTTP Request Headers through a Servlet ?.
  25. How to display Request url Information through a Servlet ?
  26. How to display request parameters in a JSP coming in a request ?.
  27. How to use model / Java / Pojo classes with JSP and Servlets ?.
  28. How to forward a request to a JSP using RequestDispatcher ?.
  29. How to do Session Management in JSP and Servlets using its methods and API ?.
  30. How to forward a request from one Jsp to another Jsp ?.
  31. How to include one JSP into another JSP ?.
  32. How to use Jsp action elements useBean, setProperty and getProperty to add, set and get property of a bean in a JSP page ?.
  33. How to decorate form in a JSP using fieldset and legend tag ?.
  34. How to write a Servlet code to download a Jar or file from the Server at a specified location ?.
  35. How to use Servlets Initialization Parameters through ServletConfig object in Java EE Application ?.
  36. How to use Context Parameters in Servlets through ServletContext object in Java EE Application ?.
  37. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  38. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  39. How to use Arithmetic Operations in Expression Language ( el ) in a simple jsp page ?.
  40. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  41. How to use param implicit object in a JSP page ?. 
  42. "Online Tweeter Enterprise Application" : Creating an Enterprise Application with EJB 3.1 in Netbeans - Part 0
  43. "Online Tweeter Enterprise Application" : Creating an Enterprise Application Project in NetBeans - Part 1
  44. "Online Tweeter Enterprise Application" : Creating a Persistence Unit in NetBeans - Part 2
  45. "Online Tweeter Enterprise Application" : Creating an Entity Class in NetBeans EJB module - Part 3
  46. "Online Tweeter Enterprise Application" : Creating a Message-Driven Bean in NetBeans EJB module - Part 4
  47. "Online Tweeter Enterprise Application" : Creating a Stateless Session Bean in NetBeans EJB module - Part 5
  48. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  49. "Online Tweeter Enterprise Application" : Creating a Singleton Session Bean in NetBeans EJB module - Part 7
  50. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  51. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  52. "Online Tweeter Enterprise Application" : Building and Running the Enterprise Application - Part 10
  53.  


@Required Annotation in Spring Framework

@Required annotation is placed in Spring API package org.springframework.beans.factory.annotation.* . This annotation is used for checking Spring Dependency. It checks whether properties of bean are set or not. @Required annotation is placed over the setter for the properties which is to be checked for Spring Dependency. 

A Spring Bean by the name "RequiredAnnotationBeanPostProcessor" checks if properties annotated with @Required have been set. Before a bean is initialized into a Spring Container this bean post processor checks for properties whether are set or not (marked as @Required).

Let's look at it by a simple example -

(WITHOUT @Required ANNOTATION)

1. Create a class say "Address.java"

package com.hubberspot.spring.ioc;

public class Address {

 private String street;
 private String city;
 
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 } 
 
}


2. Create a class say "Employee.java"

package com.hubberspot.spring.ioc;

public class Employee {

 private String firstName; 
 private Address address;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 } 
 
}




3. Create a Spring Configuration file say "spring.xml"

<beans xmlns:context="http://www.springframework.org/schema/context" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://www.springframework.org/schema/beans" 
xsi:schemalocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
 <bean class="com.hubberspot.spring.ioc.Employee" id="employee">
  <property name="firstName" value="Dinesh"></property>
 </bean>

 <bean class="com.hubberspot.spring.ioc.Address" id="address">
     <property name="street" value="Park Street"></property>
     <property name="city" value="Pune"></property>
 </bean>

</beans>



4. Create a Test class say "Test.java"

package com.hubberspot.spring.ioc;

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

public class Test {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which
  // provides with the configuration for an application.
  // It provides us with all the methods that BeanFactory
  // provides. It loads the file resources in a older
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // We are using concrete implementation of ApplicationContext
  // here called as ClassPathXmlApplicationContext because this
  // bean factory reads the xml file placed in the classpath of
  // our application. We provide ClassPathXmlApplicationContext
  // with a configuration file called as spring.xml placed
  // at classpath of our application.
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

  // In order to get a object instantiated for a particular bean
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed.
  // Here getBean() returns an Object. We need to cast it back
  // to the Employee object. Without implementing new keyword we
  // have injected object of Employee just by reading an xml
  // configuration file.  
  Employee employee = (Employee) context.getBean("employee");

  System.out.println("FirstName : " + employee.getFirstName());

  System.out.println("Address : " + employee.getAddress().getStreet() + " , "
    + employee.getAddress().getCity());


 }

}


As we haven't provided Dependency Injection for Address bean in Employee bean. When we run the above Test class the output comes out to be as -

Exception in thread "main" FirstName : Dinesh
java.lang.NullPointerException
    at com.hubberspot.spring.ioc.Test.main(Test.java:36)


Its a null pointer exception because Address bean is not set in Employee bean. When we access the properties of Address bean through Address we get null pointer exception.

(WITH @Required ANNOTATION)

1. Create a class say "Address.java"

package com.hubberspot.spring.ioc;

public class Address {

 private String street;
 private String city;
 
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 } 
 
}


2. Create a class say "Employee.java" having @Required annotation on Address setter method.

package com.hubberspot.spring.ioc;

import org.springframework.beans.factory.annotation.Required;

public class Employee {

 private String firstName; 
 private Address address;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public Address getAddress() {
  return address;
 }

 @Required
 public void setAddress(Address address) {
  this.address = address;
 }  
 
}




3. Create a Spring Configuration file say "spring.xml" having a tag context:annotation-config for registering RequiredAnnotationBeanPostProcessor which checks if all the bean properties with the @Required annotation have been set.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
 <context:annotation-config />
  
 <bean id="employee" class="com.hubberspot.spring.ioc.Employee">
  <property name="firstName" value="Dinesh"></property>
 </bean>

 <bean id="address" class="com.hubberspot.spring.ioc.Address">
     <property name="street" value="Park Street"></property>
     <property name="city" value="Pune"></property>
 </bean>

</beans>



4. Create a Test class say "Test.java"

package com.hubberspot.spring.ioc;

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

public class Test {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which
  // provides with the configuration for an application.
  // It provides us with all the methods that BeanFactory
  // provides. It loads the file resources in a older
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // We are using concrete implementation of ApplicationContext
  // here called as ClassPathXmlApplicationContext because this
  // bean factory reads the xml file placed in the classpath of
  // our application. We provide ClassPathXmlApplicationContext
  // with a configuration file called as spring.xml placed
  // at classpath of our application.
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

  // In order to get a object instantiated for a particular bean
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed.
  // Here getBean() returns an Object. We need to cast it back
  // to the Employee object. Without implementing new keyword we
  // have injected object of Employee just by reading an xml
  // configuration file.  
  Employee employee = (Employee) context.getBean("employee");

  System.out.println("FirstName : " + employee.getFirstName());

  System.out.println("Address : " + employee.getAddress().getStreet() + " , "
    + employee.getAddress().getCity());


 }

}


As we haven't provided Dependency Injection for Address bean in Employee bean but this time we have marked setter method of Address with @Required annotation. When we run the above Test class the output comes out to be as -

Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'employee' defined in class path resource [spring.xml]:
Initialization of bean failed; nested exception is

org.springframework.beans.factory.BeanInitializationException:
Property 'address' is required for bean 'employee'



It checks this time before initialization of Employee bean that Address bean is not injected and exception is thrown.


Java 7 New Features

Networking in Java

Multithreading in Java

How to count monetary units through a Java program ?.

Program to demonstrate how to count monetary units through a Java program.

import java.util.Scanner;

public class MonetaryUnits {

 public static void main(String[] args) {

  // Creating a Scanner object using a constructor
  // which takes the System.in object. There are various
  // constructors for Scanner class for different
  // purposes. We want to use Scanner class to read
  // data from console on the system, So we are using
  // a constructor which is taking an System.in object
  Scanner scanner = new Scanner(System.in);

  // Prompt the user to enter amount in dollars (in decimals)
  System.out.print("Enter an amount in dollars (in decimals) : ");
  double amount = scanner.nextDouble();

  // Convert the amount into cents by multiplying it by 100.
  int amountLeft = (int)(amount * 100);

  // In order to find number of dollars divide amountLeft
  // by 100.
  int dollars = amountLeft / 100;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 100).
  amountLeft = amountLeft % 100;

  // In order to find number of quarters divide amountLeft
  // by 25. 
  int quarters = amountLeft / 25;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 25).
  amountLeft = amountLeft % 25;

  // In order to find number of dimes divide amountLeft
  // by 10.
  int dimes = amountLeft / 10;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 10).
  amountLeft = amountLeft % 10;

  // In order to find number of dimes divide amountLeft
  // by 5.
  int nickels = amountLeft / 5;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 5).
  amountLeft = amountLeft % 5;

  // In order to find number of pennies divide amountLeft
  // by 1.
  int pennies = amountLeft / 1;

  // Displaying the result on the console.
  System.out.println("The amount : " + amount + " consists of");
  System.out.println(dollars + " Dollars");
  System.out.println(quarters + " Quarters");        
  System.out.println(dimes + " Dimes");
  System.out.println(nickels + " Nickels");
  System.out.println(pennies + " Pennies");

 }

}



Output of the program : 

 

Streams and Files in Java

  1. Creating objects and methods list of File class in Java
  2. Program to demonstrate how to display File information in Java ?.
  3. How to pass input from a console to a Java program ?.
  4. How to convert InputStream data to String data in Java ?.
  5. A simple Java program demonstrating how to read and write Images to a file ?
  6. How to Play an MP3 File in Java ?
  7. How to Capture Screen through a Java program using Robot class  ?.
  8. A simple program demonstrating how to load properties from an xml file ?
  9. A simple program demonstrating how to store properties to an XML file ?
  10. A simple Java program to read and download a Web page in a html file
  11. How to get and print last modification date of a file on the console in Java ?.
  12. How to Copy a file from one location to another in Java ?.
  13. How to read Zip or Jar Archive File using Java ?.
  14. How to create new directory and sub-directories in Java ?.
  15. How to Write an XML file through a simple Java program ?.
  16. StringTokenizer class in Java

Hibernate Framework in Java

JSP and Servlet Programming

  1. Java Server Pages (JSP) : Advantages over Servlets and other technologies
  2. How to create simple Hello World Servlet application in Java ?
  3. What is a Web Application in Java programming language?
  4. A Simple HTML and JSP Email Subscription List Application
  5. How to get real path for a file in JSP and Servlet ?.
  6. How to use various types of JSP tags in a JSP page ?
  7. How to set and get an attribute to/from request object in JSP and Servlets ?
  8. How to redirect responses to a different JSP or Servlets ?.
  9. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  10. How to destroy a session in JSP and Servlets using Session Management API ?
  11. How to expire and destroy Cookies in JSP and Servlets ?
  12. A simple application demonstrating Request, Session, Context differences and usages in JSP and Servlets
  13. How to check whether which Web-Browser have been used to run JSP and Servlets ?.
  14. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  15. How to destroy a session in JSP and Servlets using Session Management API ?
  16. How to perform create sql query in JSP and Servlets using JDBC ?
  17. How to perform insert sql query in JSP and Servlets using JDBC ?
  18. How to perform update sql query in JSP and Servlets using JDBC ?
  19. How to create a Filter that adds url and time of request to a database in JSP and Servlets ?.
  20. How to perform delete sql query in JSP and Servlets using JDBC ?
  21. How to create error page in a JSP and Servlet to handle exceptions ?
  22. How to use filters in JSP and Servlets for logging information in ServletContext logs ?
  23. How to include JSP page dynamically into another JSP page?
  24. How to display HTTP Request Headers through a Servlet ?.
  25. How to display Request url Information through a Servlet ?
  26. How to display request parameters in a JSP coming in a request ?.
  27. How to use model / Java / Pojo classes with JSP and Servlets ?.
  28. How to forward a request to a JSP using RequestDispatcher ?.
  29. How to do Session Management in JSP and Servlets using its methods and API ?.
  30. How to forward a request from one Jsp to another Jsp ?.
  31. How to include one JSP into another JSP ?.
  32. How to use Jsp action elements useBean, setProperty and getProperty to add, set and get property of a bean in a JSP page ?.
  33. How to decorate form in a JSP using fieldset and legend tag ?.
  34. How to write a Servlet code to download a Jar or file from the Server at a specified location ?.
  35. How to use Servlets Initialization Parameters through ServletConfig object in Java EE Application ?.
  36. How to use Context Parameters in Servlets through ServletContext object in Java EE Application ?.
  37. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  38. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  39. How to use Arithmetic Operations in Expression Language ( el ) in a simple jsp page ?.
  40. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  41. How to use param implicit object in a JSP page ?.




How to convert temperature degrees Fahrenheit to degrees Celsius and degrees Celsius to degrees Fahrenheit in a Java program ?.

Program to demonstrate how to convert temperature degrees Fahrenheit to degrees Celsius and degrees Celsius to degrees Fahrenheit in Java.

import java.util.Scanner;

public class TemperatureConversion {

 public static void main(String[] args) {

  // Creating a Scanner object using a constructor
  // which takes the System.in object. There are various
  // constructors for Scanner class for different
  // purposes. We want to use Scanner class to read
  // data from console on the system, So we are using
  // a constructor which is taking an System.in object
  Scanner scanner = new Scanner(System.in);

  // Prompt the user to enter temperature in Fahrenheit
  System.out.print("Enter temperature in Fahrenheit : ");

  double fahrenheit = scanner.nextDouble(); 

  // Convert Fahrenheit temperature to Celsius temperature
  // Formula : Celsius = (5/9)*(Fahrenheit - 32)

  double celsius = (5.0 / 9.0) * (fahrenheit - 32);

  // Displaying conversion on the console.
  System.out.println(fahrenheit + " degrees Fahrenheit is equal to " 
    + celsius + " degrees Celsius");

  System.out.println();

  // Prompt the user to enter temperature in Celsius
  System.out.print("Enter temperature in Celsius : ");

  celsius = scanner.nextDouble(); 

  // Convert Celsius temperature to Fahrenheit temperature
  // Formula : Fahrenheit = (9/5)*(Celsius + 32)

  fahrenheit = (9.0 / 5.0) * celsius + 32;

  // Displaying conversion on the console.
  System.out.println(celsius + " degrees Celsius is equal to " 
    + fahrenheit + " degrees Fahrenheit");
 }

}



Output of the program : 

 

Spring Framework in Java

  1. How to create BeanFactory using XmlBeanFactory in Spring Framework ?.
  2. How to provide default constructor initialization to a bean using Spring Framework ?.
  3. How to provide constructor initialization to a bean using type attribute in configuration file of Spring Framework ?.
  4. How to Create ApplicationContext with ClassPathXmlApplicationContext in Spring Framework ?.
  5. How to set properties of a bean using Spring xml configuration file in Spring Framework ?.
  6. How to provide constructor initialization to a bean using constructor-arg tag in configuration file of Spring Framework ?.
  7. How to provide constructor initialization to a bean using index attribute in configuration file of Spring Framework ?.
  8. How to provide object dependency injection to a bean using Configuration file in Spring Framework ?.
  9. How to work with Inner beans using configuration file in a Spring Framework ?.
  10. How to create a loosely coupled Java application using Spring Frameworks Dependency Injection ?.
  11. What are various Namespaces in the Spring Configuration File ?.
  12. How to provide constructor initialization to a bean using name attribute in configuration file of Spring Framework ?.
  13. How to use init-method and destroy-method attributes in Spring Configuration file ?.
  14. How to use InitializingBean and DisposableBean interface for initializing and destroying a bean in Spring Framework  ?.
  15. How AutoWiring works in Spring Framework ?
  16. How to turn on Annotations in Spring Configuration file ?
  17. How to turn on Auto Scanning of Spring Components for automatic scanning, detecting and instantiating the beans ?.
  18. How to use @Qualifier annotation in Spring Framework in making bean qualify to auto-wire from multiple beans ?.
  19. How to use @Component annotation for automatically configuring a Spring bean without using configuration xml file ?.
  20. How to perform Autowiring in Spring Framework using Annotations ?
  21. How to filter components in Spring Framework using include-filter and exclude-filter tag ?.
  22. How to use required attribute in @Autowired annotation in Spring Framework for Dependency Checking ?.
  23. How to use aliases when referring to a bean in configuration file of Spring Framework ?.
  24. How to use @Inject annotation in Spring Framework for Dependency Injection ?.
  25. How to use Java based configuration in Spring Framework without using XML based configuration ?.
  26. How to implement Before Advice using Classic Spring Proxy-Based AOP in Java ?.
  27. How to implement After Advice using @AspectJ Annotation-Driven AOP in Java ?.
  28. How to implement After Returning Advice using Classic Spring Proxy-Based AOP in Java ?.
  29. How to implement After Throwing Advice using Classic Spring Proxy-Based AOP in Java ?.
  30. How to implement Around Advice using Classic Spring Proxy-Based AOP in Java ?.
  31. How to implement Around Advice using @AspectJ Annotation-Driven AOP in Java ?.
  32. How to implement After Throwing Advice using @AspectJ Annotation-Driven AOP in Java ?.
  33. How to implement Before Advice using @AspectJ Annotation-Driven AOP in Java ?.
  34. How to implement After Returning Advice using @AspectJ Annotation-Driven AOP in Java ?.  
  35. @Required Annotation in Spring Framework

Design Patterns in Java

  1. A simple demonstration of State Design Pattern in Java through a program.
  2. A simple demonstration of Strategy Design Pattern in Java through a program.
  3. How to implement Singleton Design Pattern in java with a simple program ?
  4. How to implement Factory Design Pattern in Java with a simple program ?
  5. How to implement Adapter Design Pattern in Java with a Real World scenario ?.
  6. How to implement Dynamic Proxy Design Pattern in Java ?.
  7. How to implement Abstract Factory Design Pattern in Java ?.
  8. How to implement Chain Of Responsibility Design Pattern in Java using simple example ?.
  9. How to implement Command Design Pattern in Java using simple example ?.
  10. How to make a class singleton in Java using Singleton Design Pattern ?.
  11. How to implement Prototype Design Pattern in Java ?.
  12. How to implement Factory Design Pattern in Java ?.
  13. How to implement Builder Design Pattern in Java ?.
  14. How to implement Composite Design Pattern in Java ?.
  15. How to implement Iterator Design Pattern in Java ?.
  16. Decorator Design Pattern in Java
  17. Observer Design Pattern in Java


How to Calculate Area and Perimeter of Rectangle in a Java Program

Program to demonstrate how to Calculate Area and Perimeter of Rectangle in Java.



 

package com.hubberspot.example;

// Import java.util.Scanner to read data from
// console
import java.util.Scanner;

public class RectangleAreaPerimeterDemo {

 public static void main(String[] args) {

  // Creating a Scanner object using a constructor
  // which takes the System.in object. There are various
  // constructors for Scanner class for different
  // purposes. We want to use Scanner class to read
  // data from console on the system, So we are using
  // a constructor which is taking an System.in object
  Scanner scanner = new Scanner(System.in);

  // Create three variables which will hold the
  // values for length, breadth , area and perimeter of Rectangle.
  int length = 0;
  int breadth = 0;
  int area = 0;
  int perimeter = 0;

  // prompt the user to enter value of length of
  // Rectangle 
  System.out.print("Enter the length of Rectangle : ");

  // store the length into length variable entered by user
  length = scanner.nextInt();

  // prompt the user to enter value of breadth of
  // Rectangle
  System.out.print("Enter the breadth of Rectangle : ");

  // store the breadth into breadth variable entered by user
  breadth = scanner.nextInt();

  // Calculate area of Rectangle by multiplying length into breadth.
  area = length * breadth;

  // Calculate perimeter of Rectangle by 2 * (length + breadth)
  perimeter = 2 * (length + breadth);

  // Output area and perimeter to the console
  System.out.println("Area of Rectangle is : " + area);
  System.out.println("Perimeter of Rectangle is : " + perimeter);
 }
}


Output of the program : 


 

Collections Framework API

  1. How to use ArrayList in Java with example ?.
  2. How to use Iterator Interface to iterate/traverse Java Collections ?.
  3. How to perform operations of Union and Intersection on two or more LinkedList in Java ?.
  4. How to implement ListIterator Interface in Java Collections ?.
  5. How to use Vector in Java with example ?.
  6. How to implement Comparator Interface in Java with an example ?
  7. How to use LinkedList in Java with example ?.
  8. How to use TreeSet in Java with example ?.
  9. How to use HashSet in Java with example ?.
  10. How to use Hashtable in Java with example ?.
  11. How to sort and partial sort a primitive arrays using Arrays.sort method in Java ?.
  12. How to perform Binary Search for an element over primitive arrays in Java ?
  13. A simple Java program to sort elements in an ArrayList
  14. How to create Generic Type specific Collections in Java ?
  15. How to hold your objects using Collection Interface in Java ?
  16. How do I add an element and get an element in an ArrayList at specified index in Java ?.
  17. How to add or group one collection into another collection in Java ?.
  18. How to print collections in the Collections Framework on the console in Java ?.
  19. How to compare two or more arrays equality in Java ?.
  20. How to convert an Array into a Set in Java ?.
  21. How to check whether an ArrayList contains an element specified in Java ?.

Database Programming in Java

How to override and implement the hashCode and equals method in Java ?.

Program to demonstrate how to override and implement the hashCode and equals method in Java.

import java.util.Date;

// 1. Create Employee class
public class Employee {

 // 2. Define three properties of Employee
 // as age, name and dateOfBirth.
 private int age;
 private String name;
 private Date dateOfBirth;

 // 3. Create a Employee constructor setting three properties.
 public Employee(int age, String name, Date dateOfBirth){
  this.age = age;
  this.name = name;
  this.dateOfBirth = dateOfBirth;
 }

 // 4. Overriding equals method into the Employee class.
 @Override
 public boolean equals(Object object) {

  boolean isEquals = false;

  if(this == object){ 
   isEquals = true;
  }

  if(null == object || this.getClass() != object.getClass()){ 
   isEquals = false;
  }

  Employee employee = (Employee) object;

  if((this.age == employee.age) &&  
    (null != this.name && this.name.equals(employee.name)) &&
    (null != this.dateOfBirth && this.dateOfBirth.equals(employee.dateOfBirth))){

   isEquals = true;

  }
  return isEquals;

 }

 // 5. Overriding hashCode() mehtod in the Employee class.
 @Override
 public int hashCode() {
  int hashCode = 10;
  hashCode = (31 * hashCode) + age;
  hashCode = (31 * hashCode) + (name != null ? name.hashCode() : 0);
  hashCode = (31 * hashCode) + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
  return hashCode;
 }

 public static void main(String[] args) {

  Employee employee1 = new Employee(30, "Dinesh", new Date(1987, 12, 1));
  Employee employee2 = new Employee(31, "Jimmy", new Date(1989, 11, 2));
  Employee employee3 = new Employee(30, "Dinesh", new Date(1987, 12, 1));

  System.out.println("employee1.hashCode() = " + employee1.hashCode());
  System.out.println("employee2.hashCode() = " + employee2.hashCode());
  System.out.println("employee1.equals(employee2) = " + employee1.equals(employee2));

  System.out.println("employee1.hashCode() = " + employee1.hashCode());
  System.out.println("employee3.hashCode() = " + employee3.hashCode());
  System.out.println("employee1.equals(employee3) = " + employee1.equals(employee3));

  System.out.println("employee2.hashCode() = " + employee2.hashCode());
  System.out.println("employee3.hashCode() = " + employee3.hashCode());
  System.out.println("employee2.equals(employee3) = " + employee2.equals(employee3));

 }

}



Output of the program : 

 



Video tutorial to demonstrate how to override hashcode method in Java.








Video tutorial to demonstrate how to override equals method in Java.








Arrays in Java

Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot