Hibernate
Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables. It liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.
This article discusses the following:
History and Background
How Hibernate Works
When to Use Hibernate
Learning More
History and Background
Most applications have some need to work with data. Java applications, when running, tend to encapsulate data as networks of interconnected objects, but those objects vanish in a puff of logic when the program ends, so there needs to be some way to store them. And sometimes the data is already "out there" before the application is even written, so there needs to be a way to read it in and represent it as objects. Writing code by hand to perform these tasks is tedious and error-prone, and can represent a major portion of the effort involved in the overall application.
As good object-oriented developers got tired of this repetitive work, their typical tendency towards enlightened laziness started to manifest itself in the creation of tools to help automate the process. When working with relational databases, the culmination of such efforts were object/relational mapping tools.
There have been a variety of such tools, ranging from expensive commercial offerings to the EJB standards built into J2EE. In many cases, however, the tools introduce their own complexity, force the developer to learn detailed rules for using them, and to modify the classes making up their applications to conform to the needs of the mapping system. As the tools evolved to handle ever more rigorous and complex enterprise requirements, the intricacies required to use them started to overwhelm the savings you could obtain by doing so in simpler, common cases. This has led to something of a revolution favoring more lightweight solutions, of which Hibernate is an example.
How Hibernate Works
Hibernate doesn't get in your way; nor does it force you to change the way your objects behave. They don't need to implement any magical interfaces in order to be blessed with the ability to persist. All you need to do is create an XML "mapping document" telling Hibernate the classes you want to be able to store in a database, and how they relate to the tables and columns in that database, and then you can ask it to fetch data as objects, or store objects as data for you. Compared to most of the alternatives, it's almost magical.
There isn't room in an introductory article like this to work through a concrete example of building and using a Hibernate mapping document (that's what the first couple of chapters in my Hibernate: A Developer's Notebook are for, after all). And there are some good examples already on the Web and in the Hibernate online documentation; see "Learning More," on page 2. It really is straightforward, though. Properties in the application objects are associated with appropriate database structures in a simple, natural way.
At runtime, Hibernate reads the mapping document and dynamically builds Java classes to manage the translation between the database and Java worlds. There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database. To change those objects you just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; you just create them in the normal way and tell Hibernate about them so they can get stored to the database.
The Hibernate API is simple to learn and interacts quite naturally with the flow of your program. You invoke it in sensible places, and it does what you'd like it to. The benefits it brings in terms of automation and code savings greatly outweigh the short time it takes to learn. And you get an additional bonus in that your code doesn't care (or even have to know) what kind of database you're using. My company has had projects forced to change database vendors late in the development process. This can be a horrible mess, but with Hibernate it has required nothing more than a single change to the Hibernate configuration file.
This discussion has assumed that you already had a relational database set up, as well as Java classes to map, through the creation of the Hibernate mapping document. There is a Hibernate "toolset" that works at build time to support different workflows. For example, if you've got the Java classes and mapping document, Hibernate can create (or update) the necessary database tables for you. Or, starting with just the mapping document, Hibernate can generate the data classes for you, too. Or it can reverse engineer your database and classes to sketch out a mapping document for you. There are also some alpha plugins for Eclipse to provide intelligent editing support and graphical access to these tools right from within the IDE.
If you're in a Hibernate 2 environment, fewer of these tools are provided, but there are third-party options available.
Thursday, February 26, 2009
What is JDBC?
JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems.
Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.
Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.
Labels:
JDBC
Accessing EJB In JBoss From Swing Client
This articles shows how to access a simple stateless session bean in EJB 3.0 from a Swing client. Though it sounds like a simple process, it needs good number of steps. You need to use good number or .jar files and properties to access ejb 3.0 from a remote client.
At the end of this article you will have learnt how to do the following:
Creating a simple stateless session bean using JBoss and NetBeans.
Getting access to Naming Service of JBoss from remote client
Using appropriate .jar file of JBoss to access an EJB deployed in JBoss from a remote client.
Creating a simple stateless session bean in JBoss with NetBeans
Follow the steps and code given below to create a stateless session bean with a single method. I use JBoss as the EJB Container and NetBeans IDE.
First configure NetBeans to use JBoss as application server using Tools ->Server Manager option of NetBeans.
Create a new project using File->New Project
Select Enterprise as category and EJB Module as type of project
Enter HelloEJB as the name of the project
Select Stateless and type of EJB and Remote as the interface
NetBeans provides - HelloRemote.java and HelloBean.java
Go to HelloBean.java. Invoke popup menu (right click) and select EJB Methods->Add Business Method
Enter sayHello as name of the method and String as return type
Write the code shown below. At the end of the process HelloRemote.java and HelloBean.java should be as shown below.
// HelloRemote.java
package st;
import javax.ejb.Remote;
@Remote
public interface HelloRemote {
String sayHello();
}
// HelloBean.java
package st;
import javax.ejb.Stateless;
@Stateless
public class HelloBean implements HelloRemote {
public HelloBean() {
}
public String sayHello() {
return "Hello";
}
}
Go to Projects window using Window->Projects
Right click on project name to invoke popup menu and select Deploy Project option to deploy project
Creating Swing Client
Now, let us create a frame-based swing application to access EJB. This swing application runs on its own and not in JBoss. So, it is called as remote client to EJB. Client project needs to have access to a couple of .jar files to access to JBoss and EJB deployed in JBoss.
Take the following steps related to client:
Create a new project using File->New Project
Select General in category and Java Application as project type
Give project name as SwingClient
Select the project (SwingClient) in Projects window. Go to libraries node, right click and select Add Jar/Folder .
Add the following libraries (.jar files) to SwingClient project.
HelloEjb.jar - Jar file of HelloEJB application. This is found in dist directory of the project
jboss-ejb3-client.jar, jboss-aop-jdk50-client.jar, jboss-aspect-jdk50-client.jar and jbossall-client.jar - all these .jar files are found in client folder of JBoss installation directory( For ex, d:\jboss)
Add a Java class (HelloClient) to project using File->New File, select Java Classes in categories and Java Class as File Type
Write the following code in HelloClient.java
import java.util.Properties;
import javax.naming.InitialContext;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import st.HelloRemote;
public class HelloClient extends JFrame {
public HelloClient() {
super("Hello Client");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JButton b1 = new JButton("Access EJB");
getContentPane().add(b1, BorderLayout.PAGE_END);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String msg = "";
try {
// Access JNDI Initial Context.
Properties p = new Properties();
p.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
p.put("java.naming.provider.url","jnp://localhost:1099");
p.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
InitialContext ctx = new InitialContext(p);
// Change jndi name according to your server and ejb
HelloRemote remote = (HelloRemote) ctx.lookup("HelloBean/remote");
msg = "Message From EJB --> " + remote.sayHello();
}
catch(Exception ex){
msg = "Error --> " + ex.getCause().toString();
}
JOptionPane.showMessageDialog(HelloClient.this,msg,"Message", JOptionPane.INFORMATION_MESSAGE);
}
});
setSize(200,200);
} //
public static void main(String args[]) {
new HelloClient().setVisible(true);
}
}
Run HelloClient class by selecting Run File option from popup menu (right click).
Click on Access EJB button and you must see a message dialog with message coming from ejb - Hello.
I hope this article helps you to understand how to access an EJB deployed in JBoss from a remote client. Remote client may be a swing application, a console application or a web application.
At the end of this article you will have learnt how to do the following:
Creating a simple stateless session bean using JBoss and NetBeans.
Getting access to Naming Service of JBoss from remote client
Using appropriate .jar file of JBoss to access an EJB deployed in JBoss from a remote client.
Creating a simple stateless session bean in JBoss with NetBeans
Follow the steps and code given below to create a stateless session bean with a single method. I use JBoss as the EJB Container and NetBeans IDE.
First configure NetBeans to use JBoss as application server using Tools ->Server Manager option of NetBeans.
Create a new project using File->New Project
Select Enterprise as category and EJB Module as type of project
Enter HelloEJB as the name of the project
Select Stateless and type of EJB and Remote as the interface
NetBeans provides - HelloRemote.java and HelloBean.java
Go to HelloBean.java. Invoke popup menu (right click) and select EJB Methods->Add Business Method
Enter sayHello as name of the method and String as return type
Write the code shown below. At the end of the process HelloRemote.java and HelloBean.java should be as shown below.
// HelloRemote.java
package st;
import javax.ejb.Remote;
@Remote
public interface HelloRemote {
String sayHello();
}
// HelloBean.java
package st;
import javax.ejb.Stateless;
@Stateless
public class HelloBean implements HelloRemote {
public HelloBean() {
}
public String sayHello() {
return "Hello";
}
}
Go to Projects window using Window->Projects
Right click on project name to invoke popup menu and select Deploy Project option to deploy project
Creating Swing Client
Now, let us create a frame-based swing application to access EJB. This swing application runs on its own and not in JBoss. So, it is called as remote client to EJB. Client project needs to have access to a couple of .jar files to access to JBoss and EJB deployed in JBoss.
Take the following steps related to client:
Create a new project using File->New Project
Select General in category and Java Application as project type
Give project name as SwingClient
Select the project (SwingClient) in Projects window. Go to libraries node, right click and select Add Jar/Folder .
Add the following libraries (.jar files) to SwingClient project.
HelloEjb.jar - Jar file of HelloEJB application. This is found in dist directory of the project
jboss-ejb3-client.jar, jboss-aop-jdk50-client.jar, jboss-aspect-jdk50-client.jar and jbossall-client.jar - all these .jar files are found in client folder of JBoss installation directory( For ex, d:\jboss)
Add a Java class (HelloClient) to project using File->New File, select Java Classes in categories and Java Class as File Type
Write the following code in HelloClient.java
import java.util.Properties;
import javax.naming.InitialContext;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import st.HelloRemote;
public class HelloClient extends JFrame {
public HelloClient() {
super("Hello Client");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JButton b1 = new JButton("Access EJB");
getContentPane().add(b1, BorderLayout.PAGE_END);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String msg = "";
try {
// Access JNDI Initial Context.
Properties p = new Properties();
p.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
p.put("java.naming.provider.url","jnp://localhost:1099");
p.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
InitialContext ctx = new InitialContext(p);
// Change jndi name according to your server and ejb
HelloRemote remote = (HelloRemote) ctx.lookup("HelloBean/remote");
msg = "Message From EJB --> " + remote.sayHello();
}
catch(Exception ex){
msg = "Error --> " + ex.getCause().toString();
}
JOptionPane.showMessageDialog(HelloClient.this,msg,"Message", JOptionPane.INFORMATION_MESSAGE);
}
});
setSize(200,200);
} //
public static void main(String args[]) {
new HelloClient().setVisible(true);
}
}
Run HelloClient class by selecting Run File option from popup menu (right click).
Click on Access EJB button and you must see a message dialog with message coming from ejb - Hello.
I hope this article helps you to understand how to access an EJB deployed in JBoss from a remote client. Remote client may be a swing application, a console application or a web application.
Labels:
EJB
Web Service with AXIS
This article shows how to use AXIS from Apache to host Web Services using Tomcat5.
What is Web Service?
Web service is a collection of methods that can be accessed over internet using SOAP (Simple Object Access Protocol). SOAP itself is making use of HTTP and XML to encode and trasfer data.
Web services are interoperable , which means a Web service created in Java can be accessed from .NET and vice-versa.
What is AXIS?
AXIS is SOAP engine which works on server and client. It allows Java classes to be deployed as Web services so that they can be accessed from anywhere.
AXIS stands for Apache Extensible Interaction System. It is an open-source project and implements standard JAX-RPC API of Java.
How to install Axis?
Axis must be downloaded from axis.apache.org. It comes as a simple .zip file axis-bin-1_3.zip Extract this zip file to D drive will result in a folder with the name d:\axis-1_3.
Copy axis directory of d:\axis-1_3\webapps into webapps directory of Tomcat5.
Start Tomcat and test whether the Axis web application is running using http://localhost:8080/axis . Please change port number 8080 with port number that you use for Tomcat in your system.
Test whether Axis has access to all required libraries by using http://localhost:8080/axis/happyaxis.jsp. If any core libraries are missing, make sure you copy them to either WEB-INF/lib directory of Axis or common\lib directory of Tomcat.
Creating and comsuming a simple Web service
The following procedure explains how to create a invoke a simple web service, which has a single method sayHello().
Create the following class and place it in axis directory under the name Hello.jws.
public class Hello
{
public String sayHello( String name)
{
return "Hello," + name;
}
}
Test the web service by giving the url http://localhost:8080/axis/Hello.jws.
You must see the message saying that there is a web service installed. Click on wsdl hyperlink to see WSDL for the service.
Once service is deployed successfully then run the client by first setting the CLASSPATH and PATH as follows:
set AXIS_HOME=d:\axis-1_3
set AXIS_LIB=%AXIS_HOME%\lib
set AXISCLASSPATH=.;%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar
set classpaht=.;%classpath%;%AXISCLASSPATH%
path c:\jdk1.5.0\bin
You have to copy xercesimpl.jar and xml-apis.xml or something similar to it must be copied into lib directory of d:\axis-1_3.
HelloClient.java is the client program to access web serice.
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
public class HelloClient
{
public static void main(String args[]) throws Exception
{
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( "http://localhost:8080/axis/Hello.jws");
call.setOperationName("sayHello");
Object ret = call.invoke( new Object[] {"Srikanth"} );
String res = (String) ret;
System.out.println(res);
}
}
Then complie and run the following client.
javac HelloClient.java
java HelloClient
You must see message saying Hello,Srikanth. If you get any warning regarding Log4j, ignore them.
Installing a Web service by just copying .jws file into axis directory is called as drop-in deployment.
Deploying Web Serice using Custom deployment
The following example demonstrates how to deploy a web serice using a .class of Java. We want to expose a few methods (or all) of a Java class as web methods in web service. This can be done by the following procedure:
Create Hello.java as follows:
public class Hello
{
public String sayHello( String name)
{
return "Hello," + name;
}
}
Compile Hello.java and copy Hello.class into WEB-INF/classes directory of axis application in Tomcat.
Create Hello.wsdd , which contains details of the sercice as follows:
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
Run AdminClient to deploy service in Hello.wsdd as follows:
java org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd
Test web service by using http://localhost:8080/axis/services/hello. You must see a page saying this is a web service.
Create the HelloClient.java as follows:
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
public class HelloClient
{
public static void main(String args[]) throws Exception
{
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( "http://localhost:8080/axis/services/hello");
call.setOperationName("sayHello");
Object ret = call.invoke( new Object[] {"Srikanth"} );
String res = (String) ret;
System.out.println(res);
}
}
Compile and run HelloClient to get call sayHello() method. The return value will be Hello,Srikanth .
Conclusion
Axis really made the process of creating and deploying web serice in Java very simple. All that you have to create a web service is Tomcat5.x and Axis and a Java compiler (J2SE 5.0).
For further information, refer to axis.apache.org. Also remember axis comes with full documenation in docs directory.
Click Currency Converter Example to see how to create a currency conveter web service and corresponding client.
What is Web Service?
Web service is a collection of methods that can be accessed over internet using SOAP (Simple Object Access Protocol). SOAP itself is making use of HTTP and XML to encode and trasfer data.
Web services are interoperable , which means a Web service created in Java can be accessed from .NET and vice-versa.
What is AXIS?
AXIS is SOAP engine which works on server and client. It allows Java classes to be deployed as Web services so that they can be accessed from anywhere.
AXIS stands for Apache Extensible Interaction System. It is an open-source project and implements standard JAX-RPC API of Java.
How to install Axis?
Axis must be downloaded from axis.apache.org. It comes as a simple .zip file axis-bin-1_3.zip Extract this zip file to D drive will result in a folder with the name d:\axis-1_3.
Copy axis directory of d:\axis-1_3\webapps into webapps directory of Tomcat5.
Start Tomcat and test whether the Axis web application is running using http://localhost:8080/axis . Please change port number 8080 with port number that you use for Tomcat in your system.
Test whether Axis has access to all required libraries by using http://localhost:8080/axis/happyaxis.jsp. If any core libraries are missing, make sure you copy them to either WEB-INF/lib directory of Axis or common\lib directory of Tomcat.
Creating and comsuming a simple Web service
The following procedure explains how to create a invoke a simple web service, which has a single method sayHello().
Create the following class and place it in axis directory under the name Hello.jws.
public class Hello
{
public String sayHello( String name)
{
return "Hello," + name;
}
}
Test the web service by giving the url http://localhost:8080/axis/Hello.jws.
You must see the message saying that there is a web service installed. Click on wsdl hyperlink to see WSDL for the service.
Once service is deployed successfully then run the client by first setting the CLASSPATH and PATH as follows:
set AXIS_HOME=d:\axis-1_3
set AXIS_LIB=%AXIS_HOME%\lib
set AXISCLASSPATH=.;%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar
set classpaht=.;%classpath%;%AXISCLASSPATH%
path c:\jdk1.5.0\bin
You have to copy xercesimpl.jar and xml-apis.xml or something similar to it must be copied into lib directory of d:\axis-1_3.
HelloClient.java is the client program to access web serice.
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
public class HelloClient
{
public static void main(String args[]) throws Exception
{
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( "http://localhost:8080/axis/Hello.jws");
call.setOperationName("sayHello");
Object ret = call.invoke( new Object[] {"Srikanth"} );
String res = (String) ret;
System.out.println(res);
}
}
Then complie and run the following client.
javac HelloClient.java
java HelloClient
You must see message saying Hello,Srikanth. If you get any warning regarding Log4j, ignore them.
Installing a Web service by just copying .jws file into axis directory is called as drop-in deployment.
Deploying Web Serice using Custom deployment
The following example demonstrates how to deploy a web serice using a .class of Java. We want to expose a few methods (or all) of a Java class as web methods in web service. This can be done by the following procedure:
Create Hello.java as follows:
public class Hello
{
public String sayHello( String name)
{
return "Hello," + name;
}
}
Compile Hello.java and copy Hello.class into WEB-INF/classes directory of axis application in Tomcat.
Create Hello.wsdd , which contains details of the sercice as follows:
Run AdminClient to deploy service in Hello.wsdd as follows:
java org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd
Test web service by using http://localhost:8080/axis/services/hello. You must see a page saying this is a web service.
Create the HelloClient.java as follows:
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
public class HelloClient
{
public static void main(String args[]) throws Exception
{
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( "http://localhost:8080/axis/services/hello");
call.setOperationName("sayHello");
Object ret = call.invoke( new Object[] {"Srikanth"} );
String res = (String) ret;
System.out.println(res);
}
}
Compile and run HelloClient to get call sayHello() method. The return value will be Hello,Srikanth .
Conclusion
Axis really made the process of creating and deploying web serice in Java very simple. All that you have to create a web service is Tomcat5.x and Axis and a Java compiler (J2SE 5.0).
For further information, refer to axis.apache.org. Also remember axis comes with full documenation in docs directory.
Click Currency Converter Example to see how to create a currency conveter web service and corresponding client.
Labels:
Web Services
Introduction To Struts
Introduction To Struts
Every now and then IT industry has come out with something new. It was Java in mid 90s and .NET in 2000 and so on. All these things changed the way programmers write programs.
Java changed the preception of programmer. It let programmers concentrate on application logic more than house-keeping issues like memory management and thread management.
.NET from Microsoft came in 2000 has provided a new platform for application development. We say we develop applications for .NET and not Windows.
J2EE is widely accepted by industry. Java has grown from strength to strength in both Web application development and enterprise application development. First came Servlets, then JSP, EJB and now Java Struts.
What is Java Struts?
If you are hearing this for first time then you are not alone. Not many know it as of now, but at the same time many use it.
Struts is used to develop web applications. It is a web application framework based on JSPs, Servlets and Java Beans.
Struts project was initiated in May,2000 by Craig R. McClanahan and in July,2001 Struts 1.0 was released.
In MVC (Model-view-Controller) design pattern, Controller acts as a mediator between View (presentation) and Model (data). Prior to Struts, MVC was implemented using JSPs. The entire development was JSP Centric. In Model 2 of MVC, we use Servlets and JSPs. JSPs take care of generating HTML (view) and Servlets take care of controlling the flow. Java Beans are used to contain model (data). Beans may take data from either a database or an EJB or any other conceivable source.
View - Presentation
View portion is handled in Struts using JSPs. Struts provide a set of custom tags, which internally generate HTML. The best part of it is these HTML pages can be very easily internationalized. It means the view portion can be in any language. It takes almost no time to shift an application from English to Spanish.
View portion handled by custom tags is intergarted with Model, which is represented by Java Bean.
Controller - controlling the flow
Controller portion is handled by Servlet. ActionServlet in Struts takes request and decides which action should take place. The Action component performs business logic and then transfer control to view portion for display.
What you need to use Struts?
The following are the component required to use Struts.
Jakarta Struts library.Download struts library 1.1 , which is 16 MB.
Tomcat 4.0 or highter
JDK 1.4 to compile Java Beans
Do the following after you install Jakarta Struts 1.1.
Unzip the .ZIP file into folder
Copy struts-documentaion.war from webapps directory of the folder into which you extracted ZIP file into webapps directory of Tomcat.
Start Tomcat server
Enter the url http://localhost:8080/struts-documentation. Struts documentation is provided as one of the sample web applications.
First application
I have developed a simple Struts application. Download first.zip and extract it into webapps directory of Tomcat. Then start tomcat and run the url http://localhost:8080/first to see the sample application in action.
Java struts provides a few sample applications to demonstrate Struts. However, my application (first) will give an overview of struts without overwhelming you.
Every now and then IT industry has come out with something new. It was Java in mid 90s and .NET in 2000 and so on. All these things changed the way programmers write programs.
Java changed the preception of programmer. It let programmers concentrate on application logic more than house-keeping issues like memory management and thread management.
.NET from Microsoft came in 2000 has provided a new platform for application development. We say we develop applications for .NET and not Windows.
J2EE is widely accepted by industry. Java has grown from strength to strength in both Web application development and enterprise application development. First came Servlets, then JSP, EJB and now Java Struts.
What is Java Struts?
If you are hearing this for first time then you are not alone. Not many know it as of now, but at the same time many use it.
Struts is used to develop web applications. It is a web application framework based on JSPs, Servlets and Java Beans.
Struts project was initiated in May,2000 by Craig R. McClanahan and in July,2001 Struts 1.0 was released.
In MVC (Model-view-Controller) design pattern, Controller acts as a mediator between View (presentation) and Model (data). Prior to Struts, MVC was implemented using JSPs. The entire development was JSP Centric. In Model 2 of MVC, we use Servlets and JSPs. JSPs take care of generating HTML (view) and Servlets take care of controlling the flow. Java Beans are used to contain model (data). Beans may take data from either a database or an EJB or any other conceivable source.
View - Presentation
View portion is handled in Struts using JSPs. Struts provide a set of custom tags, which internally generate HTML. The best part of it is these HTML pages can be very easily internationalized. It means the view portion can be in any language. It takes almost no time to shift an application from English to Spanish.
View portion handled by custom tags is intergarted with Model, which is represented by Java Bean.
Controller - controlling the flow
Controller portion is handled by Servlet. ActionServlet in Struts takes request and decides which action should take place. The Action component performs business logic and then transfer control to view portion for display.
What you need to use Struts?
The following are the component required to use Struts.
Jakarta Struts library.Download struts library 1.1 , which is 16 MB.
Tomcat 4.0 or highter
JDK 1.4 to compile Java Beans
Do the following after you install Jakarta Struts 1.1.
Unzip the .ZIP file into folder
Copy struts-documentaion.war from webapps directory of the folder into which you extracted ZIP file into webapps directory of Tomcat.
Start Tomcat server
Enter the url http://localhost:8080/struts-documentation. Struts documentation is provided as one of the sample web applications.
First application
I have developed a simple Struts application. Download first.zip and extract it into webapps directory of Tomcat. Then start tomcat and run the url http://localhost:8080/first to see the sample application in action.
Java struts provides a few sample applications to demonstrate Struts. However, my application (first) will give an overview of struts without overwhelming you.
Labels:
Struts
Custom tags and JSPs interaction
Custom tags are not new to any JSP programmer. In this article, I would like to create a custom tag that demonstrates how a custom tag interacts with JSP using attributes.
In case you are new to custom tags in JSP 2.0, see article Creating and using custom tags.
I will create a custom tag called , which takes an SQL query and makes data retrieved by the query available to JSP through attributes.The following are the steps to be taken to develop this tag and use it.
The first step is to create the tag handler as follows:
package st;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class QueryHandler extends SimpleTagSupport {
private String sql;
public void doTag() throws JspException {
JspWriter out=getJspContext().getOut();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
JspContext ctx = getJspContext();
// get data related to ResultSet
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
JspFragment f=getJspBody();
while ( rs.next()) {
for(int i = 1 ; i <= count ; i ++ ) {
// Create an attribute for each column.
// Column name is attribute name and value is attribute's value.
ctx.setAttribute( rsmd.getColumnName(i), rs.getString(i));
}
// process the body of the tag and send result to JSPWriter
f.invoke(out);
}
rs.close();
con.close();
} catch (Exception ex) {
throw new JspException(ex.getMessage());
}
}
// attribute sql
public void setSql(java.lang.String value) {
this.sql = value;
}
}
In the above Tag Handler, we use SQL query passed through attribute sql to retrieve data. The data is placed in ResultSet. For each row of the ResultSet we create a set of attributes - one for each column. The name of the attribute is column name and value is column's value. To get names of columns we have to get ResultSetMetaData object from ResultSet.
NOTE : The column names are in uppercase. So even the attribute names are in uppercase. In case you want to create attributes with lowercase names, use toLowerCase() method of String class as follows:
ctx.setAttribute( rsmd.getColumnName(i).toLowerCase() , rs.getString(i));
The following is tab library descriptor (st.tld) for the above tag.
1.0
Srikanth Technologies Tags
/WEB-INF/tlds/st
query
st.QueryHandler
scriptless
sql
true
true
java.lang.String
Now, let us register st.tld in a JSP using taglib directive and use tag. The following JSP shows how to use it.
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/tlds/st.tld" prefix="st"%>
"http://www.w3.org/TR/html4/loose.dtd">
Using Query Tag
First usage of query tag is to retreive details from DEPARTMENTS table. Attributes DEPARTMENT_ID and DEPARTMENT_NAME are created from tag handler. Those attributes are used in JSP using Expression Langauge (EL) syntax. By making data available using attributes, we allow JSP to display data in the way it wants. It is demonstrated by second usage of tag as we used a table to display the data of attributes.
This article shows how to make use of the following:
Creating a custom tag using JSP 2.0 simple tag technique
Getting Connection to Oracle . Make sure you make JDBC driver available to web application.
Using ResultSet and ResultSetMetaData to get information about ResultSet
Creating page attributes in custom tag to make data available to JSP in which tag is used
Using attributes created by custom tag with expression language
The concept of custom tags is very powerful. JSTL, JSF and even frameworks such as Struts make use of custom tags extensively. So, it is worth understanding how custom tags and JSPs interact.
In case you are new to custom tags in JSP 2.0, see article Creating and using custom tags.
I will create a custom tag called
The first step is to create the tag handler as follows:
package st;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class QueryHandler extends SimpleTagSupport {
private String sql;
public void doTag() throws JspException {
JspWriter out=getJspContext().getOut();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
JspContext ctx = getJspContext();
// get data related to ResultSet
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
JspFragment f=getJspBody();
while ( rs.next()) {
for(int i = 1 ; i <= count ; i ++ ) {
// Create an attribute for each column.
// Column name is attribute name and value is attribute's value.
ctx.setAttribute( rsmd.getColumnName(i), rs.getString(i));
}
// process the body of the tag and send result to JSPWriter
f.invoke(out);
}
rs.close();
con.close();
} catch (Exception ex) {
throw new JspException(ex.getMessage());
}
}
// attribute sql
public void setSql(java.lang.String value) {
this.sql = value;
}
}
In the above Tag Handler, we use SQL query passed through attribute sql to retrieve data. The data is placed in ResultSet. For each row of the ResultSet we create a set of attributes - one for each column. The name of the attribute is column name and value is column's value. To get names of columns we have to get ResultSetMetaData object from ResultSet.
NOTE : The column names are in uppercase. So even the attribute names are in uppercase. In case you want to create attributes with lowercase names, use toLowerCase() method of String class as follows:
ctx.setAttribute( rsmd.getColumnName(i).toLowerCase() , rs.getString(i));
The following is tab library descriptor (st.tld) for the above tag.
Now, let us register st.tld in a JSP using taglib directive and use
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/tlds/st.tld" prefix="st"%>
"http://www.w3.org/TR/html4/loose.dtd">
Query
- ${DEPARTMENT_ID}, ${DEPARTMENT_NAME}
Title | Min Salary |
---|---|
${JOB_TITLE} | ${MIN_SALARY} |
First usage of query tag is to retreive details from DEPARTMENTS table. Attributes DEPARTMENT_ID and DEPARTMENT_NAME are created from tag handler. Those attributes are used in JSP using Expression Langauge (EL) syntax. By making data available using attributes, we allow JSP to display data in the way it wants. It is demonstrated by second usage of
This article shows how to make use of the following:
Creating a custom tag using JSP 2.0 simple tag technique
Getting Connection to Oracle . Make sure you make JDBC driver available to web application.
Using ResultSet and ResultSetMetaData to get information about ResultSet
Creating page attributes in custom tag to make data available to JSP in which tag is used
Using attributes created by custom tag with expression language
The concept of custom tags is very powerful. JSTL, JSF and even frameworks such as Struts make use of custom tags extensively. So, it is worth understanding how custom tags and JSPs interact.
Labels:
JSP
Creating a Servlet without any IDE
In this article, I want to show how to create a simple servlet without using any IDE like NetBeans or Eclipse. I will use Tomcat 6.0 and Notepad to create a simple test servlet and run it.
The article assumes, you have JDK 5.0/6.0 and Tomcat 6.0.
The following are the steps to be taken by you to create a simple servlet.
Download Tomcat 6.0 from http://tomcat.apache.org
Install Tomcat 6.0 into c:\ApacheTomcat6.0
Go to webapps directory of Tomcat and create the following directory structure for demo application. Any directory placed with required structure of Java EE web application is treated as a web application by Tomcat.
demo
WEB-INF
classes
TestServlet.java
web.xml
Creating Servlet Source Code
The following is the code for TestServlet.java. It simply sends a message to browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}
Deployment Descriptor - web.xml
Create web.xml as follows. It is better you copy web.xml from some other application in Tomcat webapps directory instead of typing it from scratch. Make sure it is placed in WEB-INF (in uppercase) folder of demo application with the following content.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
TestServlet
TestServlet
TestServlet
/test
TestServlet is associated with url pattern /test in web.xml. From the client, we have to make request for url pattern /test.
Compiling Servlet
Go to classes directory, where .java file is placed as enter the following commands at the command prompt to compile the servlet.
path=d:\jdk1.6.0\bin
set classpath=.;c:\apachetomcat6.0\lib\servlet-api.jar
javac TestServlet.java
Make sure you change JDK and Tomcat directories according to your installation.
Set path to the directory where JDK is installed. Servlet-api.jar contains API related to servlet like HttpServlet, HttpServletRequest etc., so it must be placed in the classpath. Compile the servlet (.java) to create .class file.
Starting Tomcat and Running Servlet
Start Tomcat by taking the follwing steps from BIN directory of Tomcat.
set java_home=d:\jdk1.6.0
startup
Once, tomcat is successfully started, go to browser and enterer the following URL.
http://localhost:8080/demo/test
You must see the output as follows.
The article assumes, you have JDK 5.0/6.0 and Tomcat 6.0.
The following are the steps to be taken by you to create a simple servlet.
Download Tomcat 6.0 from http://tomcat.apache.org
Install Tomcat 6.0 into c:\ApacheTomcat6.0
Go to webapps directory of Tomcat and create the following directory structure for demo application. Any directory placed with required structure of Java EE web application is treated as a web application by Tomcat.
demo
WEB-INF
classes
TestServlet.java
web.xml
Creating Servlet Source Code
The following is the code for TestServlet.java. It simply sends a message to browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}
Deployment Descriptor - web.xml
Create web.xml as follows. It is better you copy web.xml from some other application in Tomcat webapps directory instead of typing it from scratch. Make sure it is placed in WEB-INF (in uppercase) folder of demo application with the following content.
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
TestServlet is associated with url pattern /test in web.xml. From the client, we have to make request for url pattern /test.
Compiling Servlet
Go to classes directory, where .java file is placed as enter the following commands at the command prompt to compile the servlet.
path=d:\jdk1.6.0\bin
set classpath=.;c:\apachetomcat6.0\lib\servlet-api.jar
javac TestServlet.java
Make sure you change JDK and Tomcat directories according to your installation.
Set path to the directory where JDK is installed. Servlet-api.jar contains API related to servlet like HttpServlet, HttpServletRequest etc., so it must be placed in the classpath. Compile the servlet (.java) to create .class file.
Starting Tomcat and Running Servlet
Start Tomcat by taking the follwing steps from BIN directory of Tomcat.
set java_home=d:\jdk1.6.0
startup
Once, tomcat is successfully started, go to browser and enterer the following URL.
http://localhost:8080/demo/test
You must see the output as follows.
Labels:
Servlet
Wednesday, February 25, 2009
Inheritance and Interfaces
What is inheritance?
Inheritance is the ability of objects in java to inherit properties and methods from other objects. When an object inherits from another object it can add its own properties and methods. The object that is being inherited from is called the parent or base class and the class that is inheriting from the parent is called the child or derived class.
How to use inheritance
We will first create a parent class called Person. We will then create a child class called Student. Then we will create a program to use the Student class. The following is a Person class which has a variable for the person's name. There are also set and get methods for the name.
class Person
{
private String name;
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
Now we will create the Student class that has a variable for the student number and the get and set methods for student number. The extends keyword is used to inherit from the Person class in the following example.
class Student extends Person
{
private String stuNum;
public void setStuNum(String sn)
{
stuNum = sn;
}
public String getStuNum()
{
return stuNum;
}
}
Finally we have to create a program that will instantiate a Student object, set the name and student number and then print the values using the get methods.
public class TestInheritance
{
public static void main(String[] args)
{
Student stu = new Student();
stu.setName("John Smith");
stu.setStuNum("12345");
System.out.println("Student Name: " + stu.getName());
System.out.println("Student Number: " + stu.getStuNum());
}
}
Abstract inheritance
Abstract classes are created only for the purpose of being inherited from. In fact you can't instantiate an object from an abstract class. You must put the abstract keyword in front of the class name declaration to create an abstract class. We can change the Person class above to show how it works.
abstract class Person
{
private String name;
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
Interfaces
Interfaces are like abstract classes because you can't instantiate them and they are only used for being inherited from. The difference is that interfaces are not allowed to have variables unless they are constants and methods are not allowed to have a body. The point of an interface is for you to override the methods that are declared in it. You must use the implements keyword instead of extends when using interfaces. Here is an example of the Person class as an interface and the Student class that uses the Person interface.
interface Person
{
public void setName(String n);
public String getName();
}
class Student implements Person
{
private String stuNum;
private String name;
public void setStuNum(String sn)
{
stuNum = sn;
}
public String getStuNum()
{
return stuNum;
}
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
Inheritance is the ability of objects in java to inherit properties and methods from other objects. When an object inherits from another object it can add its own properties and methods. The object that is being inherited from is called the parent or base class and the class that is inheriting from the parent is called the child or derived class.
How to use inheritance
We will first create a parent class called Person. We will then create a child class called Student. Then we will create a program to use the Student class. The following is a Person class which has a variable for the person's name. There are also set and get methods for the name.
class Person
{
private String name;
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
Now we will create the Student class that has a variable for the student number and the get and set methods for student number. The extends keyword is used to inherit from the Person class in the following example.
class Student extends Person
{
private String stuNum;
public void setStuNum(String sn)
{
stuNum = sn;
}
public String getStuNum()
{
return stuNum;
}
}
Finally we have to create a program that will instantiate a Student object, set the name and student number and then print the values using the get methods.
public class TestInheritance
{
public static void main(String[] args)
{
Student stu = new Student();
stu.setName("John Smith");
stu.setStuNum("12345");
System.out.println("Student Name: " + stu.getName());
System.out.println("Student Number: " + stu.getStuNum());
}
}
Abstract inheritance
Abstract classes are created only for the purpose of being inherited from. In fact you can't instantiate an object from an abstract class. You must put the abstract keyword in front of the class name declaration to create an abstract class. We can change the Person class above to show how it works.
abstract class Person
{
private String name;
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
Interfaces
Interfaces are like abstract classes because you can't instantiate them and they are only used for being inherited from. The difference is that interfaces are not allowed to have variables unless they are constants and methods are not allowed to have a body. The point of an interface is for you to override the methods that are declared in it. You must use the implements keyword instead of extends when using interfaces. Here is an example of the Person class as an interface and the Student class that uses the Person interface.
interface Person
{
public void setName(String n);
public String getName();
}
class Student implements Person
{
private String stuNum;
private String name;
public void setStuNum(String sn)
{
stuNum = sn;
}
public String getStuNum()
{
return stuNum;
}
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
Labels:
Core Java
Object-Oriented Programming
What is Object-Oriented Programming?
Object oriented programming or OOP is a way of writing programs using objects. An object is a data structure in memory that has attributes and methods. The attributes of an object are the same as variables and the methods of an object are the same as functions or procedures.
The reason for using objects instead of the old procedural method of programming is because objects group the variables and methods about something together instead of keeping them all apart as in procedural programming. There are many other reasons why OOP is better which you will learn about later.
Using classes and objects
Before you can create an object you need to create a class. A class is the code for an object and an object is the instance of a class in memory. When you create an object from a class it is called instantiating the object. To help you understand think of the plan for a house. The plan for the house is like the class and the house that will be built from the plan is the object.
Creating a class
You have already been creating classes in the programs you have written so far. To show you how they work we will need to create a separate class in a separate file. This class will be called Student.
public class Student
{
}
Now we will add 2 variables to the class which are the student's name and student number.
public class Student
{
String studentName;
int studentNumber;
}
Next we must add methods for getting and setting these variables.
public class Student
{
String studentName;
int studentNumber;
public void setStudentName(String s)
{
studentName = s;
}
public void setStudentNumber(int i)
{
studentNumber = i;
}
public String getStudentName()
{
return studentName;
}
public int getStudentNumber()
{
return studentNumber;
}
}
Instantiating an object
Now that we have finished writing the class we must create the main program that will instantiate the object. We will call the main program class TestClass. It should look just like how every other java program starts off.
public class TestClass
{
public static void main(String[] args)
{
}
}
Now we will instantiate the object. To do this we declare a reference to the object called stu and set it equal to a newly created object in memory.
public class TestClass
{
public static void main(String[] args)
{
Student stu = new Student();
}
}
Using the object
Now we can call the methods from the stu object to set the values of its variables. You can't set the values of the variables in an object unless they are declared as public. This makes it safer to work with variables because they can't be changed by mistake by another object.
public class TestClass
{
public static void main(String[] args)
{
Student stu = new Student();
stu.setStudentName("John Smith");
stu.setStudentNumber(12345);
System.out.println("Student Name: " + stu.getStudentName());
System.out.println("Student Number: " + stu.getStudentNumber());
}
}
Constructors
A constructor is a method that is run when an object is instantiated. Constructors are useful for initializing variables. The constructor is declared with only the name of the class followed by brackets. Here is an example of the Student class that initializes both student name and student number.
public class Student
{
String studentName;
int studentNumber;
Student()
{
studentName = "No name";
studentNumber = 1;
}
public void setStudentName(String s)
{
studentName = s;
}
public void setStudentNumber(int i)
{
studentNumber = i;
}
public String getStudentName()
{
return studentName;
}
public int getStudentNumber()
{
return studentNumber;
}
}
You can also pass parameters to a constructor when you instantiate an object. All you need to do is add the parameters in the brackets after the constructor declaration just like a normal method.
public class Student
{
String studentName;
int studentNumber;
Student(String s, int i)
{
studentName = s;
studentNumber = i;
}
public void setStudentName(String s)
{
studentName = s;
}
public void setStudentNumber(int i)
{
studentNumber = i;
}
public String getStudentName()
{
return studentName;
}
public int getStudentNumber()
{
return studentNumber;
}
}
Now all you need to do is put the parameters in the brackets when you instantiate the object in the main program.
public class TestClass
{
public static void main(String[] args)
{
Student stu = new Student("John Smith",12345);
System.out.println("Student Name: " + stu.getStudentName());
System.out.println("Student Number: " + stu.getStudentNumber());
}
}
Object oriented programming or OOP is a way of writing programs using objects. An object is a data structure in memory that has attributes and methods. The attributes of an object are the same as variables and the methods of an object are the same as functions or procedures.
The reason for using objects instead of the old procedural method of programming is because objects group the variables and methods about something together instead of keeping them all apart as in procedural programming. There are many other reasons why OOP is better which you will learn about later.
Using classes and objects
Before you can create an object you need to create a class. A class is the code for an object and an object is the instance of a class in memory. When you create an object from a class it is called instantiating the object. To help you understand think of the plan for a house. The plan for the house is like the class and the house that will be built from the plan is the object.
Creating a class
You have already been creating classes in the programs you have written so far. To show you how they work we will need to create a separate class in a separate file. This class will be called Student.
public class Student
{
}
Now we will add 2 variables to the class which are the student's name and student number.
public class Student
{
String studentName;
int studentNumber;
}
Next we must add methods for getting and setting these variables.
public class Student
{
String studentName;
int studentNumber;
public void setStudentName(String s)
{
studentName = s;
}
public void setStudentNumber(int i)
{
studentNumber = i;
}
public String getStudentName()
{
return studentName;
}
public int getStudentNumber()
{
return studentNumber;
}
}
Instantiating an object
Now that we have finished writing the class we must create the main program that will instantiate the object. We will call the main program class TestClass. It should look just like how every other java program starts off.
public class TestClass
{
public static void main(String[] args)
{
}
}
Now we will instantiate the object. To do this we declare a reference to the object called stu and set it equal to a newly created object in memory.
public class TestClass
{
public static void main(String[] args)
{
Student stu = new Student();
}
}
Using the object
Now we can call the methods from the stu object to set the values of its variables. You can't set the values of the variables in an object unless they are declared as public. This makes it safer to work with variables because they can't be changed by mistake by another object.
public class TestClass
{
public static void main(String[] args)
{
Student stu = new Student();
stu.setStudentName("John Smith");
stu.setStudentNumber(12345);
System.out.println("Student Name: " + stu.getStudentName());
System.out.println("Student Number: " + stu.getStudentNumber());
}
}
Constructors
A constructor is a method that is run when an object is instantiated. Constructors are useful for initializing variables. The constructor is declared with only the name of the class followed by brackets. Here is an example of the Student class that initializes both student name and student number.
public class Student
{
String studentName;
int studentNumber;
Student()
{
studentName = "No name";
studentNumber = 1;
}
public void setStudentName(String s)
{
studentName = s;
}
public void setStudentNumber(int i)
{
studentNumber = i;
}
public String getStudentName()
{
return studentName;
}
public int getStudentNumber()
{
return studentNumber;
}
}
You can also pass parameters to a constructor when you instantiate an object. All you need to do is add the parameters in the brackets after the constructor declaration just like a normal method.
public class Student
{
String studentName;
int studentNumber;
Student(String s, int i)
{
studentName = s;
studentNumber = i;
}
public void setStudentName(String s)
{
studentName = s;
}
public void setStudentNumber(int i)
{
studentNumber = i;
}
public String getStudentName()
{
return studentName;
}
public int getStudentNumber()
{
return studentNumber;
}
}
Now all you need to do is put the parameters in the brackets when you instantiate the object in the main program.
public class TestClass
{
public static void main(String[] args)
{
Student stu = new Student("John Smith",12345);
System.out.println("Student Name: " + stu.getStudentName());
System.out.println("Student Number: " + stu.getStudentNumber());
}
}
Labels:
Core Java
Arrays
What is an array
An array is group of variables that is given only one name. Each variable that makes up the array is given a number instead of a name which makes it easier to work with using loops among other things.
Declaring an array
Declaring an array is the same as declaring a normal variable except that you must put a set of square brackets after the variable type. Here is an example of how to declare an array of integers called a.
public class Array
{
public static void main(String[] args)
{
int[] a;
}
}
An array is more complex than a normal variable so we have to assign memory to the array when we declare it. When you assign memory to an array you also set its size. Here is an example of how to create an array that has 5 elements.
public class Array
{
public static void main(String[] args)
{
int[] a = new int[5];
}
}
Instead of assigning memory to the array you can assign values to it instead. This is called initializing the array because it is giving the array initial values.
public class Array
{
public static void main(String[] args)
{
int[] a = {12, 23, 34, 45, 56};
}
}
Using an array
You can access the values in an array using the number of the element you want to access between square brackets after the array's name. There is one important thing you must remember about arrays which is they always start at 0 and not 1. Here is an example of how to set the values for an array of 5 elements.
public class Array
{
public static void main(String[] args)
{
int[] a = new int[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
}
}
A much more useful way of using an array is in a loop. Here is an example of how to use a loop to set all the values of an array to 0 which you will see is much easier than setting all the values to 0 seperately.
public class Array
{
public static void main(String[] args)
{
int[] a = new int[5];
for (int i = 0; i < 5; i++)
a[i] = 0;
}
}
Sorting an array
Sometimes you will want to sort the elements of an array so that they go from the lowest value to the highest value or the other way around. To do this we must use the bubble sort. A bubble sort uses an outer loop to go from the last element of the array to the first and an inner loop which goes from the first to the last. Each value is compared inside the inner loop against the value in front of it in the array and if it is greater than that value then it is swapped. Here is an example.
public class Array
{
public static void main(String[] args)
{
int[] a = {3, 5, 1, 2, 4};
int i, j, temp;
for (i = 4; i >= 0; i--)
for (j = 0; j < i; j++)
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
2D arrays
So far we have been using 1-dimensional or 1D arrays. A 2D array can have values that go not only down but also across. Here are some pictures that will explain the difference between the 2 in a better way.
1D Array
0 1
1 2
2 3
3 4
4 5
2D Array
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
All that you need to do to create and use a 2D array is use 2 square brackets instead of 1.
public class Array
{
public static void main(String[] args)
{
int[][] a = new int[3][3];
a[0][0] = 1;
}
}
An array is group of variables that is given only one name. Each variable that makes up the array is given a number instead of a name which makes it easier to work with using loops among other things.
Declaring an array
Declaring an array is the same as declaring a normal variable except that you must put a set of square brackets after the variable type. Here is an example of how to declare an array of integers called a.
public class Array
{
public static void main(String[] args)
{
int[] a;
}
}
An array is more complex than a normal variable so we have to assign memory to the array when we declare it. When you assign memory to an array you also set its size. Here is an example of how to create an array that has 5 elements.
public class Array
{
public static void main(String[] args)
{
int[] a = new int[5];
}
}
Instead of assigning memory to the array you can assign values to it instead. This is called initializing the array because it is giving the array initial values.
public class Array
{
public static void main(String[] args)
{
int[] a = {12, 23, 34, 45, 56};
}
}
Using an array
You can access the values in an array using the number of the element you want to access between square brackets after the array's name. There is one important thing you must remember about arrays which is they always start at 0 and not 1. Here is an example of how to set the values for an array of 5 elements.
public class Array
{
public static void main(String[] args)
{
int[] a = new int[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
}
}
A much more useful way of using an array is in a loop. Here is an example of how to use a loop to set all the values of an array to 0 which you will see is much easier than setting all the values to 0 seperately.
public class Array
{
public static void main(String[] args)
{
int[] a = new int[5];
for (int i = 0; i < 5; i++)
a[i] = 0;
}
}
Sorting an array
Sometimes you will want to sort the elements of an array so that they go from the lowest value to the highest value or the other way around. To do this we must use the bubble sort. A bubble sort uses an outer loop to go from the last element of the array to the first and an inner loop which goes from the first to the last. Each value is compared inside the inner loop against the value in front of it in the array and if it is greater than that value then it is swapped. Here is an example.
public class Array
{
public static void main(String[] args)
{
int[] a = {3, 5, 1, 2, 4};
int i, j, temp;
for (i = 4; i >= 0; i--)
for (j = 0; j < i; j++)
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
2D arrays
So far we have been using 1-dimensional or 1D arrays. A 2D array can have values that go not only down but also across. Here are some pictures that will explain the difference between the 2 in a better way.
1D Array
0 1
1 2
2 3
3 4
4 5
2D Array
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
All that you need to do to create and use a 2D array is use 2 square brackets instead of 1.
public class Array
{
public static void main(String[] args)
{
int[][] a = new int[3][3];
a[0][0] = 1;
}
}
Labels:
Core Java
Data input and type conversions
Until now we have set the values of variables in the programs. Now we will learn how to get input from the user so that our programs are a bit more interesting and useful.
Reading single characters
To read a single character from the user you must use the System.in.read() method. This will return and integer value of the key pressed which must be converted to a character. We use (char) in front of System.in.read() to convert the integer to a character. After the user has pressed the key they must press enter and we must put a second System.in.read() to catch this second key press.
public class ReadChar
{
public static void main(String[] args) throws Exception
{
char c;
System.out.println("Enter a character");
c = (char)System.in.read();
System.in.read();
System.out.println("You entered " + c);
}
}
You will see that it says "throws Exception" at the end of the main method declaration. An exception is an error and "throws Exception" tells java to pass the error to the operating system for handling. Your program will not compile if you don't put this in.
Reading strings
The easiest way to read a string is to use the graphical input dialog. We must import the JOptionPane.showInputDialog method before we can use it. Then we can use the JOptionPane.showInputDialog method to read the string. We can print the entered string using the JOptionPane.showMessageDialog method. You must then put a System.exit(0) at the end of the program or else the program will not stop running.
import javax.swing.*;
public class ReadString
{
public static void main(String[] args)
{
String s;
s = JOptionPane.showInputDialog("Enter your name");
JOptionPane.showMessageDialog(null, "Your name is " + s);
System.exit(0);
}
}
Type conversions
Once you have read a string you might want to convert it to another data type such as an integer. You have already seen in a previous example that you must use the type that you want to convert to between brackets in front of the variable to be converted. Here is an example of some conversions:
public class Convert
{
public static void main(String[] args)
{
int i;
char c = 'a';
i = (int)c;
i = 5;
c = (char)i;
}
}
Strings are not variables but actually classes which is why we must use the Integer.parseInt() method to convert a string to an integer.
import javax.swing.*;
public class ConvertString
{
public static void main(String[] args)
{
String s;
int i;
s = JOptionPane.showInputDialog("Enter a number");
i = Integer.parseInt(s);
JOptionPane.showMessageDialog(null, "The number you entered is " + i);
System.exit(0);
}
}
Reading single characters
To read a single character from the user you must use the System.in.read() method. This will return and integer value of the key pressed which must be converted to a character. We use (char) in front of System.in.read() to convert the integer to a character. After the user has pressed the key they must press enter and we must put a second System.in.read() to catch this second key press.
public class ReadChar
{
public static void main(String[] args) throws Exception
{
char c;
System.out.println("Enter a character");
c = (char)System.in.read();
System.in.read();
System.out.println("You entered " + c);
}
}
You will see that it says "throws Exception" at the end of the main method declaration. An exception is an error and "throws Exception" tells java to pass the error to the operating system for handling. Your program will not compile if you don't put this in.
Reading strings
The easiest way to read a string is to use the graphical input dialog. We must import the JOptionPane.showInputDialog method before we can use it. Then we can use the JOptionPane.showInputDialog method to read the string. We can print the entered string using the JOptionPane.showMessageDialog method. You must then put a System.exit(0) at the end of the program or else the program will not stop running.
import javax.swing.*;
public class ReadString
{
public static void main(String[] args)
{
String s;
s = JOptionPane.showInputDialog("Enter your name");
JOptionPane.showMessageDialog(null, "Your name is " + s);
System.exit(0);
}
}
Type conversions
Once you have read a string you might want to convert it to another data type such as an integer. You have already seen in a previous example that you must use the type that you want to convert to between brackets in front of the variable to be converted. Here is an example of some conversions:
public class Convert
{
public static void main(String[] args)
{
int i;
char c = 'a';
i = (int)c;
i = 5;
c = (char)i;
}
}
Strings are not variables but actually classes which is why we must use the Integer.parseInt() method to convert a string to an integer.
import javax.swing.*;
public class ConvertString
{
public static void main(String[] args)
{
String s;
int i;
s = JOptionPane.showInputDialog("Enter a number");
i = Integer.parseInt(s);
JOptionPane.showMessageDialog(null, "The number you entered is " + i);
System.exit(0);
}
}
Labels:
Core Java
Loops
What is a loop?
A loop is a way of repeating lines of code. If you want to for example print Hello on the screen 10 times then you can either use System.out.println 10 times or you can put 1 System.out.println in a loop that runs 10 times which takes a lot less lines of code.
For loop
The for loop goes from a number you give it to a second number you give it. It uses a loop counter variable to store the current loop number. Here is the format for a for loop:
for (set starting value; end condition; increment loop variable)
You first set the loop counter variable to the starting value. Next you set the end condition. While the condition is true the loop will keep running but when it is false then it will exit the loop. The last one is for setting the amount by which the loop variable must be increased by each time it repeats the loop. Here is how you would do the example of printing Hello 10 times using a for loop:
public class Loops
{
public static void main(String[] args)
{
int i;
for (i = 1; i <=10; i++)
System.out.println("Hello");
}
}
Incrementing and decrementing
i++ has been used to add 1 to i. This is called incrementing. You can decrement i by using i--. If you use ++i then the value is incremented before the condition is tested and if it is i++ then i is incremented after the condition is tested.
Multiple lines of code in a loop
If you want to use more than 1 line of code in a loop then you must group them together between curly brackets.
public class Loops
{
public static void main(String[] args)
{
int i;
for (i = 1; i <=10; i++)
{
System.out.println("Hello");
System.out.println(i);
}
}
}
While loop
The while loop will repeat itself while a certain condition is true. The condition is only tested once every loop and not all the time while the loop is running. If you want to use a loop counter variable in a while loop then you must initialize it before you enter the loop and increment it inside the loop. Here is the Hello example using a while loop:
public class Loops
{
public static void main(String[] args)
{
int i = 1;
while (i <= 10)
{
System.out.println("Hello");
i++;
}
}
}
Do while loop
The do while loop is like the while loop except that the condition is tested at the bottom of the loop instead of the top.
public class Loops
{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println("Hello");
i++;
}
while (i <= 10)
}
}
A loop is a way of repeating lines of code. If you want to for example print Hello on the screen 10 times then you can either use System.out.println 10 times or you can put 1 System.out.println in a loop that runs 10 times which takes a lot less lines of code.
For loop
The for loop goes from a number you give it to a second number you give it. It uses a loop counter variable to store the current loop number. Here is the format for a for loop:
for (set starting value; end condition; increment loop variable)
You first set the loop counter variable to the starting value. Next you set the end condition. While the condition is true the loop will keep running but when it is false then it will exit the loop. The last one is for setting the amount by which the loop variable must be increased by each time it repeats the loop. Here is how you would do the example of printing Hello 10 times using a for loop:
public class Loops
{
public static void main(String[] args)
{
int i;
for (i = 1; i <=10; i++)
System.out.println("Hello");
}
}
Incrementing and decrementing
i++ has been used to add 1 to i. This is called incrementing. You can decrement i by using i--. If you use ++i then the value is incremented before the condition is tested and if it is i++ then i is incremented after the condition is tested.
Multiple lines of code in a loop
If you want to use more than 1 line of code in a loop then you must group them together between curly brackets.
public class Loops
{
public static void main(String[] args)
{
int i;
for (i = 1; i <=10; i++)
{
System.out.println("Hello");
System.out.println(i);
}
}
}
While loop
The while loop will repeat itself while a certain condition is true. The condition is only tested once every loop and not all the time while the loop is running. If you want to use a loop counter variable in a while loop then you must initialize it before you enter the loop and increment it inside the loop. Here is the Hello example using a while loop:
public class Loops
{
public static void main(String[] args)
{
int i = 1;
while (i <= 10)
{
System.out.println("Hello");
i++;
}
}
}
Do while loop
The do while loop is like the while loop except that the condition is tested at the bottom of the loop instead of the top.
public class Loops
{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println("Hello");
i++;
}
while (i <= 10)
}
}
Labels:
Core Java
Decisions
What are decisions?
A decision is a way of allowing a program to choose which code to run. If a condition is met then one section of code will be run and if it is not then another section will be run.
The if decision structure
The if statement evaluates a condition and if the result is true then it runs the line of code that follows it. Here is an example of how to test if the value of a variable called i is equal to 5:
public class Decisions
{
public static void main(String[] args)
{
int i = 5;
if (i == 5)
System.out.println("i is equal to 5");
}
}
If you change i to 4 and run this program again you will see that no message is printed.
Relational operators
You will see that a == has been used to test if the values are equal. It is important to know that a = is for setting a value and a == is for testing a value. The == is called a relational operator. Here is a table of the other relational operators that can be used:
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
else
We know that if the condition is true then the code directly afer the if statement is run. You can run code for when the condition is false by using the else statement.
public class Decisions
{
public static void main(String[] args)
{
int i = 4;
if (i == 5)
System.out.println("i is equal to 5");
else
System.out.println("i is not equal to 5");
}
}
Grouping statements
If you want to run more than 1 line of code in an if statement then you must group them together with curly brackets.
public class Decisions
{
public static void main(String[] args)
{
int i = 4;
if (i != 5)
{
System.out.println("i not is equal to 5");
System.out.println("i is equal to " + i);
}
}
}
Nested if structures
You can put if statements inside other if statments which will make them nested if statements. It is sometimes more efficient to use nested if statements such as in the following example which finds out if a number is positive, negative or zero:
public class Decisions
{
public static void main(String[] args)
{
int i = 1;
if (i > 0)
System.out.println("Positive");
else
if (i < 0)
System.out.println("Negative");
else
System.out.println("Zero");
}
}
AND, OR and NOT
You can test if more than 1 condition is true using the AND(&&) operator. To test if only 1 of many conditions is true use the OR(||) operator. The NOT(!) operator will change a true to a false and a false to a true.
public class Decisions
{
public static void main(String[] args)
{
int i = 1;
int j = 1;
if (i == 1 && j == 1)
System.out.println("i is 1 and j is 1");
if (i == 1 || j == 2)
System.out.println("Either i is 1 or j is 1");
if (!(i == 1))
System.out.println("i is not 1");
}
}
The switch decision structure
The switch structure is like having many if statements in one. It takes a variable and then has a list of actions to perform for each value that the variable could be. It also has an optional part for when none of the values match. The break statement is used to break out of the switch structure so that no more conditions are tested.
public class Decisions
{
public static void main(String[] args)
{
int i = 3;
switch(i)
{
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is2");
break;
case 3:
System.out.println("i is 3");
break;
default:
System.out.println("Invalid value");
}
}
}
A decision is a way of allowing a program to choose which code to run. If a condition is met then one section of code will be run and if it is not then another section will be run.
The if decision structure
The if statement evaluates a condition and if the result is true then it runs the line of code that follows it. Here is an example of how to test if the value of a variable called i is equal to 5:
public class Decisions
{
public static void main(String[] args)
{
int i = 5;
if (i == 5)
System.out.println("i is equal to 5");
}
}
If you change i to 4 and run this program again you will see that no message is printed.
Relational operators
You will see that a == has been used to test if the values are equal. It is important to know that a = is for setting a value and a == is for testing a value. The == is called a relational operator. Here is a table of the other relational operators that can be used:
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
else
We know that if the condition is true then the code directly afer the if statement is run. You can run code for when the condition is false by using the else statement.
public class Decisions
{
public static void main(String[] args)
{
int i = 4;
if (i == 5)
System.out.println("i is equal to 5");
else
System.out.println("i is not equal to 5");
}
}
Grouping statements
If you want to run more than 1 line of code in an if statement then you must group them together with curly brackets.
public class Decisions
{
public static void main(String[] args)
{
int i = 4;
if (i != 5)
{
System.out.println("i not is equal to 5");
System.out.println("i is equal to " + i);
}
}
}
Nested if structures
You can put if statements inside other if statments which will make them nested if statements. It is sometimes more efficient to use nested if statements such as in the following example which finds out if a number is positive, negative or zero:
public class Decisions
{
public static void main(String[] args)
{
int i = 1;
if (i > 0)
System.out.println("Positive");
else
if (i < 0)
System.out.println("Negative");
else
System.out.println("Zero");
}
}
AND, OR and NOT
You can test if more than 1 condition is true using the AND(&&) operator. To test if only 1 of many conditions is true use the OR(||) operator. The NOT(!) operator will change a true to a false and a false to a true.
public class Decisions
{
public static void main(String[] args)
{
int i = 1;
int j = 1;
if (i == 1 && j == 1)
System.out.println("i is 1 and j is 1");
if (i == 1 || j == 2)
System.out.println("Either i is 1 or j is 1");
if (!(i == 1))
System.out.println("i is not 1");
}
}
The switch decision structure
The switch structure is like having many if statements in one. It takes a variable and then has a list of actions to perform for each value that the variable could be. It also has an optional part for when none of the values match. The break statement is used to break out of the switch structure so that no more conditions are tested.
public class Decisions
{
public static void main(String[] args)
{
int i = 3;
switch(i)
{
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is2");
break;
case 3:
System.out.println("i is 3");
break;
default:
System.out.println("Invalid value");
}
}
}
Labels:
Core Java
Variables and constants
What is a variable
Variables are places in the computer's memory where you store the data for a program. Each variable is given a unique name which you refer to it with.
Variable types
There are 3 different types of data that can be stored in variables. The first type is the numeric type which stores numbers. There are 2 types of numeric variables which are integer and real. Integers are whole numbers such as 1,2,3,... Real numbers have a decimal point in them such as 1.89 or 0.12.
Character variables store only 1 letter of the alphabet. You must always put the vlaue that is to be stored in a character variable inside single quotes. A string variable is like a chracter variable but it can store more than 1 character in it. You must use double quotes for a string instead of single quotes like with a character.
Boolean variables can store 1 of 2 values which are True or False.
Here is a table of the types of variables that can be used:
Name Type Values
byte Numeric - Integer -128 to 127
short Numeric - Integer -32 768 to 32 767
int Numeric - Integer -2 147 483 648 to 2 147 483 647
long Numeric - Integer -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807
float Numeric - Real -3.4 * 1038 to 3.4 * 1038
double Numeric - Real -1.7 * 10308 to 1.7 * 10308
char Character All unicode characters
String Character All unicode characters
boolean Boolean True or False
Declaring variables
You can declare a variable either inside the class curly brackets or inside the main method's curly brackets. You declare a variable by first saying which type it must be and then saying what its name is. A variable name can only include any letter of the alphabet, numbers and underscores. Variable names can start with a $ but may not start with a number. Spaces are not allowed in variable names. You usually start a variable name with a lower case letter and every first letter of words that make up the name must be upper case. Here is an example of how you declare an integer variable called MyVariable in the main method:
public class Variables
{
public static void main(String[] args)
{
int myVariable;
}
}
If you want to declare more than 1 variable of the same type you must seperate the names with a comma.
public class Variables
{
public static void main(String[] args)
{
int myVariable, myOtherVariable;
}
}
Using variables
A = is used to store a value in a variable. You put the variable name on the left side and the value to store in the variable on the right side. Remember to use quotes when storing String values. You can also store a value in a variable when it is declared or later in the program.
public class Variables
{
public static void main(String[] args)
{
int myInteger;
myInteger = 5;
String myString = "Hello";
}
}
You can print variables on the screen with System.out.println.
public class Variables
{
public static void main(String[] args)
{
int myInteger = 5;
String myString = "Hello";
System.out.println(myInteger);
System.out.println(myString);
}
}
You can join things printed with System.out.println with a +.
public class Variables
{
public static void main(String[] args)
{
int myInteger = 5;
System.out.println("The value of myInteger is " + myInteger);
}
}
Variables in calculations
The important thing about variables is that they can be used in calculations. When you perform a calculation you must store the result in a variable which can also be a variable that is used in the calculation.. Here is an example of how to add 2 numbers together and store the result in a variable:
public class Variables
{
public static void main(String[] args)
{
int answer;
answer = 2 + 3;
}
}
Once you have stored a value in a variable you can use it in a calculation just like a number.
public class Variables
{
public static void main(String[] args)
{
int answer;
int number = 2;
answer = number + 3;
}
}
Here is a table of operators which can be used in calculations:
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder of division
Constants
Constants are variables with values that can't be changed. The value is assigned to a constant when it is declared. Constants are used to give names to certain values so that their meaning is more obvious. The meaning of the number 3.14 is not obvious but if it was given the name PI then you know immediatly what it means.Use the word final in front of a normal variable declaration to make it a constant.
public class Variables
{
public static void main(String[] args)
{
final double PI = 3.14;
}
}
Variables are places in the computer's memory where you store the data for a program. Each variable is given a unique name which you refer to it with.
Variable types
There are 3 different types of data that can be stored in variables. The first type is the numeric type which stores numbers. There are 2 types of numeric variables which are integer and real. Integers are whole numbers such as 1,2,3,... Real numbers have a decimal point in them such as 1.89 or 0.12.
Character variables store only 1 letter of the alphabet. You must always put the vlaue that is to be stored in a character variable inside single quotes. A string variable is like a chracter variable but it can store more than 1 character in it. You must use double quotes for a string instead of single quotes like with a character.
Boolean variables can store 1 of 2 values which are True or False.
Here is a table of the types of variables that can be used:
Name Type Values
byte Numeric - Integer -128 to 127
short Numeric - Integer -32 768 to 32 767
int Numeric - Integer -2 147 483 648 to 2 147 483 647
long Numeric - Integer -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807
float Numeric - Real -3.4 * 1038 to 3.4 * 1038
double Numeric - Real -1.7 * 10308 to 1.7 * 10308
char Character All unicode characters
String Character All unicode characters
boolean Boolean True or False
Declaring variables
You can declare a variable either inside the class curly brackets or inside the main method's curly brackets. You declare a variable by first saying which type it must be and then saying what its name is. A variable name can only include any letter of the alphabet, numbers and underscores. Variable names can start with a $ but may not start with a number. Spaces are not allowed in variable names. You usually start a variable name with a lower case letter and every first letter of words that make up the name must be upper case. Here is an example of how you declare an integer variable called MyVariable in the main method:
public class Variables
{
public static void main(String[] args)
{
int myVariable;
}
}
If you want to declare more than 1 variable of the same type you must seperate the names with a comma.
public class Variables
{
public static void main(String[] args)
{
int myVariable, myOtherVariable;
}
}
Using variables
A = is used to store a value in a variable. You put the variable name on the left side and the value to store in the variable on the right side. Remember to use quotes when storing String values. You can also store a value in a variable when it is declared or later in the program.
public class Variables
{
public static void main(String[] args)
{
int myInteger;
myInteger = 5;
String myString = "Hello";
}
}
You can print variables on the screen with System.out.println.
public class Variables
{
public static void main(String[] args)
{
int myInteger = 5;
String myString = "Hello";
System.out.println(myInteger);
System.out.println(myString);
}
}
You can join things printed with System.out.println with a +.
public class Variables
{
public static void main(String[] args)
{
int myInteger = 5;
System.out.println("The value of myInteger is " + myInteger);
}
}
Variables in calculations
The important thing about variables is that they can be used in calculations. When you perform a calculation you must store the result in a variable which can also be a variable that is used in the calculation.. Here is an example of how to add 2 numbers together and store the result in a variable:
public class Variables
{
public static void main(String[] args)
{
int answer;
answer = 2 + 3;
}
}
Once you have stored a value in a variable you can use it in a calculation just like a number.
public class Variables
{
public static void main(String[] args)
{
int answer;
int number = 2;
answer = number + 3;
}
}
Here is a table of operators which can be used in calculations:
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder of division
Constants
Constants are variables with values that can't be changed. The value is assigned to a constant when it is declared. Constants are used to give names to certain values so that their meaning is more obvious. The meaning of the number 3.14 is not obvious but if it was given the name PI then you know immediatly what it means.Use the word final in front of a normal variable declaration to make it a constant.
public class Variables
{
public static void main(String[] args)
{
final double PI = 3.14;
}
}
Labels:
Core Java
Java First Program
What is Java?
Java is an object-oriented programming language which was developed by Sun Microsystems. Java programs are platform independant which means they can be run on any operating system with any type of processor as long as the Java interpreter is available on that system.
What you will need
You will need the Java software development kit from Sun's Java site. Follow the instructions on Sun's website to install it. Make sure that you add the java bin directory to your PATH environment variable.
Writing your first Java program
You will need to write your Java programs using a text editor. When you type the examples that follow you must make sure that you use capital and small letters in the right places because Java is case sensitive. The first line you must type is:
public class Hello
This creates a class called Hello. All class names must start with a capital letter. The main part of the program must go between curly brackets after the class declaration. The curly brackets are used to group together everything inside them.
public class Hello
{
}
We must now create the main method which is the section that a program starts.
public class Hello
{
public static void main(String[] args)
{
}
}
The word public means that it is accessible by any other classes. static means that it is unique. void is the return value but void means nothing which means there will be no return value. main is the name of the method. (String[] args) is used for command line parameters. Curly brackets are used again to group the contents of main together. You probably won't understand a few of the things that have just been said but you will know what they mean later on. For now it is enough just to remember how to write that line.
You will see that the main method code has been moved over a few spaces from the left. This is called indentation and is used to make a program easier to read and understand.
Here is how you print the words Hello World on the screen:
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Make sure that you use a capital S in System because it is the name of a class. println is a method that prints the words that you put between the brackets after it on the screen. When you work with letters like in Hello World you must always put them between quotes. The semi-colon is used to show that it is the end of your line of code. You must put semi-colons after every line like this.
Compiling the program
What we have just finished typing is called the source code. You must save the source code with the file name Hello.java before you can compile it. The file name must always be the same as the class name.
Make sure you have a command prompt open and then enter the following:
javac Hello.java
If you did everything right then you will see no errors messages and your program will be compiled. If you get errors then go through this lesson again and see where your mistake is.
Running the program
Once your program has been compiled you will get a file called Hello.class. This is not like normal programs that you just type the name to run but it is actually a file containing the Java bytecode that is run by the Java interpreter. To run your program with the Java interpeter use the following command:
java Hello
Do not add .class on to the end of Hello. You will now see the following output on the screen:
Hello World
Congratulations! You have just made your first Java program.
Comments
Comments are written in a program to explain the code. Comments are ignored by the compiler and are only there for people. Comments must go between a /* and a */ or after //. Here is an example of how to comment the Hello World program:
/* This program prints the words Hello World on the screen */
public class Hello // The Hello class
{
public static void main(String[] args) // The main method
{
System.out.println("Hello World"); // Print Hello World
}
}
Java is an object-oriented programming language which was developed by Sun Microsystems. Java programs are platform independant which means they can be run on any operating system with any type of processor as long as the Java interpreter is available on that system.
What you will need
You will need the Java software development kit from Sun's Java site. Follow the instructions on Sun's website to install it. Make sure that you add the java bin directory to your PATH environment variable.
Writing your first Java program
You will need to write your Java programs using a text editor. When you type the examples that follow you must make sure that you use capital and small letters in the right places because Java is case sensitive. The first line you must type is:
public class Hello
This creates a class called Hello. All class names must start with a capital letter. The main part of the program must go between curly brackets after the class declaration. The curly brackets are used to group together everything inside them.
public class Hello
{
}
We must now create the main method which is the section that a program starts.
public class Hello
{
public static void main(String[] args)
{
}
}
The word public means that it is accessible by any other classes. static means that it is unique. void is the return value but void means nothing which means there will be no return value. main is the name of the method. (String[] args) is used for command line parameters. Curly brackets are used again to group the contents of main together. You probably won't understand a few of the things that have just been said but you will know what they mean later on. For now it is enough just to remember how to write that line.
You will see that the main method code has been moved over a few spaces from the left. This is called indentation and is used to make a program easier to read and understand.
Here is how you print the words Hello World on the screen:
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Make sure that you use a capital S in System because it is the name of a class. println is a method that prints the words that you put between the brackets after it on the screen. When you work with letters like in Hello World you must always put them between quotes. The semi-colon is used to show that it is the end of your line of code. You must put semi-colons after every line like this.
Compiling the program
What we have just finished typing is called the source code. You must save the source code with the file name Hello.java before you can compile it. The file name must always be the same as the class name.
Make sure you have a command prompt open and then enter the following:
javac Hello.java
If you did everything right then you will see no errors messages and your program will be compiled. If you get errors then go through this lesson again and see where your mistake is.
Running the program
Once your program has been compiled you will get a file called Hello.class. This is not like normal programs that you just type the name to run but it is actually a file containing the Java bytecode that is run by the Java interpreter. To run your program with the Java interpeter use the following command:
java Hello
Do not add .class on to the end of Hello. You will now see the following output on the screen:
Hello World
Congratulations! You have just made your first Java program.
Comments
Comments are written in a program to explain the code. Comments are ignored by the compiler and are only there for people. Comments must go between a /* and a */ or after //. Here is an example of how to comment the Hello World program:
/* This program prints the words Hello World on the screen */
public class Hello // The Hello class
{
public static void main(String[] args) // The main method
{
System.out.println("Hello World"); // Print Hello World
}
}
Labels:
Core Java
Subscribe to:
Posts (Atom)