Introduction to Java programming, Part 1: Java language basics

Object-oriented programming on the Java platform
J Steven Perry (steve.perry@makotoconsulting.com) Principal Consultant Makoto Consulting Group, Inc. Skill Level: Introductory Date: 19 Aug 2010

This two-part tutorial introduces the structure, syntax, and programming paradigm of the Java™ language and platform. You'll learn the Java syntax you are most likely to encounter professionally and Java programming idioms you can use to build robust, maintainable Java applications. In Part 1, J. Steven Perry guides you through the essentials of object-oriented programming on the Java platform, including fundamental Java syntax and its use. You'll get started with creating Java objects and adding behavior to them, and conclude with an introduction to the Java Collections Framework, with considerable ground covered in between. View more content in this series

Section 1. Before you begin
Find out what to expect from this tutorial and how to get the most out of it.

About this tutorial
Become a Java developer http://www.ibm.com/developerworks/training/kp/j-kp-intro/ index.html The two-part "Introduction to Java programming" tutorial is intended to get software developers who are new to Java technology up and running with object-oriented programming (OOP) and real-world application development using the Java language and platform. This first part is a step-by-step introduction to OOP using the Java language. The tutorial begins with an overview of the Java platform and language and is followed by instructions for setting up a development environment consisting of a Java
© Copyright IBM Corporation 2010 Introduction to Java programming, Part 1: Java language basics Trademarks Page 1 of 57

developerWorks®

ibm.com/developerWorks/

Development Kit (JDK) and the Eclipse IDE. Once you have been introduced to your development environment's components, you will begin learning basic Java syntax hands-on. Part 2 covers more-advanced language features, including regular expressions, generics, I/O, and serialization. Programming examples in Part 2 build on the Person object that you begin developing in Part 1.

Objectives
When you've finished Part 1, you will be familiar with basic Java language syntax and able to write simple Java programs. You should follow up with "Introduction to Java programming, Part 2: Constructs for real-world applications" to build on this foundation.

Prerequisites
This tutorial is for software developers who are not yet experienced with Java code or the Java platform. The tutorial includes an overview of OOP concepts.

System requirements
To complete the exercises in this tutorial, install and set up a development environment consisting of: • JDK 6 from Sun/Oracle. • Eclipse IDE for Java Developers. Download and installation instructions for both are included in the tutorial. The recommended system configuration is: • A system supporting Java SE 6 with at least 1GB of main memory. Java 6 is supported on Linux®, Windows®, and Solaris®. • At least 20MB of disk space to install the software components and examples.

Section 2. Java platform overview
Java technology is used to develop applications for a wide range of environments, from consumer devices to heterogeneous enterprise systems. In this section, get a high-level view of the Java platform and its components. See Resources to learn more about the Java platform components discussed in this section.

The Java language
Get to know the Java APIs
Most Java developers constantly reference the official online Java API documentation — also called the Javadoc (see Resources). By default, Introduction to Java programming, Part 1: Java language basics Page 2 of 57

ibm.com/developerWorks/

developerWorks®

you see three frames in the Javadoc. The top-left frame shows all of the packages in the API, and beneath that are the classes in each package. The main frame (to the right) shows details for the currently selected package or class. For example, if you select the java.util package in the top-left frame and then select the ArrayList class listed below it, in the right-hand frame you will see details about ArrayList, including a description of what it does, how to use it, and its methods.

Like any programming language, the Java language has its own structure, syntax rules, and programming paradigm. The Java language's programming paradigm is based on the concept of object-oriented programming (OOP), which the language's features support. The Java language is a C-language derivative, so its syntax rules look much like C's: for example, code blocks are modularized into methods and delimited by braces ({ and }), and variables are declared before they are used. Structurally, the Java language starts with packages. A package is the Java language's namespace mechanism. Within packages are classes, and within classes are methods, variables, constants, and so on. You'll learn about the parts of the Java language in this tutorial.

The Java compiler
When you program for the Java platform, you write source code in .java files and then compile them. The compiler checks your code against the language's syntax rules, then writes out bytecodes in .class files. Bytecodes are standard instructions targeted to run on a Java virtual machine (JVM). In adding this level of abstraction, the Java compiler differs from other language compilers, which write out instructions suitable for the CPU chipset the program will run on.

The JVM
At run time, the JVM reads and interprets .class files and executes the program's instructions on the native hardware platform for which the JVM was written. The JVM interprets the bytecodes just as a CPU would interpret assembly-language instructions. The difference is that the JVM is a piece of software written specifically for a particular platform. The JVM is the heart of the Java language's "write-once, run-anywhere" principle. Your code can run on any chipset for which a suitable JVM implementation is available. JVMs are available for major platforms like Linux and Windows, and subsets of the Java language have been implemented in JVMs for mobile phones and hobbyist chips.

The garbage collector
Rather than forcing you to keep up with memory allocation (or use a third-party library to do this), the Java platform provides memory management out of the box. When your Java application creates an object instance at run time, the JVM automatically
Introduction to Java programming, Part 1: Java language basics Page 3 of 57

developerWorks®

ibm.com/developerWorks/

allocates memory space for that object from the heap, which is a pool of memory set aside for your program to use. The Java garbage collector runs in the background, keeping track of which objects the application no longer needs and reclaiming memory from them. This approach to memory handling is called implicit memory management because it doesn't require you to write any memory-handling code. Garbage collection is one of the essential features of Java platform performance.

The Java Development Kit
When you download a Java Development Kit (JDK), you get — in addition to the compiler and other tools — a complete class library of prebuilt utilities that help you accomplish just about any task common to application development. The best way to get an idea of the scope of the JDK packages and libraries is to check out the JDK API documentation (see Resources).

The Java Runtime Environment
The Java Runtime Environment (JRE; also known as the Java runtime) includes the JVM, code libraries, and components that are necessary for running programs written in the Java language. It is available for multiple platforms. You can freely redistribute the JRE with your applications, according to the terms of the JRE license, to give the application's users a platform on which to run your software. The JRE is included in the JDK.

Section 3. Setting up your Java development environment
In this section, you'll get instructions for downloading and installing JDK 6 and the current release of the Eclipse IDE, and for setting up your Eclipse development environment. If you already have the JDK and Eclipse IDE installed, you may want to skip to the Getting started with Eclipse section or to the one after that, Object-oriented programming concepts.

Your development environment
The JDK includes a set of command-line tools for compiling and running your Java code, including a complete copy of the JRE. Although you certainly can use these tools to develop your applications, most developers appreciate the additional functionality, task management, and visual interface of an IDE. Eclipse is a popular open source IDE for Java development. It handles basic tasks, such as code compilation and setting up a debugging environment, so that you can
Introduction to Java programming, Part 1: Java language basics Page 4 of 57

ibm.com/developerWorks/

developerWorks®

focus on writing and testing code. In addition, you can use Eclipse to organize source code files into projects, compile and test those projects, and store project files in any number of source repositories. You need an installed JDK in order to use Eclipse for Java development.

Install JDK 6
Follow these steps to download and install JDK 6: 1. Browse to Java SE Downloads and click the Java Platform (JDK) box to display the download page for the latest version of the JDK (JDK 6, update 21 at the time of this writing). 2. Click the Download button. 3. Select the operating system platform you need. 4. You will be asked for your account username and password. Enter them if you have an account, sign up if you don't, or you can click Continue to skip this step and proceed to the download. 5. Save the file to your hard drive when prompted. 6. When the download is complete, run the install program. (The file you've just downloaded is a self-extracting ZIP file that is also the install program.) Install the JDK to your hard drive in an easy-to-remember location (such as C:\home \jdk1.6.0_20 on Windows or ~/jdk1.6.0_20 on Linux). It's a good idea to encode the update number in the name of the install directory you choose. You now have a Java environment on your machine. Next, you will install the Eclipse IDE.

Install Eclipse
To download and install Eclipse, follow these steps: 1. 2. 3. 4. Browse to Eclipse Galileo Sr2 Packages. Click on Eclipse IDE for Java Developers. Under Download Links on the right-hand side, select your platform. Select the mirror you want to download from, then save the file to your hard drive. 5. Extract the contents of the .zip file to a location on your hard drive that you'll be able to remember easily (such as C:\home\eclipse on Windows or ~/eclipse on Linux).

Set up Eclipse
The Eclipse IDE sits atop the JDK as a useful abstraction, but it still needs to access the JDK and its various tools. Before you can use Eclipse to write Java code, you have to tell it where the JDK is located. To set up your Eclipse development environment:
Introduction to Java programming, Part 1: Java language basics Page 5 of 57

developerWorks®

ibm.com/developerWorks/

1. Launch Eclipse by double-clicking on eclipse.exe (or the equivalent executable for your platform). 2. The Workspace Launcher will appear, allowing you to select a root folder for your Eclipse projects. Choose a folder you will easily remember, such as C: \home\workspace on Windows or ~/workspace on Linux. 3. Dismiss the Welcome to Eclipse screen. 4. Click Window > Preferences > Java > Installed JREs. Figure 1 shows the setup screen for the JRE: Figure 1. Configuring the JDK used by Eclipse

5. Eclipse will point to an installed JRE. You need to make sure you use the one you downloaded with JDK 6. If Eclipse does not automatically detect the JDK you installed, click Add... and in the next dialog Standard VM, then click Next. 6. Specify the JDK's home directory (such as C:\home\jdk1.6.0_20 on Windows), then click Finish. 7. Confirm that the JDK you want to use is selected and click OK. Eclipse is now set up and ready for you to create projects and compile and run Java code. The next section will familiarize you with Eclipse.

Section 4. Getting started with Eclipse
Introduction to Java programming, Part 1: Java language basics Page 6 of 57

Each tab shown in Figure 2 is a view for the Java perspective. The Java perspective Figure 2 shows the Java perspective. Package Explorer and Outline are two particularly useful views.ibm. it is an entire development ecosystem. Introduction to Java programming. See Resources if you want to learn more about Eclipse. This section is a brief hands-on introduction to using Eclipse for Java development. You should see this perspective when you start up Eclipse. A workspace contains all of your projects. and within a perspective are one or more views. The Eclipse development environment The Eclipse development environment has four main components: • • • • Workspace Projects Perspectives Views The primary unit of organization in Eclipse is the workspace. Part 1: Java language basics Page 7 of 57 . Eclipse Java perspective The Java perspective contains the tools you need to begin writing Java applications. Figure 2.com/developerWorks/ developerWorks® Eclipse is not just an IDE. A perspective is a way of looking at each project (hence the name). which is the default perspective for Eclipse.

If you want to modify the default project settings. Click on File > New > Java Project .developerWorks® ibm.) 4. However. though. Enter Intro as the project name and click Finish. an understanding of the OOP Introduction to Java programming. click Next. and you will see a dialog box open like the one shown in Figure 3: Figure 3. Click Finish to accept the project setup and create the project.com/developerWorks/ The Eclipse environment is highly configurable. Part 1: Java language basics Page 8 of 57 . stick with the default perspective and view setup.. New Java Project wizard 2. (This is recommended only if you have experience with the Eclipse IDE. 3. Create a project Follow these steps to create a new Java project: 1. so you can move it around in the Java perspective and place it where you want it. You have now created a new Eclipse Java project and source folder. Each view is dockable. For now.. Your development environment is ready for action.

using structured programming as a point of contrast. What is an object? Structured programming languages like C and COBOL follow a very different programming paradigm from object-oriented ones. Part 1: Java language basics Page 9 of 57 . The objectoriented paradigm allows you to reuse the common attributes and behavior of the parent object. you might want to skip to Getting started with the Java language. its concepts might seem strange at first. and then program instructions that act on that data.) Object communication and coordination Objects talk to other objects by sending messages (method calls in the Java language). The structured-programming paradigm is highly data-oriented.com/developerWorks/ developerWorks® paradigm — covered in this tutorial's next two sections — is essential. in an objectoriented language. If you haven't used an object-oriented language before.) Introduction to Java programming.ibm. An object is a self-contained entity that contains attributes and behavior. adding to its child objects attributes and behavior that differ. Section 5. Parent and child objects A parent object is one that serves as the structural basis for deriving more-complex child objects. (You'll learn more about inheritance in the next section of this tutorial. this coordinating program code is the Controller. A child object looks like its parent but is more specialized. and nothing more. which means that you have data structures on one hand. in an object-oriented application. from fine-grained objects like a Number. data and program logic are combined. program code coordinates the activities among objects to perform tasks within the context of the given application domain. Object-oriented programming concepts The Java language is (mostly) object-oriented. Object-oriented languages like the Java language combine data and program instructions into objects. (In the Model-View-Controller paradigm. If you are familiar with OOP concepts and principles. to coarse-grained objects such as a FundsTransfer service in a large banking application. Rather than having a data structure with fields (attributes) and passing that structure around to all of the program logic that acts on it (behavior). See Resources to learn more about MVC. This section is a short introduction to OOP language concepts. This combination can occur at vastly different levels of granularity. Furthermore.

Attributes What attributes can a person have? Some common ones include: • • • • • • Name Age Height Weight Eye color Gender You can probably think of more (and you can always add more attributes later).com/developerWorks/ Object summary A well-written object: • Has crisp boundaries • Does a finite set of activities • Knows only about its data and any other objects that it needs to accomplish its activities In essence. In a business-application context. Person would tell you the value of its Age attribute. you might want to ask your Person object. you know that an object has two primary elements: attributes and behavior. but object behaviors usually relate to some kind of application context. More-complex logic could be hidden inside of the Person object. for instance. but this list is a good start. You'll see how these apply to the Person object. "What is your age?" In response. an object is a discrete entity that has only the necessary dependencies on other objects to perform its tasks. Behavior An actual person can do all sorts of things. The Person object I'll start with an example that is based on a common application-development scenario: an individual being represented by a Person object. but for now suppose that Person has the behavior of answering these questions: • What is your name? • What is your age? • What is your height? Introduction to Java programming. Going back to the definition of an object. Now you'll see what an object looks like.developerWorks® ibm. Part 1: Java language basics Page 10 of 57 .

Principles of OOP If you come from a structured-programming background.com/developerWorks/ developerWorks® • What is your weight? • What is your eye color? • What is your gender? State and string State is an important concept in OOP. the OOP value proposition might not be clear yet. Together. Encapsulation Recall that an object is above all discrete. you might do so using a String class. Encapsulation is a powerful feature of the Java language. Part 1: Java language basics Page 11 of 57 . protected nature of objects. you can vary the strength of that boundary on an object-byobject basis. the concepts of state and string allow you to say to Person: tell me who you are by giving me a listing (or String) of your attributes. Introduction to Java programming. inheritance. If you wanted to present a list of several of those attributes. The public/private boundary enforces the object-oriented principle of encapsulation. its state is defined by attributes such as name. Hiding is another term that is sometimes used to express the self-contained. which I'll talk more about later in the tutorial. On the Java platform.ibm. On the Java platform. the attributes of a person and any logic to retrieve (and convert) their values could be written in C or COBOL. objects used in computer programming have various types of relationships with different categories of objects in the applications that use them. Section 6. and the outside world. or self-contained. age. height. you can use access specifiers (which I'll introduce later in the tutorial) to vary the nature of object relationships from public to private. what's important is that the object maintains a boundary between its state and behavior. In the case of Person. and weight. Like objects in the real world. depending on a system of trust. An object's state is represented at any moment in time by the value of its attributes. Regardless of terminology. This is the principle of encapsulation at work. After all. whereas private access means the object's attributes are accessible only within the object itself. Public access is wide open. and polymorphism. This section clarifies the benefits of the OOP paradigm by explaining its defining principles: encapsulation.

In essence. Being the child of Person. it is common to copy a structure. it means that objects that belong to the same branch of a hierarchy. Inheritance at work Suppose you are writing a human-resources application and want to use the Person object as the basis for a new object called Employee. To understand how polymorphism applies to a business-application context. then you simply override them. You only change what you need to change in order to create specialized objects. when sent the same message (that is. Polymorphism is one of the more complex concepts you'll encounter in OOP on the Java platform and not within the scope of an introductory tutorial.developerWorks® ibm. whereby specialized objects — without additional code — can "copy" the attributes and behavior of the source objects they specialize. when told to do the same thing). Remember telling Person to format its attributes into a String? Polymorphism makes it possible for Person to represent its attributes in a variety of ways depending on the type of Person it is. If some of those attributes or behaviors need to change. Over time. along with additional ones. Introduction to Java programming. You'll see plenty of examples of inheritance in Java programming later in the tutorial. Part 1: Java language basics Page 12 of 57 . and the new specialization is called the child. See Resources if you want to learn more about polymorphism. OOP introduces the concept of inheritance. which can create maintenance issues.com/developerWorks/ Inheritance In structured programming. Polymorphism Polymorphism is a harder concept to grasp than encapsulation and inheritance. give it a new name. the source object is called the parent. return to the Person example. Employee would have all of the attributes of a Person object. such as: • Taxpayer identification number • Hire date • Salary Inheritance makes it easy to create the new Employee class of the object without needing to copy all of the Person code manually or maintain it. As you know from the Object-oriented programming concepts section. this approach generates a great deal of duplicated code. especially in Part 2. can manifest that behavior differently. and add or modify the attributes that make the new entity (such as an Account record) different from its original source.

The remainder of Part 1 focuses on the basics of the language. First. Getting started with the Java language The Java language: Not purely object-oriented The Java language lets you create first-class objects. it allows you to write code that exposes the inner workings of one object to any other object that uses it. The Java language does give you the tools necessary to follow sound OOP principles and produce sound object-oriented code. leaving you with enough knowledge and practice to write simple programs. Reserved words Like any programming language. you must exercise some discipline in how you write code — the language doesn't force you to do the right thing. Second. Because Java is not purely object-oriented. and as such you are not allowed to use them for naming your Java constructs.ibm.) It would be impossible to introduce the entire Java language syntax in a single tutorial. but not everything in the language is an object. Two qualities differentiate the Java language from purely object-oriented languages such as Smalltalk. Part 1: Java language basics . so you must do it yourself.com/developerWorks/ developerWorks® Section 7. the Java language designates certain words that the compiler recognizes as special. OOP is all about objects. so this section starts with two topics specifically related to how the Java language handles them: reserved words and the structure of a Java object. the Java language is a mixture of objects and primitive types. (This tutorial's last section. Writing good Java code. provides tips. The list of reserved words is surprisingly short: • • • • • • • • • • • • • • • • • abstract assert boolean break byte case catch char class const continue default do double else enum extends Page 13 of 57 Introduction to Java programming.

com/developerWorks/ final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Note that true. Although they are literals. Every object-oriented language has rules about how to define an object. One advantage of programming with an IDE is that it can use syntax coloring for reserved words. Part 1: Java language basics Page 14 of 57 . as you'll see later in this tutorial.developerWorks® • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • ibm. That means that it has a crisp boundary and a state and can do things when correctly asked. I included them in this list because you can't use them to name Java constructs. and null are technically not reserved words. Structure of a Java object Remember that an object is a discrete entity that contains attributes and behavior. false. Introduction to Java programming.

At times. Note: In Listing 1 and some other code examples in this section. The constructs shown in bold (which you'll find in the list of reserved words) are literals. import ClassNameToImport. You'll learn more about comments when you get to this tutorial's Writing good Java code section. you may end up using the same name to express two Introduction to Java programming.ibm. I'll explain all of the constructs in detail in the rest of this section. must be terminated with */. Person. objects are defined as demonstrated in Listing 1: Listing 1. or LizardMan. Object definition package packageName. accessSpecifier class ClassName { accessSpecifier dataType variableName [= initialValue]. A multiline comment begins with / *. Packaging objects The Java language lets you choose the names for your objects. although you can use adjacent single-line comments to form a block. A single-line comment must be contained on one line. Comments in code Notice that Listing 1 also includes some comment lines: // This is a comment /* This is a comment too */ /* This is a multiline comment */ Just about every programming language allows the programmer to add comments to help document the code. such as Account. The brackets themselves (unlike { and }) are not part of the Java syntax.com/developerWorks/ developerWorks® In the Java language. accessSpecifier ClassName([argumentList]) { constructorStatement(s) } accessSpecifier returnType methodName([argumentList]) { methodStatement(s) } // This is a comment /* This is a comment too */ /* This is a multiline comment */ } Listing 1 contains various types of constructs. Java syntax allows for both single-line and multiline comments. which I've differentiated with font formatting. and can span any number of lines. in any object definition. they must be exactly what they are here. Part 1: Java language basics Page 15 of 57 . square brackets indicate that the constructs within them are not required. The names that I've given the other constructs describe the concepts they represent.

* after the package name. Any nontrivial object uses other objects for some functionality. you must fully qualify it by including its namespace. A Java package is a mechanism for providing a namespace: an encapsulated area in which names are unique. Often package names are separated by dots. You specify the import keyword followed by the class that you want to import followed by a semicolon. or ibm.orgName. I recommend that you define all of your Java classes in packages. • orgName is the name of the organization's domain. sun.compName. You'll follow that convention throughout this tutorial. Packages also give you a nice way to build more complex applications into discrete units of functionality. and follow this de facto scheme: package orgType. you don't need to specify a package at all. Import statements Up next in the object definition (referring back to Listing 1) is the import statement. terminated with a semicolon. and the import statement is how you tell the Java compiler about them. meaning it should include its package. and it happens frequently. • appName is the name of the application. Package definition To define a package. For example.appName. abbreviated. An import statement usually looks like this: import ClassNameToImport.makotogroup package: Introduction to Java programming. or net. The class name should be fully qualified. This is called a name collision. An import statement tells the Java compiler where to find classes you reference inside of your code. but outside of which they might not be. in which case all of your objects must have unique class names and will reside in the default package. org. this statement imports every class in the com. This package definition breaks down like so: • orgType is the organization type such as com. In fact. As a best practice. • compName is the name of the component. The Java language uses packages to resolve these conflicts. Part 1: Java language basics Page 16 of 57 . such as makotogroup.com/developerWorks/ slightly different concepts. The Java language doesn't force you to follow this package convention.developerWorks® ibm. you can put . you use the package keyword followed by a legal package name. To identify a construct uniquely. To import all classes within a package.

The word object is often used synonymously with the word class. Think of a class as a template for an object.makotogroup. capitalize the first letter of each concatenated word. Strictly speaking.ibm. You'll look at other values of accessSpecifier soon. A variable has: Introduction to Java programming. but most of the time it is public. but the convention is to use CamelCase: start with a capital letter. These values are often referred to as instance variables.com/developerWorks/ developerWorks® import com. Listing 1 includes this class declaration: accessSpecifier class ClassName { accessSpecifier dataType variableName [= initialValue]. it displays a dialog box asking you which class you want to add imports for. you can type the name of a class you want to use. so I recommend that you import just the classes you need. a class defines the structure of a thing of which the object is an instance. The class defines the object's basic structure. If Eclipse finds two classes with the same name. followed by Ctrl+Shift+O. Sticking to these guidelines will ensure that your code is more accessible to other developers following the same conventions. however. Eclipse simplifies imports When writing code in the Eclipse editor. Part 1: Java language basics Page 17 of 57 . Classes can have two types of members: variables and methods. Variables The values of a given class's variables distinguish each instance of that class and define its state. Class names should contain only letters and numbers. Eclipse figures out which imports you need and adds them automatically. you must declare a class. and at run time your application creates an instance of the object. accessSpecifier ClassName([argumentList]) { constructorStatement(s) } accessSpecifier returnType methodName([argumentList]) { methodStatement(s) } } A class's accessSpecifier could have several values. Importing an entire package can make your code less readable. like a cookie cutter.*. and make all the other letters lowercase. Class declaration In order to define an object in the Java language. Class-naming conventions You can name classes pretty much however you want.

so the option exists. Basic class definition for Person package com.intro.) Example: Class definition for Person Before moving on to methods. here's an example that summarizes what you've learned so far. A variable's dataType depends on what the variable is — it could be a primitive type or another class type (again. private int weight. but by convention variable names use the CamelCase convention I described earlier. private int height. but in extremely rare cases it could be necessary. private String eyeColor. private String gender. except that they begin with a lowercase letter. can see the variable. private int age. even if tempted to do otherwise. • public: Any object in any package can see the variable. Part 1: Java language basics Page 18 of 57 . • private: Only the class containing the variable can see it.) Don't worry about the initialValue for now.developerWorks® • • • • An accessSpecifier A dataType A variableName Optionally. (This style is sometimes called lowerCamelCase. (Otherwise.) • protected: Any object defined in the same package. (Don't ever use this value. or a subclass (defined in any package). } Introduction to Java programming.makotogroup. an initialValue ibm. Listing 2 is a class definition for Person: Listing 2. The Java platform doesn't constrain your use cases. more about this later). The variableName is up to you. • No specifier (also called friendly or package private access): Only objects whose classes are defined in the same package can see the variable. the compiler generates a default for you that will be set when the class is instantiated. so it's up to you to be disciplined about using good coding conventions.com/developerWorks/ The possible accessSpecifier values are: Public variables It's never a good idea to use public variables. public class Person { private String name. just know that you can initialize an instance variable when you declare it.

the compiler will provide one for you. If you provide a constructor other than a no-argument (or no-arg) constructor. Other types of methods can be used for virtually any application behavior. There are essentially two categories of methods: constructors and all other methods — of which there are many types. called the default (or no-argument) constructor. The name of the constructor must match the name of the class. Listing 1 shows the constructor declaration syntax in abstract form. Constructor declaration syntax accessSpecifier ClassName([argumentList]) { constructorStatement(s) } Constructors are optional If you don't provide a constructor. Part 1: Java language basics Page 19 of 57 . A constructor's accessSpecifier is the same as for variables. Next you'll look in more detail at the two types of methods. Other times. A constructor method is used only to create an instance of a class. Constructor methods Constructors let you specify how to instantiate a class. the behavior can be quite complex. Looking back at Listing 1. it shows the way to define the structure of a method. Sometimes this behavior is nothing more than to return the current value of an attribute. which includes things like: • • • • accessSpecifier returnType methodName argumentList The combination of these structural elements in a method's definition is called its signature.com/developerWorks/ developerWorks® The basic class definition for Person isn't very useful at this point because it defines only its attributes (and private ones at that). Introduction to Java programming. starting with constructors. then the name of the constructor must also be Person. here it is again in Listing 3: Listing 3. To be more interesting. the Person class needs behavior — and that means methods. So if you call your class Person. the compiler will not generate one for you.ibm. Methods A class's methods define its behavior.

} } Note the use of the this keyword in making the variable assignments in Listing 4. but it needs more behavior. String eyeColor. Person class definition with a constructor package com. private int weight.developerWorks® ibm. private String eyeColor. public class Person { private String name. int height.gender = gender. Similarly. Other methods A constructor is a particular kind of method with a particular function.age = age. private String gender. and no two arguments can have the same name. this. Listing 4 shows how to create constructors and also how to use argumentList: Listing 4. many other types of methods perform particular functions in Java programs. Part 1: Java language basics Page 20 of 57 . Introduction to Java programming. argumentType is either a primitive type or another class type (the same as with variable types). Exploration of other methods begins in this section and continues throughout the tutorial. this.. this. int age.intro. String gender) { this. private int height. The Person object is getting more interesting. Class definition with a constructor Now you'll see what happens when you add the capability to create a Person object in two ways: by using a no-arg constructor and by initializing a partial list of attributes. And for that. which is one or more of: argumentType argumentName Arguments in an argumentList are separated by commas.makotogroup. is both a constructor parameter and a class variable). this. private int age. This is Java shorthand for "this object" and must be used when referencing two variables with the same name (as in this case where age. you pass an argumentList. } public Person(String name.height = height.com/developerWorks/ For any constructor other than the default constructor. public Person() { // Nothing to do.name = name. you need more methods. this.weight = weight. and helps the compiler disambiguate the reference.eyeColor = eyeColor. for example..

public class Person { private String name. Part 1: Java language basics Page 21 of 57 . (I've omitted constructors for brevity.com/developerWorks/ developerWorks® Back in Listing 1. Static and instance methods There are generally two types of (nonconstructor) methods: instance methods and static methods. you must tell the compiler by specifying the void return type in its signature. but you could define more in a similar fashion..) Listing 5." You''ll work more with getters and setters later in the tutorial.ibm. private int age. } // Other getter/setter combinations. you can see in Listing 5 see what happens when you add a few more methods to the Person object. } public void setName(String value) { name = value. Instance methods are dependent on the state of a specific Introduction to Java programming. there are rules). Note in Listing 5 that if a method doesn't return a value. and a setter is a method for modifying that value. • Use only alphabetic characters. • Avoid numbers unless absolutely necessary. private int height.. I showed you how to declare a method: accessSpecifier returnType methodName([argumentList]) { methodStatement(s) } Other methods look much like constructors. private String eyeColor. public String getName() { return name. For now. with a couple of exceptions. other methods have an optional return type. private String gender. I recommend the following conventions: • Start with a lowercase letter. Second. you can name other methods whatever you like (though. of course. I've shown only one getter/setter combination (for the Name attribute). private int weight.makotogroup. First. Person with a few new methods package com. unlike constructors.intro. all you need to know is that a getter is a method for retrieving the value of an attribute. Person's other methods Armed with this basic information. } Notice the comment in Listing 5 about "getter/setter combinations.

Part 1: Java language basics Page 22 of 57 . throughout this tutorial you'll use the JDK Logger class to output information to the console. because their behavior is not dependent on any single object's state. This section walks you through declaring a class and adding variables and methods to it using the Eclipse Package Explorer. you don't need an object instance. You're going to get set up to create your first Java class. and also how to use a main() method as a test harness. For example. instead. Your first Java object It's time to pull together what you've learned in the previous sections and start writing some code. you can think of them as a way of having global methods (à la C) while keeping the code itself grouped with the class that needs it. The first step is to create a place for the class to live. get to the Package Explorer perspective in Eclipse.developerWorks® ibm. Static methods are used largely for utility. just the name of the class. To create a Logger class instance. you'll create one specifically for the code you'll be writing. The syntax for invoking a static method is different from the syntax used to invoke a method on an object instance. Rather than use the default package (almost always a bad idea). Section 8. you invoke a static method called getLogger(). So to invoke a static method. You'll learn how to use the Logger class to keep an eye on your application's behavior. Packages are namespace constructs. Click File > New > Package to bring up the Java Package wizard. as shown in this invocation: Logger l = Logger. You also use the name of the class that contains the static method.getLogger("NewLogger"). A static method's behavior happens at the class level. you don't instantiate a Logger class. shown in Figure 4: Introduction to Java programming. Static methods are also sometimes called class methods.com/developerWorks/ object instance for their behavior. but they conveniently map directly to the file system's directory structure as well. Creating a package If you're not already there.

Part 1: Java language basics Page 23 of 57 . In the Name text box. check public static void main(String[] args).com/developerWorks/ developerWorks® Figure 4.ibm. (You'll see why shortly. Declaring the class There's more than one way to create a class from the Package Explorer. but the easiest way is to right-click on the package you just created and choose New > Class. click Finish.) Next. You will see the new package created in the Package Explorer. type Person.makotogroup. You will see the New Class dialog box.. I recommend closing a few of the views from their default appearance to make it easier to see your source code... Under Which method stubs would you like to create?.intro into the Name text box and click Finish. as shown in Figure 5: Introduction to Java programming. The new class appears in your edit window. The Eclipse Java Package wizard Type com.

Next. Now I'll formally define how to add class variables. You can configure how Eclipse generates new classes via Window > Preferences > Java > Code Style > Code Templates. indicating that I've made a modification. a variableName.com/developerWorks/ Eclipse generates a shell class for you and includes the package statement at the top. a dataType. This is just a small demonstration of the power of an IDE over using command-line tools for software development. optionally. along with the main() method you asked for and the comments you see. Earlier. Part 1: Java language basics Page 24 of 57 . The compiler could not find a reference to such a class and flagged it as a compile error (that's the wavy red line underneath Strin). Now you'll see the dataType that a variable can have. you looked briefly at how to define the accessSpecifier and variableName. you began to flesh out the Person class. A well-ordered workspace ibm. In Figure 5. notice that I made a mistake when declaring the Name attribute: I declared Name's type to be Strin. Of course. Recall that a variable has an accessSpecifier. I can fix my mistake by adding a g to the end of Strin. notice the asterisk (*) next to the new source-code file. You just need to flesh out the class now. but I didn't explain much of the syntax. Adding class variables In Listing 4.developerWorks® Figure 5. you'll go with Eclipse's out-of-the-box code generation. For simplicity. and. Introduction to Java programming. And notice that the code is unsaved. an initialValue.

ibm.util. notice that Age is an int (a primitive type). you need to know how your programs tell you what they are doing. Table 1 shows the eight primitive data types you're likely to see on a regular basis. and those in the java.util.lang package do not need to be imported (a shorthand courtesy of the Java compiler).lang. nonstatic) method.com/developerWorks/ developerWorks® A dataType can be either a primitive type or a reference to another object. If you are making a Logger call inside of a static method. The Java platform includes the java. Introduction to Java programming.0 Range of values true or false -128 to 127 \u0000' \u0000' to \uffff' or 0 to 65535 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807 1.logging package. the syntax is essentially the same.0 0. . Part 1: Java language basics Page 25 of 57 . like so: import java.class. a built-in logging mechanism for gathering program information in a readable form.getLogger(getClass().getLogger(Person. just get in the habit of passing the name of the class the code you're writing is located in.9e-324 to 1.getName()). The JDK comes packed full of useful classes like java. the code above will always reference the name of the class and pass that to the Logger.String. Logger l = Logger. For example. When calling the getLogger() method. But whether the dataType is a JDK class such as String or a user-defined class. For now. you pass it a String. Primitive data types Type boolean byte char short int long float double Size n/a 8 bits 16 bits 16 bits 32 bits 64 bits 32 bits 64 bits Default value false 0 (unsigned) 0 0 0 0.Logger. and Name is a String (an object). just reference the name of the class you're inside of: Logger l = Logger.7976931348623157e+308 Built-in logging Before going further into coding. including the default values that primitives take on if you do not explicitly initialize a member variable's value: Table 1.17549435e-38 to 3. Loggers are named entities that you create through a static method call to the Logger class. From any regular (that is.getName()). .logging. //.4028235e+38 4.

the code you're inside of is the Person class. Using main() as a test harness is a special method that you can include in any class so that the JRE can execute its code. but for the purpose of this tutorial. click Select All. so you reference a special literal called class that retrieves the Class object (more on this later) and gets its Name attribute. most never will — and a class can have at most one main() method.. you would use test libraries. on the word Person in the class definition).developerWorks® ibm. Part 1: Java language basics Page 26 of 57 . In enterprise development. When the dialog box opens. and go to Source > Generate Getters and Setters. you will use main() as your test harness.. A class is not required to have a main() method — in fact. put your mouse caret on the Person class definition (that is.com/developerWorks/ In this example.. Eclipse has a handy code generator to generate getters and setters (among other things). To try it out. main() is a handy method to have because it gives you a quick test harness for the class. main() Go into the Eclipse source code editor for Person and add code to make it look like Listing 4. This tutorial's Writing good Java code section includes a tip on how not to do logging. as shown in Figure 6: Introduction to Java programming.

There's more to main() Now you'll add some code to main() to allow you to instantiate a Person.gender = gender. Notice that the getters and setters appear after the main() method. this.ibm. choose Last member and click OK. this. String eyeColor.com/developerWorks/ developerWorks® Figure 6. String gender) { this. and then print those to the console.age = age. set a few attributes. Start by adding a constructor to Person. Introduction to Java programming. Person constructor public Person(String name. Part 1: Java language basics Page 27 of 57 . this. Type the code in Listing 6 into your source window just below the top part of the class definition (the line immediately beneath public class Person ()): Listing 6. int age. this.eyeColor = eyeColor. this. } Make sure you have no wavy lines indicating compile errors.weight = weight. int height.height = height. int weight.name = name. Eclipse generating getters and setters For the insertion point.

You're now ready to run your first Java program. select to run Person as a Java application. Part 1: Java language basics Page 28 of 57 . 82. Executing code in Eclipse To run a Java application from inside Eclipse. which reveals the basic structure of the Person class at a glance.info("Gender:" + p.info("Name: " + p.class.com/developerWorks/ Next.getGender()). l.developerWorks® ibm.getAge()). then click the Run icon (which is green and has a small triangular arrow pointing to the right).getName()). "MALE"). See Person run Notice that the Console view opens automatically and shows Logger output.getEyeColor()). l.info("Age:" + p. select the class you want to run. The main() method public static void main(String[] args) { Person p = new Person("Joe Q Author". 42.info("Height (cm):" + p. l. Currently. l. 173. Introduction to Java programming. l. "Brown".getLogger(Person. go into the main() method and make it look like Listing 7: Listing 7.getName()). then sit back and watch it go.info("Weight (kg):" + p. When asked. Just enter the code as you see it in Listing 7. You should see something like the screenshot in Figure 7: Figure 7. I have also selected the Outline view in the left-hand pane. Logger l = Logger. you have only one class — and it does have a main() method — so select Person.info("Eye Color:" + p.getWeight()). } Don't worry about the Logger class for now.getHeight()). l. which must have a main() method.

lang. creating behavior means adding methods. and do not return a value. a getter is an accessor method for retrieving the value of an attribute. whose type is java. as shown back in Figure 6.ibm. Part 1: Java language basics Page 29 of 57 . Suppose you have an attribute. a setter is an accessor method for modifying that value. } You may notice right away that the parameter value passed to the setter is named differently than if it had been generated by Eclipse. The naming of accessors follows a strict convention known as the JavaBeans pattern. Declaring accessors By far the easiest way to declare accessors is to let Eclipse do it for you. Adding behavior to a Java object is looking good so far. • Getters don't take any parameters and return a value whose type is the same as the attribute it accesses. Person Accessor methods In order to encapsulate a class's data from other objects.com/developerWorks/ developerWorks® Section 9. Foo. As you know.String. The JavaBeans pattern is so common that support for it is built right into the Eclipse IDE. whereby any attribute Foo has a getter called getFoo() and a setter called setFoo(). A complete declaration for it (following the accessor guidelines) would be: private String foo. } public void setFoo(String value) { foo = value. You've even already seen it in action — when you generated getters and setters for Person in the preceding section. the getters and setters you've already seen in action. As you've already learned. but it could use some additional behavior to make it more interesting. Accessors follow these guidelines: • The attribute itself is always declared with private access. • The access specifier for getters and setters is public. of the type of the attribute. and Introduction to Java programming. This is my own convention. But you should also know how to hand-code a getter-and-setter pair. This section looks more closely at accessor methods — namely. public String getFoo() { return foo. you declare its variables to be private and then provide accessor methods. You'll also learn syntax for calling methods. • Settings only take one parameter.

And you can separate the parameters with spaces and newlines. Part 1: Java language basics Page 30 of 57 . Using value as the setter's parameter value reminds me that this setter is special. 42. You saw in Listing 7 how to invoke the various getters of Person to return their values. a literal dot. The Java compiler doesn't care. (Code comments could also do that. "Brown". And here is a method invocation with parameters (accessing the Name attribute of Person): Person p = new Person("Joe Q Author".getName(). Method invocation with and without parameters To invoke a method on an object. 82. "Brown". or calling. Introduction to Java programming. This eyecatcher reminds that I've hand-coded the setter.someMethod(). 82.developerWorks® ibm.getLogger(Person. "MALE").getName()). 173. "Brown". Nested method invocation Method invocations can also be nested: Logger l = Logger. 42. too. the method name. 82. p. "MALE"). Here is a method invocation without parameters: Person p = /*obtain somehow */.someOtherMethod(parameter).info("Name: " + p. Because I usually allow Eclipse to generate getters and setters for me. Remember that constructors are methods. l. These next two method invocations are identical: new Person("Joe Q Author". I always use the name value as the parameter value to the setter.com/developerWorks/ one I recommend to other developers.) Calling methods Invoking.getName()). On the rare occasion that I do hand-code a setter. "MALE"). objectReference. Now I'll formalize the mechanics of making method calls. 42.class. new Person("Joe Q Author". when I don't there's a good reason for it. methods is easy. 173. and any parameters that need to be passed: objectReference. 173. Methodinvocation syntax comprises the object reference. you need a reference to that object.

) Introduction to Java programming. but there are several other ways to do that. you just use the name of the class itself as the left-hand side of the invocation. but without much explanation. Remember that the getLogger() method call is a static method call.info("Name: " + p. because the Java language creates a String object to hold the literal. instead.) You've already seen how to instantiate a String object and set its value (back in Listing 5).com/developerWorks/ developerWorks® Here you are passing the return value of Person. Section 10. and also find out when and how to use operators. which can hold a single Unicode character.ibm. strings are first-class objects of type String. but for now you don't need to worry about it. In the Java language. then assigns that object to the instance variable.class. with methods that help you manipulate them.getName() to the getLogger() method. Here are a couple of ways to create a String instance with a value of hello: String greeting = "hello". (The closest Java code gets to the C world with regard to strings is the char primitive data type. (You don't need a Logger reference to make the invocation. so its syntax differs slightly. Learn more about strings in this section. or combining. and the class has many helpful methods. Setting a variable of type String has the same result. Part 1: Java language basics Page 31 of 57 . Concatenating strings You can do many things with String. Strings Handling strings in C is labor-intensive because they're null-terminated arrays of 8-bit characters that you have to manipulate. Strings and operators The tutorial has so far introduced several variables of type String. Because Strings are first-class objects in the Java language. them: l.) That's really all there is to method invocation. The plus (+) sign is shorthand for concatenating Strings in the Java language. greeting = new String("hello"). you can use new to instantiate them. you've already done something interesting with two Strings by concatenating. such as a.getName()). (There is a performance penalty for doing this type of concatenation inside a loop. Without even using a method.

you've replaced it with firstName and lastName. you have a name instance variable. You don't need name anymore. Part 1: Java language basics Page 32 of 57 . private String firstName. The Java language uses two types of operators: • Unary: Only one operand is needed. } This code illustrates chaining of method calls. Operators As you might expect.developerWorks® Concatenation example ibm. but it would be nice to have a firstName and lastName. where a modification to an immutable object always returns the modification (but doesn't change the original). the Java language can do arithmetic. remove the setName() method.com/developerWorks/ Let's try concatenating Strings inside of the Person class. private String lastName. Java language's arithmetic operators Operator + Usage a + b Description Adds a and b + +a Promotes a Introduction to Java programming.concat(" "). and you've already seen how to assign variables. changed value. and change getName() to look like this: public String getName() { return firstName. The Java language's arithmetic operators are summarized in Table 2: Table 2. At this point.concat(lastName). The first thing you need to do is add the new instance variables (at the same location in the source code where name is currently defined): //private String name. Now I'll give you a brief look at some of the Java language operators you'll need as your skills improve. This is a technique commonly used with immutable objects like String. You then operate on the returned. Chaining method calls Now you can generate getters and setters for firstName and lastName (as shown back in Figure 6). You could then concatenate them when another object requests Person's full name. • Binary: Two operands are needed.

Part 1: Java language basics Page 33 of 57 . computes the value of a before incrementing ++ ++a Increments a by 1.com/developerWorks/ developerWorks® to int if it's a byte .b Subtracts b from a * -a a * b Arithmetically negates a Multiplies a and b / a / b Divides a by b % a % b Returns the remainder of dividing a by b (the modulus operator) ++ a++ Increments a by 1.ibm. computes the value of a after incrementing -a-Decrements a by 1. or char a . short . computes the value of a before decrementing ---a Decrements Introduction to Java programming.

learn about the various statements and operators you'll use to tell your Java programs how you want them to act based on different input.developerWorks® a ibm. programs that respond differently based on different input. Relational and conditional operators The Java language gives you operators and control statements that let you make decisions in your code. Conditional operators and control statements In this section. which delimit a comma-separated list of parameters to a method • new. one that evaluates to either true or false). Such expressions use relational operators. that is. Table 3 lists the relational and conditional operators of the Java language: Introduction to Java programming. For instance: • Period (. Most often.). You'll look at those in the next section. which compare one operand or expression to another. Part 1: Java language basics Page 34 of 57 . you've seen several other symbols that are called operators in the Java language. a decision in code starts with a boolean expression (that is.com/developerWorks/ by 1. computes the value of a after decrementing += -= *= %= a += b a -= b a *= b a %= b Shorthand for a = a + b Shorthand for a = a .b Shorthand for a = a * b Shorthand for a = a % b Additional operators In addition to the operators in Table 2. which (when followed by a constructor name) instantiates an object The Java language syntax also includes a number of operators that are used specifically for conditional programming. and conditional operators. which qualifies names of packages and invokes methods • Parentheses (()). Section 11.

ibm. Part 1: Java language basics Page 35 of 57 . a is greater than b >= a >= b a is greater than or equal to b < a < b a is less than b <= a <= b a is less than or equal to b == a == b a is equal to b != a != b a is not equal to b && a && b a and b are both true.. Relational and conditional operators Operator > Usage a > b Returns true if .. conditionally evaluates b (if a is false.com/developerWorks/ developerWorks® Table 3. b is not evaluated) || a || b a or b is true. conditionally evaluates b (if a is true. b Introduction to Java programming.

This code shows what happens when you add some logic to the Person object's getHeight() accessor: public int getHeight() { int ret = height.com/developerWorks/ The if statement Now that you have a bunch of operators. // If locale of the machine this code is running on is U. In this case.equals(Locale. A compound statement groups many statements into one — and compound statements can also contain other compound statements. then it might make sense to convert the internal value of height (in centimeters) to inches. Part 1: Java language basics Page 36 of 57 .getDefault(). which evaluates a boolean expression inside parentheses. if (Locale.US.// convert from cm to inches return ret.54. it's time to use them. always evaluates b | a | b a or b is true. it executes the next statement.. If you need to execute more than one statement. you only need to execute one statement if the Locale of the machine the code is running on is Locale.developerWorks® is not evaluated) ! !a a is false & a & b a and b are both true. you can use curly braces to form a compound statement. always evaluates b ^ a ^ b a and b are different ibm. } If the current locale is in the United States (where the metric system is not in use).S. If that expression evaluates to true. This example illustrates the use of the if statement. Introduction to Java programming.US)) ret /= 2.

That's when else comes in handy: public int getHeight() { int ret. nonstatic) methods. In this case. as shown in Listing 8: Listing 8. public void someMethod(String someParameter) { String someLocalVariable = "Hello". } someClassVariable = someParameter.getLogger("Person"). but outside of that method it is not. Within the if block. or localized namespace. where you can access it by name within the code. } The else statement works the same way as if. Take a few minutes to familiarize yourself with them."). Outside that space the variable is out of scope.. if (gender. // also legal someOtherLocalVariable = someLocalVariable. You can also use else to perform an additional if check. if (true) { String someOtherLocalVariable = "Howdy". else { ret = height.. and outside of that if block it is out of scope. and the same is true for someLocalVariable.com/developerWorks/ developerWorks® Variable scope Every variable in a Java application has scope. in that it executes only the next statement it runs across. someClassVariable is accessible by all instance (that is. // legal someLocalVariable = someClassVariable. Scope levels in the Java language are defined by where a variable is declared.// Variable out of scope! } public void someOtherMethod() { someLocalVariable = "Hello there".equals("MALE")) ret = height + 2.// That variable is out of scope! } } Within SomeClass. someParameter is visible.ibm. Scope has many rules. Within someMethod. someOtherLocalVariable is declared. Logger. two statements are grouped into a compound statement (notice the curly braces). Variable scope public class SomeClass { private String someClassVariable. which the program then executes. The else statement There are times in a program's control flow when you want to take action only if a particular expression fails to evaluate to true. } return ret. like so: Introduction to Java programming. and you will get a compile error if you try to access it.info("Being honest about height. Part 1: Java language basics Page 37 of 57 . but Listing 8 shows the most common ones.

If conditional evaluates to true. and the program jumps to the next statement after the final curly brace. then Block 2 is executed. then Block 1 is executed and the program jumps to the next statement after the final curly brace (which is indicated by // End). learn Introduction to Java programming. and another if it does not. like so: public int getHeight() { return (gender. then the program moves on to conditional3. If conditional2 is not true. statementIfFalse is executed. then statementIfTrue is executed. The ternary operator comes in handy when you know you will need to execute one statement as the result of the conditional evaluating to true. If conditional does not evaluate to true.developerWorks® if (conditional) { // Block 1 } else if (conditional2) { // Block 2 } else if (conditional3) { // Block 3 } else { // Block 4 } // End ibm. but they do make the code more readable. then conditional2 is evaluated. Section 12. Part 1: Java language basics Page 38 of 57 . otherwise. Loops In addition to being able to apply conditions to your programs and see different outcomes based on various if/then scenarios. you sometimes want your code just to do the same thing over and over again until the job is done.equals("MALE")) ? (height + 2) : height. If it is true. Ternary operators are most often used to initialize a variable (like a return value).com/developerWorks/ If conditional evaluates to true. In this section. Compound statements are not allowed for either statement. Its syntax is: (conditional) ? statementIfTrue : statementIfFalse. The ternary operator The Java language provides a handy operator for doing simple if/else statement checks. and so on. Only if all three conditionals failed would Block 4 be executed. } The parentheses following the question mark above aren't strictly required.

} } The local variable aa is initialized to zero at the beginning of the listing.info("Age:" + p. l. For instance.getHeight()). or loop over all the elements of an array. This statement executes only once.) for loops The basic loop construct in the Java language is the for statement. As you will see later. So long as loopWhileTrue (a Java conditional expression that must evaluate to either true or false) is true. processing each one. just note the use of the for loop syntax in Listing 9. l.info("Height (cm):" + p. 173. At the bottom of the loop. "MALE"). aa++) { Person p = new Person("Joe Q Author".info("Gender:" + p.getName()). which lets you iterate over a range of values to determine how many times to execute a loop. the loop will be executed.info("Weight (kg):" + p. Introduction to Java programming.com/developerWorks/ developerWorks® about two constructs used to iterate over code or execute it more than once: for loops and while loops. an alternate for loop syntax is available for looping over constructs that implement the Iterable interface (such as arrays and other Java utility classes).getName()).getGender()).class. l. Example of a for loop If you wanted to change a main() method to execute three times.info("Name: " + p. executeAtBottomOfEachLoop) { statementsToExecute } At the beginning of the loop. 82.info("Eye Color:" + p.getAge()). l. What is a loop? A loop is a programming construct that executes repeatedly while some condition (or set of conditions) is met.getLogger(Person. l.getWeight()).getEyeColor()). Part 1: Java language basics Page 39 of 57 . l. l. loopWhileTrue.info("Loop executing iteration# " + aa). For now. (You'll learn about arrays in this tutorial's Java Collections section. you might ask a program to read all records until the end of a file. for (int aa = 0. and each time aa is incremented by one. The loop then continues three times. A for loop public static void main(String[] args) { Logger l = Logger. aa < 3.ibm. executeAtBottomOfEachLoop is executed. you could use a for loop. 42. The abstract syntax for a for loop is: for (initialization. when the loop is initialized. "Brown". as shown in Listing 9: Listing 9. the initialization statement is executed (multiple initialization statements can be separated by commas).

while (aa < 3) { Person p = new Person("Joe Q Author".info("Name: " + p. You must initialize the aa variable and also remember to increment it at the bottom of the loop.getEyeColor()).getHeight()). do.while loop int aa = 0. "Brown"...getAge()). so the loop will execute. a while loop requires a bit more housekeeping than a for loop.getHeight()).while loops If you want a loop that will always execute once and then check its conditional expression.info("Age:" + p.info("Weight (kg):" + p. l. 173. the condition is evaluated.info("Loop executing iteration# " + aa). l. l.getGender()). aa++. Introduction to Java programming. int aa = 0. l. "MALE"). 82. 42.info("Height (cm):" + p. So it is possible that a while loop will never execute if its conditional expression is not true at least once.. 173.info("Name: " + p. l.info("Weight (kg):" + p. Listing 10 codes it using a while loop: Listing 10. Part 1: Java language basics Page 40 of 57 .getLogger(Person. l.while loop. l. try using a do...developerWorks® ibm.getName()). do { Person p = new Person("Joe Q Author".getAge()). A do.info("Eye Color:" + p.getWeight()).info("Eye Color:" + p.getName()). l. If true.. For comparison. } As you can see.getGender()).info("Gender:" + p.info("Height (cm):" + p. l. "MALE").getWeight()). while loopWhileTrue evaluates to true. "Brown".com/developerWorks/ while loops The syntax for a while loop is: while (loopWhileTrue) { statementsToExecute } As you might suspect.info("Loop executing iteration# " + aa). 42.getEyeColor()). as shown in Listing 11: Listing 11. l. before any statements execute).getName()). l. l.info("Age:" + p. Look again at the for loop in Listing 9. At the top of each iteration (that is. l. A while loop public static void main(String[] args) { Logger l = Logger.info("Gender:" + p.class. } while (aa < 3). 82. the loop executes. l. aa++.

l. For those times when you just want to bail. while (aa < 3) { if (aa == 1) continue.info("Name: " + p. int aa = 0. A continue statement public static void main(String[] args) { Logger l = Logger.getGender()).info("Gender:" + p. l. 42.getName()).info("Height (cm):" + p.info("Eye Color:" + p.getName()). else aa++.getLogger(Person.getGender()).info("Gender:" + p.getHeight()). l. shown in Listing 13: Listing 13.getEyeColor()).info("Age:" + p. 82.info("Weight (kg):" + p. l. 42. while (aa < 3) { if (aa == 1) break. l.getName()). you only want to execute the loop once and bail. Person p = new Person("Joe Q Author". as shown in Listing 12: Listing 12. l. l.ibm.class. Loop branching There are times when you need to bail out of a loop before the conditional expression evaluates to false. l. "MALE"). l. you didn't care about the other elements of the array.getAge()).getHeight()). l. This could happen if you were searching an array of Strings for a particular value.info("Loop executing iteration# " + aa). l. For that.info("Eye Color:" + p.getName()). you need the continue statement. } Introduction to Java programming. 82.getAge()). l. Loop continuation In the (simplistic) example in Listing 12. 173. l. and once you found it.info("Name: " + p.info("Loop executing iteration# " + aa).getLogger(Person. "MALE"). Part 1: Java language basics Page 41 of 57 . } The break statement takes you to the very next executable statement outside of the loop in which it's located.getEyeColor()).info("Height (cm):" + p. A break statement public static void main(String[] args) { Logger l = Logger.class. Person p = new Person("Joe Q Author". int aa = 0. aa++.getWeight()).info("Weight (kg):" + p.com/developerWorks/ developerWorks® The conditional expression (aa < 3) is not checked until the end of the loop. You can also skip a single iteration of a loop but continue executing the loop. "Brown". l. 173.getWeight()).info("Age:" + p. "Brown". the Java language provides the break statement.

processing records and come across a record you definitely don't want to process. 3. 4. Arrays Most programming languages include the concept of an array to hold a collection of things. Part 1: Java language basics Page 42 of 57 . Java Collections Most real-world applications deal with collections of things: files. Section 13. continue comes in handy when you are. This statement creates the array and initializes it all at once: // creates an array of 5 elements with values: int[] integers = new int[] { 1. and the Java language is no exception. Declaring an array In general. but it will introduce the most commonly used collection classes and get you started with using them. database result sets. This statement creates an array with space for five elements. but it is empty: // creates an empty array of 5 elements: int[] integers = new int[5]. The Java language has a sophisticated Collections Framework that allows you to create and manage collections of objects of various types. 5 }. An array is nothing more than a collection of elements of the same type. variables.com/developerWorks/ In Listing 13. which is fixed for the life of the array. you skip the second iteration of a loop but continued to the third. Just skip that record and move on to the next one. You can declare an array in one of two ways: • Create it with a certain size. • Create it with a certain set of initial values. not indicators of optional elements. 2. This section won't teach you everything about Java Collections. The size of this set determines the size of the array — it will be exactly large enough to hold all of those values. Introduction to Java programming. and so forth. say.developerWorks® ibm. you declare an array like this: new elementType [arraySize] There are two ways to create an integer array of elements. and its size is fixed for the life of the array. records from files. Note: The square brackets in this section's code examples are part of the required syntax for Java Collections.

the Java runtime will complain and throw an exception. for (int aa = 0. for (int aa = 0. you loop through the integers from 1 through the length of the array (which you get by calling .ibm.getLogger("Test"). Part 1: Java language basics Page 43 of 57 . you need the reference to the array (its name) and the index where the element you want resides. } This syntax (new since JDK 5) also works: Logger l = Logger. and into each bucket goes an element of a certain type. } I find the newer syntax simpler to work with. aa < integers.length. Introduction to Java programming. for (int i : integers) { l. aa++) { integers[aa] = aa. } This code declares the integer array of five elements.length.length on the array — more about that in a minute). Once the array is loaded. If you try to put more than five elements in the array.info("This little integer's value is: " + i). To access an element. In this case. and I'll use it throughout this section. aa++) { l. is length. as you've already seen. Access to each bucket is gained using an index: element = arrayName [elementIndex]. The length method A handy method. so its syntax doesn't include the usual parentheses. You'll learn about exceptions and how to handle them in Part 2. you can access it as before: Logger l = Logger.com/developerWorks/ developerWorks® The initial values go between the curly braces and are separated by commas.getLogger("Test"). you stop when you hit 5.info("This little integer's value is: " + integers[aa]). Loading an array To load the array. It's a built-in method. aa < integers. Arrays the hard way A harder way to create an array would be to create it and then code a loop to initialize it: int[] integers = new int[5]. The element index Think of an array as a series of buckets. Just type the word length and it will return — as you would expect — the size of the array.

the array is the Java language's most utilitarian collection.com/developerWorks/ Arrays in the Java language are zero-based.Integer objects isn't much different from creating an array of primitive types. for some array named array. In that sense.lang.developerWorks® ibm.lang. or box.Integer java.valueOf(4) Integer. Primitives and JDK counterparts Primitive boolean byte char short int long float double JDK counterpart java.lang.valueOf(3) Integer.Boolean java. Boxing and unboxing Every primitive type in the Java language has a JDK counterpart class.lang. but it's worth mentioning that they can also hold objects.Double Each JDK class provides methods to parse and convert from its internal representation to a corresponding primitive type.lang.Short java. // creates an array of 5 elements with values: Integer[] integers = new Integer[] { Integer. Once again.Long java. because you're putting the primitive into a wrapper. Introduction to Java programming. Creating an array of java.Float java.lang.valueOf(value).valueOf(1). and the last resides at array[array. Integer. So. For example. the first element in the array always resides at array[0].lang.length .Byte java. An array of objects You've seen how arrays can hold primitive types.1]. you have two ways to do it: // creates an empty array of 5 elements: Integer[] integers = new Integer[5].Character java. Part 1: Java language basics Page 44 of 57 . Integer boxedValue = Integer. which you can see in Table 4: Table 4.valueOf(2) Integer.lang.valueOf(5)). this code converts the decimal value 238 to an Integer: int value = 238. This technique is known as boxing.lang.

Instead. Integer boxedValue = intValue. and it defines a strict contract about how it behaves. too: String characterNumeric = "238". and thus more readable. like so: Integer boxedValue = Integer. You can also convert the contents of a JDK wrapper type to a String: Integer boxedValue = Integer. Autoboxing and auto-unboxing Strictly speaking. to convert the Integer representation back to its int counterpart.ibm. ArrayList: List List<Object> listOfObjects = new ArrayList<Object>(). Because a List is ordered. you could use the Java language's autoboxing and auto-unboxing features. so you can't instantiate it directly. A Java List collection can only hold objects. you would unbox it. I recommend that you avoid autoboxing and auto-unboxing.com/developerWorks/ developerWorks® Similarly. Introduction to Java programming. and wrapper types automatically have toString() invoked on them. Note that when you use the concatenation operator in a String expression (you've already seen this in calls to Logger). Lists A List is a collection construct that is by definition an ordered collection. You'll work with its most commonly used implementation. you don't need to box and unbox primitives explicitly.parseInt(characterNumeric).intValue(). like so: int intValue = 238. however. Part 1: Java language basics Page 45 of 57 . you have complete control over where in the List items go. The code in the boxing and unboxing snippets is more obvious. int intValue = boxedValue. also known as a sequence. but what about parsing a String you suspect has a boxed type into its proper box? The JDK wrapper classes have methods for that. // intValue = boxedValue. because it can lead to code problems.toString(). String characterNumeric = boxedValue. Parsing and converting boxed types You've seen how to obtain a boxed type. Integer convertedValue = Integer.valueOf(238). Pretty handy. the primitive type is autoboxed. than the autoboxed code. and I believe that's worth the extra effort. is an interface.valueOf(238).

call the add() method: List<Integer> listOfIntegers = new ArrayList<Integer>(). Formal type What's with the <Object> in the above code snip? It's called the formal type. You've already seen how to create an instance of List by instantiating its ArrayList implementation type. l.valueOf(238)). Let's try some of these out.get(0)). which means you can pretty much put whatever you like in the List.info("Item at index 0 is: " listOfIntegers. • Ask the List how big it currently is.valueOf(238)). To put something in a List. listOfIntegers.add(Integer.getLogger("Test").add(Integer. Part 1: Java language basics Page 46 of 57 . • Get something out of the List.info("Current List size: " + listOfIntegers. Logger l = Logger. call size(): List<Integer> listOfIntegers = new ArrayList<Integer>().valueOf(238)).developerWorks® ibm.size()). you'd define it differently: List<Person> listOfPersons = new ArrayList<Person>(). If you wanted to tighten up the constraints on what could or could not go into the List. To retrieve an item from the List. l. The add() method adds the element to the end of the List. We will look more at how variable assignments are affected in Part 2 in the Inheritance section. listOfIntegers.add(Integer. and it tells the compiler that this List contains a collection of type Object. Logger l = Logger. listOfIntegers. like Java collections in general. Java programming allows you to assign a variable of one type to another so long as the variable being assigned to is a superclass or interface implemented by the variable being assigned from. Now your List can only hold Person instances. call get() and pass it the index of the item you want: List<Integer> listOfIntegers = new ArrayList<Integer>().com/developerWorks/ Note that we have assigned the ArrayList object to a variable of type List. To ask the List how big it is. Using Lists Using Lists is super easy. Here are some of the things you will want to do with Lists: • Put something in the List. Introduction to Java programming.getLogger("Test"). so you'll start from there.

util. now here's a more realistic one: List<Integer> listOfIntegers = obtainSomehow(). } The first snip uses shorthand syntax: there is no index variable (aa in this case) to initialize.getLogger("Test").get(aa). } That little code snip does the same thing as this longer one: List<Integer> listOfIntegers = obtainSomehow(). a Set can only contain a given instance once... Here it is again: for (objectType varName : collectionReference) { // Start using objectType (via varName) right away. Part 1: Java language basics Page 47 of 57 .lang. Logger l = Logger. How do you do that in a generic fashion? You want to iterate over the collection. A Java Set collection can only hold objects. which you can do because List implements the java.getLogger("Test").size().ibm. aa++) { Integer I = listOfIntegers. Whereas a List can contain the same object hundreds of times. a List would contain records.com/developerWorks/ developerWorks® In a real-world application.Iterable.Collection. Sets A Set is a collections construct that by definition contains unique elements — that is. it is called an iterable collection. and you would possibly want to look over them all as part of your processing. You've already seen the special syntax for iterating over collections that implement the Iterable interface. you can use the shorthand syntax to iterate over any List. Introduction to Java programming.lang. and it defines a strict contract about how it behaves. Because List extends java. aa < listOfIntegers. } Iterating over a List That previous example was abstract. for (Integer i : listOfIntegers) { l.info("Integer value is : " + i). l. in the Loops section. no duplicates. which implements Iterable. for (int aa = 0.) Iterable If a collection implements java.info("Integer value is : " + i). and no call to the List's get() method. or business objects.Iterable interface. That means you can start at one end and walk through the collection item-by-item until you run out of items. (You'll learn about interfaces in Part 2. Logger l = Logger.

valueOf(11)). for (Integer i : setOfIntegers) { l. like so: Set<Integer> setOfIntegers = new HashSet().add(Integer.add(Integer. so I'll show you one of my favorite implementations: HashSet.valueOf(40)). } You might expect that the Set would have three elements in it. Here are some of the things you will want to do with Maps: Introduction to Java programming. Logger l = Logger. setOfIntegers. • Ask the Set how big it currently is. You'll see this for yourself if you paste the code above into the main() method of your Person class and run it.valueOf(10)). setOfIntegers. setOfIntegers.valueOf(10)). so I'll show you one of my favorite implementations: HashMap. you can't instantiate it directly. setOfIntegers.add(Integer. setOfIntegers.getLogger("Test").add(Integer. and it's used to retrieve the value at a later time.add(Integer.valueOf(20)). HashSet is easy to use and is similar to List.add(Integer. Keep this behavior in mind when iterating over a Set. } Chances are the objects will print out in a different order than you added them in because a Set guarantees uniqueness. Using Sets A Set's distinguishing attribute is that it guarantees uniqueness among its elements.info("Integer value is : " + i). Because Map is an interface. setOfIntegers. you can't instantiate it directly. but in fact it only has two because the Integer object that contains the value 10 will only be added once. Consider the following code: Set<Integer> setOfIntegers = new HashSet<Integer>(). As you might imagine. Here are some things you will want to do with a Set: • Put something in the Set. • Get something out of the Set. setOfIntegers. setOfIntegers.com/developerWorks/ Because Set is an interface. but doesn't care about the order of the elements.valueOf(10)). the key to the Map must be unique. and it defines a strict contract about how it behaves.add(Integer. Maps A Map is a handy collection construct because it lets you associate one object (the key) with another (the value). not order.valueOf(30)). for (Integer i : setOfIntegers) { l. Part 1: Java language basics Page 48 of 57 .valueOf(50)).add(Integer.info("Integer value is: " + i). A Java Map collection can only hold objects.developerWorks® ibm.

put("168".get("168"). mapOfIntegers. To retrieve a particular Integer value. and you simply want to walk over its entire set of contents. which happens to be their String representation. Integer. Map doesn't return a List of its keys because the Map is keyed. Integer> createMapOfIntegers() { Map<String. . mapOfIntegers.getLogger("Test"). mapOfIntegers. Logger l = Logger. • Get a Set of keys to the Map — for iterating over it. mapOfIntegers. for (String key : keys) { Integer value = mapOfIntegers. Integer oneHundred68 = mapOfIntegers. Part 1: Java language basics Page 49 of 57 . and each key is unique. Integer. you need its String representation: mapOfIntegers = createMapOfIntegers().put("1". Archiving Java code Now that you've learned a bit about writing Java applications. This section shows you how.valueOf(2)).com/developerWorks/ developerWorks® • Put something in the Map. } In this example.ibm. Introduction to Java programming. Map contains Integers. you need to have an object that represents its key and an object that represents its value: public Map<String. you will need a Set of the keys to the Map: Set<String> keys = mapOfIntegers. Integer. .info("Value keyed by '" + key + "' is '" + value + "'"). Integer. you may find yourself with a reference to a Map. Section 14. Integer> mapOfIntegers = new HashMap<String.put("2". Integer>(). uniqueness is the distinguishing characteristic of a Set.valueOf(3)). } Note that the toString() method of the Integer retrieved from the Map is automatically called when used in the Logger call. Using Set with Map On occasion. Using Maps To put something into a Map. you may be wondering how to package them up so that other developers can use them.get(key).put("3". • Get something out of the Map. // .valueOf(1)). In this case. l. or how to import code from other developers into your applications.keySet().valueOf(168)). keyed by a String.

Once you've packaged your code into a JAR file.developerWorks® ibm. Choose Java > JAR file. Click Finish.makotogroup. right-click the com. You can use the classes in it from your code if you put it in your build path in Eclipse. Introduction to Java programming. You'll see your JAR file in the location you selected. let's say that you wanted to use joda-time. Doing that is a snap. Part 1: Java language basics Page 50 of 57 . You use this tool to create JAR files. as you'll see next. manipulations. Creating a JAR file in Eclipse is a snap. Figure 8. Export dialog box. other developers can simply drop the JAR file into their projects and configure their projects to use your code. you will want to use more and more third-party applications to support your code. a JDK replacement library for doing date/time handling.jar extension is the default. and calculations. You'll see the dialog shown in Figure 8.intro package and select Export. For the sake of example.com/developerWorks/ JARs The JDK ships with a tool called JAR. Using third-party applications As you grow more comfortable with writing Java applications. When the next dialog box opens. The . In your workspace. which stands for Java Archive. browse to the location where you want to store your JAR file and name the file whatever you'd like. too. which I recommend using.

ibm. Now copy the joda-time . your first step is to create a lib directory in your project and drop the JAR file into it: 1. Choose New > Folder and call the folder lib. The new folder shows up at the same level as src.6. Right-click the Intro root folder in Project Explorer view. the class files) in the JAR file have been processed by Eclipse. Notice in Introduction to Java programming.jar file. 3. For this example. then select Properties.jar file into your project: 1. they are available to reference (import) from your Java code.jar file into your new lib directory. To use the classes. which is stored in a JAR file. 2. Properties > Java Build Path 3. Part 1: Java language basics Page 51 of 57 . select the Libraries tab.) Now all you need to do is tell Eclipse to include the classes in the joda-time-1. 2.6.com/developerWorks/ developerWorks® Let's assume you've already downloaded joda-time. select the joda-time-1.6. (It's common in naming a JAR file to include the version number. Once the code (that is. and click OK. Click the Add External JARs button. then browse to the project's lib directory. Click Finish. In the Properties dialog box. as shown in Figure 9: Figure 9.jar. Right-click the Intro project in your workspace. the file is called joda-time-1.

After generating getter/setter pairs for even the small number (by the standards of a real-world Java class) of attributes. Introduction to Java programming. but a name that conveys what a method does needn't be ridiculously long. probably computes interest. Certainly. This makes my application classes more maintainable. programmers have a tendency to give methods (and variables. yet for some reason. for that matter) small. In general. Name methods carefully A good coding pattern when it comes to method names is the intention-revealing method-names pattern.jar file. This pattern is easiest to understand with a simple example. a ridiculously long name can be inconvenient. If you need several helper methods that do essentially the same thing but take different parameters (such as the printAudit() method).developerWorks® ibm.com/developerWorks/ Project Explorer that there is a new Folder called Referenced Libraries that contains the joda-time-1. Keep classes small You created a few classes in this tutorial. The point to methods is to keep just the ones you need. This final section lays out a few best practices that will help you write cleaner. classes represent some conceptual entity in your application. that's a fine choice. and for similar reasons. abbreviated names. but it's obvious that a method called computeInterest().6. Keep methods small Small methods are just as preferable as small classes. It's not uncommon to see classes with 50 or 100 methods and a thousand lines of source (or more). Which of the following method names is easier to decipher at a glance? • a() • computeInterest() The answer should be obvious. and their size should reflect only the functionality to do whatever that entity needs to do. Part 1: Java language basics Page 52 of 57 . well. which means the first half of this tutorial is about to conclude. Writing good Java code You've got enough Java syntax under your belt to write basic Java programs. and no more. This is a small class. you may not remember what you meant to do with a method called a(). the Person class has 150 lines of code. Just be sure to limit the list of methods to what you need. One idiom I try to follow is to keep the size of a method to one page as I look at it on my screen. Six months after you write a bunch of code. They should stay tightly focused to do a small number of things and do them well. Section 15. more maintainable Java code.

• Your code probably isn't as well written as you'd like to think. I've found that a method doing only one thing well doesn't usually take more than about 30 lines of code. Period. six months down the road) will thank you.com/developerWorks/ developerWorks® If a method grows beyond one page.ibm. Having said that. yourself. Eclipse has a wonderful set of refactoring tools. Take this functionality and move it to another method (naming it accordingly) and pass in parameters as needed. Use comments Please. Eclipse does allow you to define code styles and format your code any way you like. so most code you run across (as in. Usually a long method contains subgroups of functionality bunched together. The main thing is that you pick a style and stick with it. it's standard. Limit each method to a single job. The people who follow along behind you (or even you. so who needs comments? I'll give you two reasons why this is false: • Most code is not well written. Use built-in logging Before Java 1. Use a consistent style Coding style is really a matter of personal preference. but might be paid to maintain) will most likely be written that way. the canonical way to find out what your program was doing was to make a system call like this one: Introduction to Java programming. code you didn't write. Refactoring means changing the design of existing code without changing its results. comment your code. use comments. Part 1: Java language basics Page 53 of 57 . but I would like to offer this piece of advice: use standard Java syntax for braces: public static void main(String[] args) { } Don't use this style: public static void main(String[] args) { } Or this one: public static void main(String[] args) { } Why? Well. I refactor it. You may have heard the old adage Well-written code is self-documenting. So.4 introduced built-in logging.

although the overall discussion will still be introductory in scope. you've learned about object-oriented programming. you will ultimately produce cleaner code and more functional applications than many of your peers. and I'm not alone) is Refactoring: Improving the Design of Existing Code. If everybody were good at both. } ibm. refactoring and the ability to write test-first code are the most important skills for new programmers to learn.out. it would revolutionize the industry... I never use System. Conclusion to Part 1 In this tutorial. (see Resources).println("Telling you all about it:").. by Martin Fowler et al. If you become good at both. and I suggest you don't use it either. You also know how to JAR up your applications for other developers to use in their programs. In the footsteps of Fowler The best book in the industry (in my opinion. In my opinion.com/developerWorks/ The Java language's built-in logging facility (refer back to Your first Java object) is a better alternative.println() in my code. Fowler and his co-authors talk about "code smells" that beg for refactoring. and they go into great detail about the various techniques for fixing them. // Now tell all about it System. you will begin learning about some of the more advanced constructs of Java programming. It's even fun to read. and familiarized yourself with an IDE that helps you control your development environment. Section 16. What's next In the second half of this tutorial. discovered Java syntax that lets you create useful objects..out.developerWorks® public void someMethod() { // Do some stuff. // Etc. Java programming topics covered in that tutorial include: • • • • • • Inheritance and abstraction Interfaces Nested classes Regular expressions Generics Enum types Page 54 of 57 Introduction to Java programming. and you've got some basic best Java programming practices under your belt. You know how to create and run Java objects that can do a good number of things. Part 1: Java language basics . including doing different things based on different input.

Part 1: Java language basics Page 55 of 57 . Part 2: Constructs for real-world applications.com/developerWorks/ developerWorks® • I/O • Serialization Read "Introduction to Java programming.ibm." Introduction to Java programming.

Connect with other developerWorks users while exploring the developer-driven blogs. Introduction to Java programming. including beginner tips for writing GC-friendly classes. • Refactoring: Improving the Design of Existing Code (Martin Fowler et al. • Javadoc homepage: Learn the ins and outs of using the Javadoc. groups. developerWorks.: This developerWorks series provides short introductions to lesser-known (but often introductory) Java programming tips and lore. 1999): This book is an excellent resource for learning how to write cleaner. • IBM developer kits: IBM provides a number of Java developer kits for use on popular platforms. an open-source MVC implementation" (Malcolm Davis.developerWorks® ibm.com/developerWorks/ Resources Learn • Java technology homepage: The official Java site has links to all things related to the Java platform. and wikis. including how to use the command-line tool and how to write your own Doclets that let you create custom formats for your documentation. • Eclipse: Download the Eclipse IDE for Java Developers. • "Struts. • Java 6: Learn more about JDK 6 and the tools that come with it. why it is important. Get products and technologies • JDK 6: Download JDK 6 from Sun (Oracle). • "Java theory and practice: Garbage collection and performance" (Brian Goetz. forums. Part 1: Java language basics Page 56 of 57 .. more maintainable code. • The developerWorks Java technology zone: Hundreds of articles about every aspect of Java programming. • 5 things you didn't know about . • The Java Tutorials: Get a comprehensive introduction to the Java language. Addison-Wesley. Discuss • Get involved in the My developerWorks community. and where to learn more about it. developerWorks. • Eclipse IDE project resources from developerWorks: Learn what Eclipse is good for. how you can get started with it. • New to Java technology: Check out this compendium of developerWorks resources for beginning Java developers.. January 2004): This article is an overview of garbage collection. including the Java language specification and Java API documentation.. February 2001): This article introduces the model-viewcontroller design pattern as it is implemented in one of the Java platform's oldest web development frameworks.

and general Java nut who has been developing software professionally since 1991. and the IBM developerWorks articles "Joda-Time" and OpenID for Java Web applications." In his spare time.ibm. rides his bike. architect.com/developerWorks/ developerWorks® About the author J Steven Perry J.ibm. © Copyright IBM Corporation 2010 (www. and teaches yoga.com/developerworks/ibm/trademarks/) Introduction to Java programming.shtml) Trademarks (www. Log4j (O'Reilly). Part 1: Java language basics Page 57 of 57 . he hangs out with his three kids.com/legal/copytrade. Steve has a passion for writing and mentoring. His professional interests range from the inner workings of the JVM to UML modeling and everything in between. Steven Perry is a software developer.ibm. he is the author of Java Management Extensions (O'Reilly).

Introduction to Java programming. introduces the more-sophisticated programming constructs required for building complex. Before you begin Find out what to expect from this tutorial and how to get the most out of it. regular expressions. Java I/O. © Copyright IBM Corporation 2010 Introduction to Java programming. Topics covered include exception handling. Inc. professional Java™ programmer J. generics. Part 2: Constructs for real-world applications More-advanced Java language features J Steven Perry Principal Consultant Makoto Consulting Group. Steven Perry introduced the Java language syntax and libraries you need to write simple Java applications. Skill Level: Introductory Date: 19 Aug 2010 In Part 1 of this tutorial. real-world Java applications. About this tutorial This second half of the "Introduction to Java programming" tutorial introduces capabilities of the Java language that are more sophisticated than those covered in Part 1. and Java serialization. About this series The two-part "Introduction to Java programming" tutorial is intended to get software developers new to Java technology up and running with object-oriented programming (OOP) and real-world application development using the Java language and platform. View more content in this series Section 1. still geared toward developers new to Java application development. Part 2. inheritance and abstraction. Part 2: Constructs for real-world applications Trademarks Page 1 of 53 .

System requirements The exercises in this tutorial require a development environment consisting of: • JDK 6 from Sun/Oracle • Eclipse IDE for Java Developers Download and installation instructions for both are included in Part 1. • Begin the programming project that you will continue developing in Part 2. The recommended system configuration for this tutorial is: • A system supporting JDK 6 with at least 1GB of main memory. including: • • • • • • • • • Exception handling Inheritance and abstraction Interfaces Nested classes Regular expressions Generics enum types I/O Serialization Prerequisites Develop skills on this topic This content is part of a progressive knowledge path for advancing your skills.developerWorks® ibm. See Become a Java developer The content of this tutorial is geared toward programmers new to the Java language who are unfamiliar with its more-sophisticated features. Part 1: Java language basics" in order to: • Gain an understanding of the basics of OOP on the Java platform. In this tutorial. The tutorial assumes that you have worked through "Introduction to Java programming. Part 2: Constructs for real-world applications Page 2 of 53 . Java 6 is supported on Linux®. you'll be introduced to features of the Java language that you will need to handle complex programming scenarios. Introduction to Java programming. and Solaris®.com/developerWorks/ Objectives The Java language is mature and sophisticated enough to help you accomplish nearly any programming task. • Set up the development environment for the tutorial examples. • At least 20MB of disk space to install the software components and examples covered. Windows®.

buffer. buffer.append(". Introduction to Java programming.append("Name=").append(".append(getHeight()).toString()). printAudit(sb). I'll call those methods printAudit(). buffer. you give the caller a choice of how to print an audit of the class. l.append(getName()). buffer. Suppose that Person needs a couple of methods to print an audit of its current state.append("."). buffer. buffer. buffer. you have two overloaded versions of printAudit().append(getAge()). buffer.append("Gender="). and one actually uses the other. printAudit(): An overloaded method public void printAudit(StringBuilder buffer) { buffer. you have an overloaded method."). Two rules of method overloading Remember these two important rules when using overloaded methods: • You can't overload a method just by changing its return type.append(getGender()). Here you will begin learning about techniques to enhance an object like Person. By providing two versions.append("Height="). the compiler will give you an error. buffer. Part 2: Constructs for real-world applications Page 3 of 53 .append("Weight=").append(getEyeColor()).append(".append("Age="). Overloaded methods are always in the same class.append(getWeight()). • You can't have two methods with the same parameter list.info(sb. but not as useful as it could be. } In this case."). buffer.append("EyeColor="). Depending on the parameters that are passed. buffer.").com/developerWorks/ developerWorks® Section 2. Next steps with objects Part 1 of this tutorial left off with a Person object that was reasonably useful. the Java runtime will call the correct method. } public void printAudit(Logger l) { StringBuilder sb = new StringBuilder(). buffer. buffer. the Java Runtime Environment (JRE. also known as the Java runtime) decides which variation of your overloaded method to call based on the arguments that have been passed to it. starting with the following techniques: • • • • Overloading methods Overriding methods Comparing one object with another Making your code easier to debug Overloading methods When you create two methods with the same name but with different argument lists (that is. Paste the overloaded method in Listing 1 into the Eclipse editor view: Listing 1.ibm. buffer. If you violate these rules.append(". At run time."). buffer. buffer. different numbers or types of parameters).

Once you have it set up.com/developerWorks/ Overriding methods When a subclass of another class provides its own implementation of a method defined on a parent class. Employee: A subclass of Person Recall from Part 1 of this tutorial that Employee might be a subclass (or child) of Person that has some additional attributes: • • • • Taxpayer identification number Employee number Hire date Salary To declare such a class in a file called Employee.. and the New Java Class dialog box will open.java. as shown in Figure 1: Figure 1. Part 2: Constructs for real-world applications Page 4 of 53 . Choose New > Class. New Java Class dialog Introduction to Java programming. that's called method overriding.developerWorks® ibm. you need to do some work on your Employee class. I'll be able to show you where method overriding comes in handy.. right-click the com. In order to see how method overriding is useful.makotogroup..intro package in Eclipse.

// TODO Auto-generated constructor stub } } Introduction to Java programming. weight.com/developerWorks/ developerWorks® Type Employee as the name of the class and Person as its superclass. String eyeColor.ibm. eyeColor. You don't explicitly need to declare a constructor.. First.makotogroup. make sure the Employee class edit window has the focus. You should now have an Employee class like the one in Listing 2: Listing 2. You will see the Employee class in an edit window. String gender) { super(name. then click Finish. age. and you'll see a dialog that looks like Figure 2: Figure 2. and click OK. int age. The new. int height. // TODO Auto-generated constructor stub } public Employee(String name.. int weight. Eclipse will generate the constructors for you.. improved Employee class package com. public class Employee extends Person { public Employee() { super(). Generate Constructors from Superclass dialog Check both constructors (as shown in Figure 2). Part 2: Constructs for real-world applications Page 5 of 53 . gender). height. then go to Source > Generate Constructors from Superclass.intro. but go ahead and implement both constructors anyway.

} // Other getter/setters. The solution is to override the overload of printAudit() that takes a StringBuilder as a parameter and add code to print the attributes specific to Employee.math. you're ready for an exercise in overriding methods. set its attributes. You'll override the printAudit() method (see Listing 1) that you used to format the current state of a Person instance. Part 2: Constructs for real-world applications Page 6 of 53 . However.com/developerWorks/ inherits the attributes and behavior of its parent. private String employeeNumber. and also has some of its own. } Method overriding: printAudit() Now.. import java.. as promised.BigDecimal. The problem is that it cannot format the attributes specific to an Employee. and you'll see a dialog box that looks like Figure 3: Introduction to Java programming. and invoke one of the overloads of printAudit(). The Employee class with Person's attributes package com. Person. public Employee() { super(). public class Employee extends Person { private String taxpayerIdentificationNumber. Employee inherits that behavior from Person. } public void setTaxpayerIdentificationNumber(String taxpayerIdentificationNumber) { this.makotogroup. as you can see in Listing 3: Employee Listing 3. } public String getTaxpayerIdentificationNumber() { return taxpayerIdentificationNumber. because Person doesn't know about them..intro. go to Source > Override/Implement Methods. and if you instantiate Employee. the call will succeed.taxpayerIdentificationNumber = taxpayerIdentificationNumber.. private BigDecimal salary. the audit that is produced won't fully represent an Employee.. To do this in your Eclipse IDE.developerWorks® Employee inherits from Person ibm.

ibm. it just seemed like a good idea to print those attributes first. and then you can just fill in the rest. Override/Implement Methods dialog Select the StringBuilder overload of printAudit.printAudit() method). } Notice the call to super."). Making the call to super.printAudit() at all. // Now format this instance's values buffer.com/developerWorks/ developerWorks® Figure 3. What you're doing here is asking the (Person) superclass to exhibit its behavior for printAudit(). If you don't call it.append(".append(getSalary(). buffer.toPlainString()). you don't need to call super. is easier. you must either format the attributes from Person yourself (in the Employee. as shown in Figure 3. Part 2: Constructs for real-world applications Page 7 of 53 . buffer. In fact.append(getEmployeeNumber()). like so: @Override public void printAudit(StringBuilder buffer) { // Call the superclass version of this method first to get its attribute values super. buffer. The call to super. buffer. and then you augment it with Employee-type printAudit() behavior.printAudit(buffer).").printAudit(). Eclipse will generate the method stub for you.append(getTaxpayerIdentificationNumber()). Introduction to Java programming. or exclude them altogether.append(".append("TaxpayerIdentificationNumber=").append("EmployeeNumber=").append("Salary="). and click OK.setScale(2). buffer. in this case.printAudit() doesn't need to be first.printAudit(). buffer. buffer.

• To track "counters" of instances of the class. the first time it encounters the class in a program). They are not part of the declaration syntax. The differences between class members and instance members are: • Every instance of a class shares a single copy of a class variable. You declare class members with the static keyword introduced in Part 1 of this tutorial. For example. Classes themselves can also have variables and methods. In contrast. because it is based on the state of the object instance. • On a class with utility methods that don't ever need an instance of the class (such as Logger. That makes class variables a good choice for constants that all instances should be able to use. • Instance methods can access class variables. The JRE creates space in memory to store each of a class's instance variables for every instance of that class. • You can call class methods on the class itself. All instances of the class will share that single copy of the variable. Adding class variables and methods When does it make sense to add class variables and methods? The best rule of thumb is to do so rarely. the JRE creates only a single copy of each class variable. Listing 4 shows a common use of class variables: Introduction to Java programming. what's generated by calling printAudit()) will be different. Every object instance has variables and methods.getLogger()). without having an instance. but class methods cannot access instance variables. To use them you either must instantiate the class you need or have a reference to the instance. Class variables To create a class variable. regardless of the number of instances. • Class methods can access only class variables. Note: The square brackets here indicate that their contents are optional. use the static keyword when you declare it: accessSpecifier static variableName [= initialValue]. Part 2: Constructs for real-world applications Page 8 of 53 .com/developerWorks/ Class members The variables and methods you have on Person and Employee are instance variables and methods. you declared the Gender attribute of Person to be a String. but you didn't put any constraints around it. which are called class members. so that you don't overuse them. it's a good idea to use class variables and methods: • To declare constants that any instance of the class can use (and whose value is fixed at development time). It does so the first time the class is loaded (that is. and for each one the exact behavior (for example.developerWorks® ibm. That said.

} Declaring constants Typically. you would simply reference its name. . // . GENDER_MALE).GENDER_MALE. . Declared with a public access specifier (so that they can be accessed by other classes that need to reference their values by name). like this: String genderValue = Person. Declared final (so that their values cannot be modified). // . constants are: • • • • Named in all uppercase. "Brown".ibm. Named as multiple words. Class methods are also sometimes called static methods for this reason. As with class variables. . to use the constant for MALE in the Person constructor call. the static keyword identifies Logger (in this example) as a class method. public static final String GENDER_MALE = "MALE".getLogger() several times — whenever you've retrieved a Logger instance to write some output to the console. you've already called the static method Logger. 42. Part 2: Constructs for real-world applications Page 9 of 53 . public static void main(String[] args) { Person p = new Person("Joe Q Author". which all instances will share. Listing 5 shows how: Introduction to Java programming. instead. . you'd preface it with the name of the class where it was declared. . Notice.You'll declare a private static final variable to hold a Logger. Using class methods Now you'll combine what you've learned about static variables and methods to create a static method on Employee. public static final String GENDER_FEMALE = "FEMALE". that you didn't need an instance of Logger to do this. and which will be accessible by calling getLogger() on the Employee class. To use a constant outside of the class. separated by underscores. 82. you referenced the Logger class itself. . Class methods If you've been following along since Part 1. though. In Listing 4. . 173. Using class variables public class Person { //.com/developerWorks/ developerWorks® Listing 4. . } //. This is the syntax for making a class method call.

For primitives. Creating a class (or static) method ibm. Part 2: Constructs for real-world applications Page 10 of 53 . it means that the values are identical. this is because you use the Java initializer syntax to give it a value. integer2 = new Integer(int2). Employee employee2 = new Employee().class.com/developerWorks/ public class Employee extends Person { private static final Logger logger = Logger.getLogger(). If you run the Listing 6 code inside Eclipse. l.getLogger(Employee. l. integer1 = new Integer(int1). the output should be: Introduction to Java programming. • The Logger is initialized when the class is loaded. int int2 = 1. //. . Integer integer1 = Integer.valueOf(int1). l. you make the following call: Logger employeeLogger = Employee. l. For objects. Consider the example in Listing 6: Listing 6. } } Two important things are happening in Listing 5: • The Logger instance is declared with private access. Comparing objects with == int int1 = 1. . Integer integer2 = Integer.info("Q: Integer1 == Integer2? A: " + (integer1 == integer2)).developerWorks® Listing 5.info("Q: Employee1 == Employee2? A: " + (employee1 == employee2)). public static Logger getLogger() { return logger.info("Q: int1 == int2? A: " + (int1 == int2)). To retrieve the Employee class's Logger object.getName()). Comparing objects The Java language provides two ways to compare objects: • The == operator • The equals() method Comparing objects with == The == syntax compares objects for equality such that a == b returns true only if a and b have the same value.info("Q: Integer1 == Integer2? A: " + (integer1 == integer2)). so no class outside Employee can access the reference directly.valueOf(int2). Employee employee1 = new Employee(). this means that the two refer to the same object instance.

intro.intro.equals(employee2)). By default a Java program would simply check to see if the two objects were the same using the == syntax. Part 2: Constructs for real-world applications Page 11 of 53 . the values of the primitives are the same. 2010 5:30:10 AM com. *l.getLogger(Employee. Integer integer1 = Integer.intro.makotogroup. it should be clear why employee1 == employee2 returns false. 2010 5:43:53 AM com.Employee INFO: Q: int1 == int2? A: true Apr 19.Employee main INFO: Q: integer1.class. so again == returns true.equals(integer2)). so the == operator returns true.ibm. A: " + integer1. You call equals() just as you would any other method: a.Employee main Introduction to Java programming.Object (which every Java object inherits from). passing to it a reference to object b. In the second case.Employee main INFO: Q: integer1 == integer2? A: true Apr 19.equals(integer2)? A: " + (integer1 == integer2)). This statement invokes the equals() method of object a.info("Q: employee1 == employee2 ? A: " + (employee1 == employee2)). l.Employee INFO: Q: Employee1 == Employee2? A: false main main main main In the first case in Listing 6. however. Consider the example from Listing 6.equals(employee2) ? A : " + employee1.equals(b).intro.equals(integer2)? integer1 = integer2 = l. Employee employee1 = new Employee().makotogroup. because it is defined as an instance method of java. Based on this.info("Q: l. Integer integer2 = Integer. Comparing objects with equals() equals() is a method that every Java language object gets for free. A: " + integer1.com/developerWorks/ developerWorks® Apr 19. new Integer(integer2). In the third case.equals(integer2)). the Integer objects refer to the same instance.valueOf(1).info("Q: new Integer(integer1). 2010 5:30:10 AM com.info("Q: integer1.makotogroup.info("Q: integer1 == integer2? l.makotogroup.Employee INFO: Q: Integer1 == Integer2? A: true Apr 19. Comparing objects with equals() Logger l = Logger. A: " + (integer1 == integer2)).info("Q: employee1.intro. == returns false because integer1 and integer2 refer to different objects. even though the Integer objects wrap the same value. integer1 == integer2? integer1.getName()). Because equals() is a method.makotogroup.valueOf(1). 2010 5:43:53 AM com. 2010 5:30:10 AM com. modified in Listing 7 to compare the two objects using equals(): Listing 7. 2010 5:30:10 AM com.makotogroup. l.equals(integer2)? A: true Apr 19.Employee INFO: Q: Integer1 == Integer2? A: false Apr 19. Employee employee2 = new Employee().lang. 2010 5:43:53 AM com.makotogroup.intro.* Running this code produces: Apr 19.intro. it can be overridden.

2010 5:43:53 AM com. and would instead return true in cases in which the underlying int value is the same.equals(employee2)? A: false ibm. this means that for any object you write. you did not override equals(). you can define what equals() means as appropriate for the application you are writing. The dialog box in Figure 4 will appear: Introduction to Java programming. 2010 5:43:53 AM com. you can use Eclipse to do this.Employee main INFO: Q: integer1.Employee main INFO: Q: employee1. where you create separate objects that both wrap the value 1: == returns false because integer1 and integer2 refer to different objects.Employee main INFO: Q: employee1 == employee2? A: false Apr 19. For Employee.intro.intro.intro.makotogroup. Make sure Employee has the focus in your Eclipse IDE's Source window. Again. 2010 5:43:53 AM com. The writers of the JDK decided that for Integer. Part 2: Constructs for real-world applications Page 12 of 53 . Overriding equals() You can define what equals() means to your application's objects by overriding the default behavior of Object. given that employee1 and employee2 do in fact refer to different objects.makotogroup. but equals() returns true. but notice what happens in the second case.equals().com/developerWorks/ A note about comparing Integers In Listing 7. so the default behavior (of using ==) returns what you would expect. it should be no surprise that the equals() method of Integer returns true if == returns true. Basically.makotogroup. the meaning of equals() would be different from the default (which is to compare the object references to see if they refer to the same object).developerWorks® INFO: Q: integer1 == integer2? A: false Apr 19.equals(integer2)? A: true Apr 19. then go to Source > Override/Implement Methods.

Autogenerating equals() Eclipse can generate an equals() method for you based on the instance variables (attributes) you've defined for a class. Because Employee is a subclass of Person. Override/Implement Methods dialog You've used this dialog before.com/developerWorks/ developerWorks® Figure 4. you'll first generate equals() for Person. and click OK. right-click Person and choose Generate hashCode() and equals() to bring up the dialog box shown in Figure 5: Introduction to Java programming. but in this case you want to implement the Object. age — are the same.ibm. Part 2: Constructs for real-world applications Page 13 of 53 . Eclipse will generate the correct code and place it in your source file. That is. In Eclipse's Project Explorer view.equals() superclass method. they're equal if their values — last name. It makes sense that the two Employee objects are equal if the states of those objects are equal. first name. find Object in the list. So. check the equals(Object) method.

An equals() method generated by Eclipse @Override public boolean equals(Object obj) { if (this == obj) return true.gender != null) return false. if (gender == null) { if (other.getClass()) return false. } else if (!eyeColor. if (height != other. if (getClass() != obj.equals(other. if (age != other.age) return false. } else if (!name.equals(other. if (eyeColor == null) { if (other.developerWorks® Figure 5. if (name == null) { if (other.weight) Introduction to Java programming.height) return false. Eclipse will generate an equals() method that looks like the one in Listing 8: Listing 8. Part 2: Constructs for real-world applications Page 14 of 53 .com/developerWorks/ Select all attributes (as shown in Figure 5) and click OK.eyeColor)) return false.gender)) return false. if (weight != other.name != null) return false. Generate hashCode() and equals() dialog ibm.name)) return false. } else if (!gender.eyeColor != null) return false. Person other = (Person) obj. if (obj == null) return false.equals(other.

makotogroup. Part 2: Constructs for real-world applications Page 15 of 53 . l. then each attribute value of the object passed in is checked to see if it matches value-for-value with the state of the given Person instance. If the attribute values are null (meaning missing) then the equals() will check as many as it can. and if those match.equals(employee2)? A: " + employee1. The equals() method generated by Eclipse looks complicated. but what it does is pretty simple: if the object passed in is the same object as the one in Listing 8.equals(employee2)). in a method called (no surprise) toString(). } Don't worry about hashCode() for now — you can keep it or delete it. but it works for most purposes. you were right! Formatting the state of an object into a String is such a common pattern that the designers of the Java language built it right into Object itself. the objects will be considered equal. Feel free to add more attributes to this example and see what you get.Employee main INFO: Q: employee1 == employee2? A: false Apr 19. employee1.getName()). If that's true. you'll make the default toString() a little more useful.Employee main INFO: Q: employee1. return true. 2010 5:26:50 PM com. Introduction to Java programming. l.ibm. 2010 5:26:50 PM com. Employee employee1 = new Employee(). You may not want this behavior for every program. If the object passed in is null. In this exercise. add the following code above it: public static void main(String[] args) { Logger l = Logger. Exercise: Override toString() Remember the printAudit() method from the beginning of this section? If you thought it was working a little too hard. employee2. Exercise: Generate an equals() for Employee Try following the steps in Autogenerating equals() to generate an equals() for Employee.setName("J Smith").getLogger(Employee. then equals() will return true.intro. you should see the following output: Apr 19. } If you run the code.info("Q: employee1 == employee2? A: " + (employee1 == employee2)).class. Once you have your generated equals(). After that.info("Q: employee1. Employee employee2 = new Employee(). but every object has one. it will return false.com/developerWorks/ developerWorks® return false. a match on Name alone was enough to convince equals() that the two objects were equal.makotogroup.intro. the method checks to see if the Class objects are the same (meaning the passed-in object must be a Person object). The default implementation of toString() is not very useful.equals(employee2)? A: true In this case.setName("J Smith").

if only for support purposes. The code generated by Eclipse for Employee is shown in Listing 9: Listing 9. salary=" + salary + ".toString() + "Employee [employeeNumber=" + employeeNumber + ".. Go back into your Project Explorer and right-click the Employee class.. } now does the heavy lifting of formatting the object's current state. salary=" + salary + ". then choose Source > Generate toString(). In this section. you are correct. } The addition of toString() makes printAudit() much simpler: @Override public void printAudit(StringBuilder buffer) { buffer. Exceptions No program ever works 100 percent of the time. } The code Eclipse generates for toString doesn't include the superclass's toString() (Employee's superclass being Person). A toString() method generated by Eclipse @Override public String toString() { return "Employee [employeeNumber=" + employeeNumber + ". and the designers of the Java language knew this. You can fix that in a flash. using Eclipse. learn about the Java platform's built-in mechanisms for handling situations where your code doesn't work exactly as planned.append(toString()).. taxpayerIdentificationNumber=" + taxpayerIdentificationNumber + "]". It's virtually inevitable that at some point you'll want to see what an object's state is while your application is running. Section 3. Part 2: Constructs for real-world applications Page 16 of 53 . and toString() is a great hook for doing that. You'll see a dialog box similar to the one in Figure 5.com/developerWorks/ If you suspect that Eclipse can generate a toString() method for you.developerWorks® ibm. and you simply stuff what it returns into the StringBuilder and return. Choose all attributes and click OK. toString() I recommend always implementing toString() in your classes. Introduction to Java programming. taxpayerIdentificationNumber=" + taxpayerIdentificationNumber + "]". with this override: @Override public String toString() { return super.

catch. and finally: Listing 11. Fortunately. and finally Listing 11 shows the buggy code from Listing 10 cleaned up with the standard code blocks for exception handling try.equals(employee2)).getName()). public class Employee extends Person { // . In essence.. employee1. . public static void main(String[] args) { Employee employee1 = new Employee(). Catching an exception // .getName()).class.ibm. you can use try and catch blocks to catch it (along with a little help from finally). private static Logger logger. } Notice that the initializer for the static variable holding the Logger reference has been commented out. employee2.equals(employee2)? A: " + employee1. catch.setName("J Smith").setName("J Smith"). Employee employee2 = new Employee().getLogger(Employee. try. take a look at the code in Listing 10: Listing 10. logger. To get started with exception handling.intro. .lang. employee2.// = Logger. . .equals(employee2)? A: " + employee1. employee1.getLogger(Employee.class.. . public class Employee extends Person { // . Employee employee2 = new Employee(). Exception handling is an essential technique of Java programming.info("Q: employee1. logger. logger.info("Q: employee1 == employee2? A: " + (employee1 == employee2)).info("Q: employee1 == employee2? A: " + (employee1 == employee2)).makotogroup. and use it to catch various types of exceptions.com/developerWorks/ developerWorks® Exception-handling basics An exception is an event that occurs during program execution that disrupts the normal flow of the program's instructions.info("Q: employee1. Part 2: Constructs for real-world applications Page 17 of 53 . logger. Do you see the error? // . Run this code and you'll get the following output: Exception in thread "main" java. private static Logger logger. Introduction to Java programming.main(Employee.Employee.equals(employee2)).// = Logger.setName("J Smith"). public static void main(String[] args) { try { Employee employee1 = new Employee().NullPointerException at com. .java:54) This output is telling you that you are trying to reference an object that isn't there. .setName("J Smith"). . } catch (NullPointerException npe) { // Handle. you wrap your code in a try block (which means "try this and let me know if it causes an exception"). which is a pretty serious development error.

the try. catch. as you saw in Listing 10... } catch (Exception e) { // Handle more general exception here. whether or not an exception has been thrown. you can try to recover gracefully from it. then the child classes are placed ahead of the parent classes in the order of the catch blocks.com/developerWorks/ System. First. The exception hierarchy The Java language incorporates an entire exception hierarchy consisting of many types of exceptions grouped into two major categories: • Checked exceptions are checked by the compiler (meaning the compiler will make sure that they get handled somewhere in your code). If it does. then prints out a message to report what happened. or you can exit the program (or method). Here's an example: try { // Code here. If it doesn't find one by the time if reaches the top of the stack.. } catch (NullPointerException e) { // Handle NPE. This is followed by a comma-separated list of exceptions the method could potentially throw during the course of its execution. If your code calls a method that specifies that it throws one or more types of exceptions. } finally { // Always executes } } Together. When you catch an exception.println("Yuck! Outputting a message with System. In the event of an exception. • Unchecked exceptions (also called runtime exceptions) are not checked by the compiler. Part 2: Constructs for real-world applications Page 18 of 53 . you say it throws the exception. you must handle it somehow. the program recovers from the error.out.. If any exceptions are subclasses of other exceptions. and finally blocks form a net for catching exceptions. execution continues to the finally block. or exception handler.developerWorks® ibm. the Java language runtime searches for an exception handler somewhere up the stack..out. When a program causes an exception. In Listing 11. the try statement wraps code that might throw an exception. or add a throws to your method signature to pass that exception type along. } Introduction to Java programming. When all the trying and catching is done. Multiple catch blocks You can have multiple catch blocks. but they must be structured in a particular way. it will halt the program abruptly.. execution drops immediately to the catch block. A checked exception is declared to the compiler by any method with the keyword throws in its method signature.println() " + "because the developer did something dumb!").

See Resources to learn more about exception handling in Java programs. Elements of a Java application All Java applications need an entry point where the Java runtime knows to start executing code. You've been working since Part 1 on the example of a human-resources application that includes Person and its Employee subclasses. Now you'll see what happens when you add a new class to the application.ibm. evolves into an application. That entry point is the main() method. you will continue building up Person as a Java application. so it must be placed ahead of the more general Exception catch block.com/developerWorks/ developerWorks® In this example. Notice that this simple driver for the human-resources application contains a main() method: package com.makotogroup. the NullPointerException is a child class (eventually) of Exception. Eclipse will generate the class for you. Creating a driver class The purpose of a driver class (as its name implies) is to "drive" an application. You've seen just a tiny glimpse of Java exception handling in this tutorial. being sure to select the option to add a main() method to the class. Section 4. Building Java applications In this section. Part 2: Constructs for real-world applications Page 19 of 53 . Domain objects typically don't have main() methods. Name the class HumanResourcesApplication. The topic could make a tutorial on its own. public class HumanResourcesApplication { public static void main(String[] args) { } } Create a driver class in Eclipse using the same procedure you used to create Person and Employee. or collection of objects. Along the way. you'll get a better idea of how an object. but at least one class in every application must. Add some code to your new main() so that it looks like this: Introduction to Java programming.intro.

. How inheritance works Classes in Java code exist in hierarchies.getLogger(Person. This section reviews some of Part 1's material on inheritance and explains in more detail how inheritance works — including the inheritance hierarchy.intro. name=J Smith. gender=null.setName("J Smith"). You should see this output (with the backslashes here indicating a line continuation): Apr 29. .Person printAudit INFO: Person [age=0. The java. e. Classes above a given class in a hierarchy are superclasses of that class. . . e. Part 2: Constructs for real-world applications Page 20 of 53 .com/developerWorks/ Now launch the HumanResourcesApplication class and watch it run.printAudit(log). .makotogroup. e.setEmployeeNumber("0001"). eyeColor=null.developerWorks® public class HumanResourcesApplication { . 2010 6:45:17 AM com.\ taxpayerIdentificationNumber=123-45-6789] That's really all there is to creating a simple Java application. e. height=0. salary=null.class). and inheritance abstraction. That particular class is a subclass of every class higher up the hierarchy. public static void main(String[] args) { Employee e = new Employee(). Section 5. you'll begin looking at some of the syntax and libraries that will help you develop more-complex applications. and inherits from.Object class is at the top of the class hierarchy. meaning every Java class is a subclass of. Inheritance You've encountered examples of inheritance a few times already in this tutorial. Object. private final Logger log = Logger. constructors and inheritance. For example. suppose you have a Person class that looks like the one in Listing 12: Introduction to Java programming. A subclass inherits from its superclasses.lang.setTaxpayerIdentificationNumber("123-45-6789"). In the next section. . } ibm. } .\ weight=0]Employee [employeeNumber=0001. .

private int age. as well as Object (because it actually extends that class. Its class definition (or inheritance graph) would look something like this: public class Employee extends Person { private String taxpayerIdentificationNumber. } The Person class in Listing 12 implicitly inherits from Object. // . private String gender. . private String employeeNumber. In this case. Public Person class package com. you don't need to type extends Object for every class you define. public Person() { //Nothing to do.com/developerWorks/ developerWorks® Listing 12.makotogroup.Object. public static final String GENDER_FEMALE = "FEMALE". So the class hierarchy for any given Java class always consists of a straight line all the way up to java. Part 2: Constructs for real-world applications Page 21 of 53 . Person can see and use Object's public methods and variables and Object's protected methods and variables.lang. Introduction to Java programming. Because that's assumed for every class. single inheritance Languages like C++ support the concept of multiple inheritance: at any point in the hierarchy a class can inherit from one or more classes. // . But what does it mean to say that a class inherits from its superclass? It simply means that Person has access to the exposed variables and methods in its superclasses. Defining a class hierarchy Now suppose you have an Employee class that inherits from Person. private BigDecimal salary. private int weight. // . I'll introduce you to multiple interfaces later in the tutorial. private int height. private String eyeColor. } private String name. The Employee inheritance graph implies that Employee has access to all public and protected variables and methods in Person (because it directly extends it). . the Java language supports implementing multiple interfaces in a single class. .. .ibm. which means you can only use the extends keyword with a single class. which gives you a workaround of sorts to single inheritance.. too. } Multiple vs. . public class Person { public static final String GENDER_MALE = "MALE".intro. However. . though indirectly). However. The Java language supports only single inheritance.

. To go one step deeper into the class hierarchy. For example. From Employee's default constructor. and it has no return type. suppose Person has a constructor that takes the name of the Person object being created. you could create a third class that extends Employee: public class Manager extends Employee { // . The preceding class definition and this one are identical in how they function: public class Person { } Invoking a superclass constructor To invoke a superclass constructor other than the default constructor. . the compiler will generate one for you. you could invoke the Person constructor shown in Listing 13: Introduction to Java programming. and if you don't explicitly define a constructor for your class. any class can have at most one superclass. Before I go into that. I'll review some basic rules about how constructors are defined and invoked. you must do so explicitly. but a class can have any number of subclasses. For example: public class Person { public Person() { } } Every class has at least one constructor.com/developerWorks/ because Employee and Person are in the same package. Employee also has access to the package-private (sometimes called friendly) variables and methods in Person. instead. That is the most important thing to remember about inheritance hierarchy in the Java language. Constructors and inheritance Constructors aren't full-fledged object-oriented members. } In the Java language.developerWorks® ibm. Constructor basics Remember that a constructor always has the same name as the class it is used to construct. called the default constructor. Part 2: Constructs for real-world applications Page 22 of 53 . you must explicitly implement them in subclasses. so they aren't inherited.

It's much less confusing from a maintenance standpoint. these two declarations are functionally identical.name = name. it's a good idea to implement superclass constructors in subclasses if you think you will need them. and Java syntax in general.java public class Employee extends Person { public Employee(String name) { super(name). Until you get more comfortable with object-oriented concepts. Part 2: Constructs for real-world applications Page 23 of 53 . } } // Meanwhile.java public class Employee extends Person { public Employee() { } } Or: Introduction to Java programming.name = name. in Employee. in Employee. however.java public class Employee extends Person { public Employee() { super("Elmer J Fudd"). public Person(String name) { this. Listing 14 defines a constructor in Employee that looks like the one in Person so that they match up. and invoke them homogeneously. so pick one: public class Person { public Person() { } } // Meanwhile. } } You would probably never want to initialize a new Employee object this way. Listing 14. public Person() { } public Person(String name) { this. in Employee. } } Declaring a constructor The first thing a constructor does is invoke the default constructor of its immediate superclass. unless you — on the first line of code in the constructor — invoke a different constructor. For example.com/developerWorks/ developerWorks® Listing 13. } } // Meanwhile. Initializing a new Employee public class Person { private String name.ibm. Invoking a superclass homogeneously public class Person { private String name.

it's not really a default. Introduction to Java programming.java You will see this idiom frequently. in Employee. or it is not available. because there are conditions under which it is not included. passing in some default value if that constructor is invoked. It's also a great way to add a new constructor to a class while minimizing impact on code that already uses an older constructor. For example: public class Person { private String name.name = name. Just like super(). For example. } } ibm.developerWorks® public class Person { public Person() { } } // Meanwhile. public Person() { this("Some reasonable default?").java public class Employee extends Person { public Employee() { super(). This is why the default constructor is sometimes called the no-argument (or no-arg) constructor. How constructors invoke constructors A constructor from within a class can be invoked by another constructor using the this keyword. } } // Meanwhile. in Employee. the following code would give you a compile error: public class Person { private String name. in Employee. public Person(String name) { this. the this() call must be the first line in the constructor. you must explicitly provide the default constructor. because it provides an alternate constructor without explicitly including the default constructor. } } // Meanwhile. } public Person(String name) { this.java public class Employee extends Person { public Employee() { } } This example has no default constructor. where one constructor delegates to another. Part 2: Constructs for real-world applications Page 24 of 53 . along with an argument list.name = name.com/developerWorks/ No-arg constructors If you provide an alternate constructor.

or that a method call won't call what you think it will. In that case. say. or even in a different method altogether). This can cause you no end of grief as you gain proficiency in Java programming. a static method would be used to create instances of the class. Constructor can be invoked by any class in the same package. By default. Constructor access rules Constructor access modifier public protected No modifier (package-private) private Description Constructor can be invoked by any class. Eclipse will provide ample warnings that you are hiding a variable from a superclass. but how is a private constructor useful? I've used private constructors when I didn't want to allow direct creation of an object through the new keyword when implementing. the variable is visible to the code trying to access it). Table 1 summarizes the rules of constructor access: Table 1. provided the caller has access to the variable (that is. In an OOP context. would be allowed to invoke the private constructor: Inheritance and abstraction If a subclass overrides a method from a superclass. not the superclass's version. however. this can be done from any line in the subclass method. the Factory pattern (see Resources). being included in the class itself. The subclass can invoke the superclass method by prefacing the name of the method with the super keyword (and unlike with the constructor rules. and certain rules of visibility apply. Part 2: Constructs for real-world applications Page 25 of 53 . Constructor can be invoked only by the class in which the constructor is defined. Constructor can be invoked by an class in the same package or any subclass. You may be able to think of use cases where constructors would be declared protected or even package-private.com/developerWorks/ developerWorks® Constructor access levels Constructors can have any access level you want.ibm. The main reason for doing this is to reuse common code by pushing it as far up the hierarchy as possible. Introduction to Java programming. Having common code in one place makes it easier to maintain. When you move variables or methods from a subclass to a superclass. abstraction refers to generalizing data and behavior to a type higher up the inheritance hierarchy than the current class. The same applies to variables. you say you are abstracting those members. and that method. that method is essentially hidden because calling that method through a reference to the subclass invokes the subclass's version of the method. a Java program will call the subclass method if it is invoked through a reference to the subclass. This isn't to say the superclass method is no longer accessible.

Part 2: Constructs for real-world applications Page 26 of 53 . and you're done: public abstract class Employee extends Person { // etc. Here are some basic rules for abstract classes and methods: • • • • Any class can be declared abstract. You simply declare it using the abstract keyword. you will find that there are times when certain methods need to be implemented differently for each subclass that implements the superclass. } Every direct subclass of Employee (such as Manager) is now required to implement the validate() method. Using abstraction Suppose you don't want to allow the Employee class to be instantiated directly. By the same token.com/developerWorks/ There are times when you will want to create classes that only serve as abstractions and do not necessarily ever need to be instantiated. This definition would be perfectly valid: Introduction to Java programming. you'll get a compile error: public void someMethodSomwhere() { Employee p = new Employee(). Abstract classes cannot be instantiated. once a subclass has implemented the validate() method.developerWorks® Abstract classes and methods ibm.// compile error!! } The compiler is complaining that Employee is abstract and cannot be instantiated. However. Any class with an abstract method must be declared abstract. } If you try to run this code. but would behave sufficiently differently among all potential subclasses that there is zero potential for reuse. This need would seem to be common to all Employee objects. An abstract method cannot contain a method body. In that case. you declare the validate() method abstract (forcing all subclasses to implement it): public abstract class Employee extends Person { public abstract boolean validate(). For example. The power of abstraction Suppose that you need a method to examine the state of an Employee object and make sure it is valid. suppose you have an Executive object that extends Manager. none of its subclasses need to implement it. Such classes are called abstract classes. Such methods are abstract methods.

let them remain nonabstract. it's possible for assignments of objects with different inheritance graphs (such as Manager and Employee) to be assigned to a variable of the wrong type. // wrong! The destination variable must be of a supertype of the class belonging to the source reference. Basically. Employee e = new Employee(). Remember. or the compiler will give you an error. Consider the trade-off between classes that are too large and maintainable code. Eclipse has wonderful support for refactoring. Using abstract classes early in the design forces you down a certain path. Part 2: Constructs for real-world applications Page 27 of 53 . whatever is on the right side of the assignment must be a subclass or the same class as the thing on the left. // still okay e2 = p. Person p = m. If not. Consider this example: Manager m = new Manager(). it is most definitely not a Manager. and that could restrict your application. Deep inheritance graphs can make code maintenance difficult. Interfaces Introduction to Java programming. common behavior (which is the entire point of having abstract classes) can always be refactored further up the inheritance graph. Assignments: Classes When assigning a reference from one class to a variable of a type belonging to another class. // still okay Employee e2 = e. Let's look at this example: Manager m = new Manager(). // okay Employee e = p. Person p = m. but there are rules. and the compiler enforces this. Second. // okay p = e. It is almost always better to do this once you've discovered that you do need it. Unless your superclasses contain lots of common behavior. Section 6. // yep. okay e = m. and on their own are not really meaningful.ibm. resist the use of abstract classes when you can. you can do so. // wrong! While an Employee is a Person. as powerful as they are. don't abstract in your initial design.com/developerWorks/ developerWorks® public class Executive extends Manager { public Executive() { } } When (not) to abstract: Two rules As a first rule of thumb. // so far so good Employee e = m.

actually defining an interface is easy: public interface StockOptionRecipient { void processStockOptions(int numberOfOptions. because they mark a class as implementing that interface but offer no special explicit behavior. (Remember. BigDecimal price).. but by convention interface names look like class names. You define hierarchies of interfaces.com/developerWorks/ In this section. In fact. just as you do for classes. Methods defined in an interface have no method body. like this: public class Manager extends Employee implements BonusEligible.) If one class extends another and implements interface(s). then the interfaces are listed after the extended class. The implementer of the interface is responsible for providing the method body (just as with abstract methods). a class can extend only one class. except that a single class can implement as many interfaces as it wants to. You can name the interface anything you want to (subject to language rules). such interfaces are called marker interfaces. Defining an interface is straightforward: public interface interfaceName { returnType methodName( argumentList ). except that you use the interface keyword. Part 2: Constructs for real-world applications Page 28 of 53 . StockOptionRecipient { // Etc. } An interface declaration looks like a class declaration. An interface specifies what behavior the implementation provides. Defining an interface An interface is a named set of behaviors (and/or constant data elements) for which an implementer must provide code. } Introduction to Java programming.developerWorks® ibm. Once you know all that. } Marker interfaces An interface does not need to have any body at all. begin learning about interfaces and start using them in your Java code. but not how it is accomplished. the following definition is perfectly acceptable: public interface BonusEligible { } Generally speaking..

choose Add Unimplemented Methods. which means you can refer to an interface anywhere you would refer to a class. but it isn't required to implement all of the methods on that interface. Generating interfaces in Eclipse Eclipse can easily generate the correct method signature for you if you decide one of your classes should implement an interface. Introduction to Java programming. Implementing an interface public class Manager extends Employee implements StockOptionRecipient { public Manager() { } public void processStockOptions (int numberOfOptions. An abstract class can declare that it implements a particular interface.ibm. you implement it.info("I can't believe I got " + number + " options at $" + price.toPlainString() + "!"). BigDecimal price) { log. press Ctrl + 1. placing them at the bottom of the source file. as shown in Listing 16. Just change the class signature to implement the interface. You do that with the implements keyword: public class className extends superclassName implements interfaceName { // Class Body } Suppose you implement the StockOptionRecipient interface on the Manager class. Click the class name with your mouse. the first one that can be instantiated) must implement all methods the hierarchy does not. the first concrete class (that is. You must implement the methods with signatures that match the ones on the interface. However.com/developerWorks/ developerWorks® Implementing interfaces To use an interface. This is because abstract classes aren't required to provide implementations for all of the methods they claim to implement. which simply means providing a method body. you provide behavior for the method(s) on the interface. with the addition of the public access modifier. Part 2: Constructs for real-world applications Page 29 of 53 . Eclipse puts a red squiggly line under the class. Of these. Using interfaces An interface defines a new reference data type. or cast from one type to another. which in turn provides the behavior to fulfill the interface's contract. and Eclipse will generate the methods for you. } } When you implement the interface. flagging it to be in error because the class doesn't provide the method(s) on the interface. This includes when you declare a reference variable. as shown in Listing 15: Listing 15. and Eclipse will suggest "quick fixes" for you.

//okay Employee e = soe. StockOptionEligible soe = m. public static void calculateAndAwardStockOptions(StockOptionEligible soe) { BigDecimal reallyCheapPrice = BigDecimal.processStockOptions(numberOfOptions. . a nested class is one defined within another class. } As you can see. but it is not. this might at first seem okay. Part 2: Constructs for real-world applications Page 30 of 53 . reallyCheapPrice). Assignments: Classes When assigning a reference from a class that implements an interface to a variable of an interface type. The reason is that the Manager class implements that interface. but there are rules. we see that assigning a Manager instance to a StockOptionEligible variable reference is perfectly valid.valueOf(0.// works too } . Here is a nested class: Introduction to Java programming. int numberOfOptions = 10000. Where to use nested classes As its name suggests. soe. it is *different* and in this particular case implements an interface that Employee does not. you may only assign an interface reference to a variable of the same type or a superinterface type.// perfectly valid calculateAndAwardStockOptions(soe). the following assignment would not be valid: Manager m = new Manager().com/developerWorks/ Listing 16.developerWorks® ibm. Section 7. learn about nested classes and where and how to use them. From Listing 16.01). Nested classes In this section. as well as to pass a new Manager instance to a method that expects a StockOptionEligible reference. Assigning a new Manager instance to a StockOptionEligible reference public static void main(String[] args) { StockOptionEligible soe = new Manager(). However. And just like with classes. // Wrong! Because Employee is supertype of Manager. Assignments such as these follow the rules of assignment we saw in Inheritance. you can do so. . Because Manager is a specialization of Employee. calculateAndAwardStockOptions(new Manager()). it is perfectly valid to assign a new Manager instance to a StockOptionEligible reference.

directReports = new DirectReports(). it seems like you could give the DirectReports class public scope. For example. . private. as shown in Listing 17: Introduction to Java programming. . Part 2: Constructs for real-world applications Page 31 of 53 . Typically. it is bound by the rules of scope. } } Just like member variables and methods. } . A nested class has access to the private data within its enclosing class. so I've made it private. } } Just as each Manager object represents a unique human being. . it makes sense that one would only reference the DirectReports nested class in the context of its enclosing instance of Manager. but this functionality is limited to the class where you need it. only Manager can create an instance of DirectReports. which is a collection of the Employees that report to that Manager: public class Manager extends Employee { private DirectReports directReports. . you'll use a nested class for cases where you need a class that is tightly coupled with the class in which it is defined. public class NestedClass { . public Manager() { this. Public nested classes Because it's private. a member variable can only be accessed through an instance of the class (an object). the DirectReports object represents a collection of actual people (employees) who report to a manager. . or protected. But suppose you wanted to give an external entity the ability to create instances of DirectReports? In this case. . but this carries with it some side-effects that are not obvious when you start working with nested (or inner) classes.com/developerWorks/ developerWorks® public class EnclosingClass { . DirectReports will differ from one Manager to another. Scope in nested classes Because a nested class has scope. and then any external code could create DirectReports instances. The same is true of a nested class. . . Suppose you have the following relationship between a Manager and a nested class called DirectReports. In this case. Java classes can also be defined at any scope including public.ibm. private class DirectReports { . Nested classes can be useful when you want to handle internal processing within your class in an object-oriented fashion.

right? Well. } } // Meanwhile. which is used to compare two instances of the same class. The problem (and also its solution) lies with the way DirectReports is defined within Manager. followed by the class you want to create. and you're probably wondering why. One common example of this is to implement a Comparator. That's where static inner classes come into play.. usually for the purpose of ordering (or sorting) the classes: Introduction to Java programming. and with the rules of scope. Manager. in another method somewhere. .developerWorks® ibm.DirectReports().DirectReports dr = manager. . } Note that the syntax calls for a reference to the enclosing instance. at least as you defined it in Listing 17. you use a special version of the new operator.// This won't work! } The code in Listing 17 doesn't work. Combined with a reference to some enclosing instance of an outer class.DirectReports dr = new Manager. . To create an instance of a public nested class.com/developerWorks/ Listing 17. not requiring a reference to an enclosing instance. . . Static inner classes At times you will want to create a class that is tightly coupled (conceptually) to a class.new DirectReports(). you would expect the compiler to require you to have a reference to a Manager object before you could reference it. Creating DirectReports instances: First attempt public class Manager extends Employee { public Manager() { } .. . private class DirectReports { . plus a dot and the new keyword. } } // public static void main(String[] args) { Manager. public static void main(String[] args) { Manager manager = new Manager(). revisited If you had a member variable of Manager. the same applies to DirectReports. but where the rules of scope are somewhat relaxed. . Part 2: Constructs for real-world applications Page 32 of 53 . private class DirectReports { . . The rules of scope. new allows you to create an instance of the nested class: public class Manager extends Employee { public Manager() { } .

Anonymous inner classes The Java language allows you to declare classes pretty much anywhere. soe. in the case of a utility class like ManagerComparator. } .valueOf(0.// perfectly valid handleStockOptions(employee). in another method somewhere. . Clearly. } } // Meanwhile.ManagerComparator mc = new Manager. .com/developerWorks/ developerWorks® public class Manager extends Employee { . . you don't need an enclosing instance.processStockOptions(numberOfOptions. and they should really only be used when you need to couple a class tightly with its definition. Handling Employee types that are not StockOptionEligible public static void main(String[] args) { Employee employee = new Manager(). } }). and even without providing a name for the class.. int numberOfOptions = 10000. but there are times when anonymous inner classes are extremely handy to have. } else { calculateAndAwardStockOptions(new StockOptionEligible() { @Override public void awardStockOptions(int number. . reallyCheapPrice).// not StockOptionEligible handleStockOptions(employee).01).. private static void calculateAndAwardStockOptions(StockOptionEligible soe) { BigDecimal reallyCheapPrice = BigDecimal. } In this case. Static inner classes act like their regular Java class counterparts. . .info("Sorry. you provide an implementation of the StockOptionEligible interface by using an anonymous inner class for instances of Employee that do not implement Introduction to Java programming. Part 2: Constructs for real-world applications Page 33 of 53 . BigDecimal price) { log. .ibm. . public static class ManagerComparator implements Comparator<Manager> { . even in the middle of a method if necessary. public static void main(String[] args) { Manager. } } . you're not StockOptionEligible!"). . This is basically a compiler trick.ManagerComparator(). Defining such classes as static inner classes is the way to go. employee = new Employee(). Listing 18 builds on the example in Listing 15. . adding a default method for handling Employee types that are not StockOptionEligible: Listing 18. private static void handleStockOptions(Employee e) { if (e instanceof StockOptionEligible) { calculateAndAwardStockOptions((StockOptionEligible)e). . creating an external class is unnecessary and potentially clutters up your code base. } In this example.

you'll take a look at the regex pattern syntax. Before you do that. Once you understand the syntax. This is where regular expressions can look a bit strange.com/developerWorks/ that interface. and in event handling.developerWorks® ibm. You'll begin working on a simple regular-expressions pattern that uses these classes shortly. Section 8. The Regular Expressions API Here's a set of strings that have a few things in common: • A string • A longer string • A much longer string Note that each of these strings begins with a and ends with string. • Matcher tests a string to see if it matches the pattern. Part 2: Constructs for real-world applications Page 34 of 53 . however. ? What qualifies as a match Any character Zero (0) or one (1) of what came before Introduction to Java programming. If you're not used to regular expressions syntax. This section gets you started with using regular expressions in your Java programs. Regular expressions A regular expression is essentially a pattern to describe a set of strings that share that pattern. too. it can look weird. If you're a Perl programmer. see the pattern among them. however. though. it becomes easier to decipher. Table 2 lists some of the most common regex constructs that you will use in pattern strings: Table 2. Common regex constructs Regex construct . Anonymous inner classes are also useful for implementing callback methods. The Java Regular Expressions API (see Resources) helps you pull out these elements. Regex pattern syntax A regex pattern describes the structure of the string that the expression will try to find in an input string. and do interesting things with the information you've gleaned. The Regular Expressions API has three core classes that you'll use almost all the time: • Pattern describes a string pattern. • PatternSyntaxException tells you that something wasn't acceptable about the pattern that you tried to define. you should feel right at home with the regular expression (regex) pattern syntax in the Java language.

compile("a. [0-9]) Any nondigit (alternatively. That call creates a Matcher instance. followed by string.ibm. You can access that information by calling various methods on Matcher: Introduction to Java programming. Logger. the Matcher contains information about matches found (or not found) in the input string. because they quantify what comes before them. boolean didMatch = matcher. [^\n\t\f\r]) Any word character (alternatively. Every Java language string is an indexed collection of characters. "notwhatever") Any digit (alternatively. the Matcher searches the string you passed in for matches against the pattern string you used when you created the Pattern. After that process completes. Matcher matcher = pattern. starting at 0. Pattern matching Armed with the pattern syntax in Table 2. you can work through the simple example in Listing 19.start().info (patternStartIndex). Listing 19 calls matcher() on Pattern. the English translation of the pattern is: Find a string of the form a followed by zero or more characters. int patternEndIndex = matcher.com/developerWorks/ developerWorks® * + [] ^ \d \D \s \S \w \W Zero (0) or more of what came before One (1) or more of what came before A range of characters or digits Negation of whatever follows (that is. [a-zA-Z_0-9]) Any nonword character (alternatively. The Matcher parses the string. [\n\t\f\r]) Any nonwhitespace character (alternatively.getAnonymousLogger(). Any character that doesn't have special meaning in a pattern is a literal and matches itself. [^\w]) The first few constructs are called quantifiers. Logger. Methods for matching Next. with a string literal representing the pattern you want to match. int patternStartIndex = matcher.info (didMatch).*string"). and looks for matches against it.matches().matcher("a string"). When that happens. Constructs like \d are predefined character classes. That literal uses the regex pattern syntax. which is a static method on Pattern.end(). starting with 0 and ending with the string length minus one. [^0-9]) Any whitespace character (alternatively. Part 2: Constructs for real-world applications Page 35 of 53 . Pattern matching with regex Pattern pattern = Pattern. First.info (patternEndIndex). Logger. Listing 19 creates a Pattern class by calling compile().getAnonymousLogger(). In this example. using the classes in the Java Regular Expressions API: Listing 19.getAnonymousLogger().

the call to matches() returns true. each of which begins with an uppercase letter. then SomeWikiWord. Complex patterns in regex Simple searches are easy with the regex classes.*string and get a match if you use lookingAt(). Part 2: Constructs for real-world applications Page 36 of 53 .com/developerWorks/ • matches() tells you if the entire input sequence was an exact match for the pattern. is a web-based system that lets users modify pages. lookingAt() searches for substring matches for a given pattern. and the call to end() returns 8. Wikis are based almost entirely on regular expressions. Their content is based on string input from users.matcher(input). lookingAt() vs.find()) { Logger. because there's more to the string than just what's in the pattern. which is parsed and formatted using regular expressions. then YetAnotherWikiWord. • end() tells you the index value in the string where the matched string ends. you could use lookingAt() instead of matches(). You could search it for a.". Pattern pattern = Pattern. which is typically a series of concatenated words.developerWorks® ibm. consider the following string: Here is a string with more than just the pattern. Thus. assume the following string: Here is a WikiWord followed by AnotherWikiWord. plus one. You could search for wiki words in this string with a regex pattern like this: [A-Z][a-z]*([A-Z][a-z]*)+ And here's some code to search for wiki words: String input = "Here is a WikiWord followed by AnotherWikiWord. } Introduction to Java programming.compile("[A-Z][a-z]*([A-Z][a-z]*)+").group()). A wiki. as you surely know. matches() If there were more elements in your string than the characters in the pattern you searched for.info("Found this wiki word: " + matcher. Matcher matcher = pattern.getAnonymousLogger(). it would return false. Listing 19 finds a single match starting at 0 and ending at 7. Any user can create a link to another topic in a wiki by entering a wiki word. For example. • start() tells you the index value in the string where the matched string starts. while (matcher. the call to start() returns 0. But if you use matches(). like this: MyWikiWord Knowing that about wikis. but you can also do some highly sophisticated things with the Regular Expressions API.

getAnonymousLogger(). Pattern pattern = Pattern. then SomeWikiWord.". you would've seen this: Before: Here is a WikiWord followed by AnotherWikiWord.ibm.matcher(input). Using Matcher's replace methods is straightforward: String input = "Here is a WikiWord followed by AnotherWikiWord. This code finds wiki words. then SomeWikiWord. then SomeWikiWord. but you also can manipulate strings once you find a match for them. Run this code and you should get the following console output: Introduction to Java programming. • replaceFirst() replaces only the first match with a specified string.getAnonymousLogger(). Replacing strings Searching for matches is useful.replaceAll("blah$0blah"). When you run this code. Part 2: Constructs for real-world applications Page 37 of 53 .getAnonymousLogger(). starting with 1 (group 0 represents the entire match). But it's also possible to reference matches by capturing groups. String result = matcher. You've seen some of that with the start() and end() methods on Matcher. If you'd used replaceFirst(). After: Here is replacement followed by replacement.info("Before: " + input). as before.getAnonymousLogger().info("Before: " + input). it replaces the wiki word text with its replacement. then replacement. When the Matcher finds a match.compile("[A-Z][a-z]*([A-Z][a-z]*)+"). After: Here is a replacement followed by AnotherWikiWord. Matcher matcher = pattern. and you should see the three wiki words in your console. Matcher matcher = pattern.info("After: " + result).".compile("[A-Z][a-z]*([A-Z][a-z]*)+"). Groups are numbered from left to right. Matching groups String input = "Here is a WikiWord followed by AnotherWikiWord. you typically create groups by enclosing parts of the pattern in parentheses. just as you might search for some text in a word-processing program and replace it with other text. Logger.matcher(input). Pattern pattern = Pattern. String result = matcher. you can get information about what you found. then SomeWikiWord. Logger.info("After: " + result). you should see the following on your console: Before: Here is WikiWord followed by AnotherWikiWord.com/developerWorks/ developerWorks® Run this code. Logger. You can do that by replacing matched strings with something else. Matching and manipulating groups When you search for matches against a regex pattern. Logger. The code in Listing 20 replaces each wiki word with a string that "wraps" the word: Listing 20. then SomeWikiWord. Matcher has a couple of methods for replacing string elements: • replaceAll() replaces all matches with a specified string.replaceAll("replacement"). In each pattern.

Any portion of a replacement string of the form $int refers to the group identified by the integer (so $1 refers to group 1.toString()). If you've used C++ templates.com/developerWorks/ Before: Here is a WikiWord followed by AnotherWikiWord. If you haven't used C++ templates. then blahSomeWikiWordblah.util.appendTail(buffer).info("After: " + buffer. Rather than calling replaceAll().ArrayList. You could accomplish the same replacement goal by using some other methods. } matcher.find()) { matcher. "blah$0blah"). $0 is equivalent to matcher. Generics The introduction of generics in JDK 5 marked a huge leap forward for the Java language. then don't worry: This section offers a high-level introduction to generics in the Java language. the Java language suddenly sprouted strange and exciting new syntax. which is a List of Objects that is backed by an array.developerWorks® ibm.appendReplacement(buffer. and so on).. Logger. Part 2: Constructs for real-world applications Page 38 of 53 . Generics in action To see what a difference generics make. After: Here is a blahWikiWordblah followed by blahAnotherWikiWordblah. you'll find that generics in the Java language are similar. consider the example of a class that has been in the JDK for a long time: java. then SomeWikiWord. Introduction to Java programming. while (matcher. but not exactly the same. some familiar JDK classes were replaced with their generic equivalents. Another approach to matching groups Listing 20 references the entire match by including $0 in the replacement string. What are generics? With the release of JDK 5. After: Here is a blahWikiWordblah followed by blahAnotherWikiWordblah. In other words. Generics is a compiler mechanism whereby you can create (and use) types of things (such as classes or interfaces) in a generic fashion by harvesting the common code and parameterizing (or templatizing) the rest. you could do this: StringBuffer buffer = new StringBuffer().group(0). then SomeWikiWord. Section 9.getAnonymousLogger(). Basically. then blahSomeWikiWordblah. And you'd get the same result: Before: Here is a WikiWord followed by AnotherWikiWord.

arrayList. aa < theList. you can specify the type of item that went in the ArrayList. arrayList. so good. } } Iterating with generics Generics enhance the Java language with special syntax for dealing with entities like Lists that you commonly want to step through. *// In some later part of the code.com/developerWorks/ developerWorks® Listing 21 shows how java. String s = theList. arrayList. you either must check the element you want to access to see if you can handle its type. arrayList. Part 2: Constructs for real-world applications Page 39 of 53 . which caused many coding mistakes. // So far.size(). or face a possible ClassCastException.add(new Integer(10)).. aa++) { // At some point..ArrayList is instantiated: Listing 21.. arrayList. String s = (String)theList.. everything is looking good so far..add("Another String"). *// In some later part of the code. // So far. Listing 23 shows how: Listing 23. which Listing 22 tries to do? Listing 22. A second attempt..util.ibm. } } Without prior knowledge of what's in the ArrayList. As you can see..add("A String"). using generics ArrayList<String> arrayList = new ArrayList<String>(). Before JDK 5 there was nothing in the Java language to constrain this behavior. arrayList. In Listing 21. this will fail.add(new Integer(10)). so good.size(). for example.// compiler error! arrayList. aa < theList.add(new Integer(10)).get(aa). arrayList.. *processArrayList(arrayList). But what about accessing the elements of the ArrayList.add("A String"). With generics. so good.add("Another String").add("A String"). *processArrayList(arrayList). private void processArrayList(ArrayList<String> theList) { for (int aa = 0. private void processArrayList(ArrayList theList) { for (int aa = 0. arrayList. Instantiating ArrayList ArrayList arrayList = new ArrayList().add("Another String"). the ArrayList is heterogeneous: it contains two String types and one Integer type. aa++) { // No cast necessary. If you want to Introduction to Java programming. element by element.get(aa). An attempt to access elements in ArrayList ArrayList arrayList = new ArrayList(). // So far.

The concreteListClass is the class from the JDK you are instantiating. for instance. and the features (attributes. for example) surrounding it are identical. which stands for Element. A parameterized List In generics syntax. • Common behavior: you do pretty much the same operations regardless of the "thing" at the center of the class. it's usually referring to a collection of some kind. is the "thing" I mentioned earlier.lang. Parameterized classes Parameterized classes really shine when it comes to collections. It represents an ordered collection of objects. say.com/developerWorks/ iterate through ArrayList. The JDK includes several List<E> implementations. you could rewrite the code from Listing 23 like so: private void processArrayList(ArrayList<String> theList) { for (String s : theList) { String s = theList. size. So.developerWorks® ibm. Applying these two criteria. Part 2: Constructs for real-world applications Page 40 of 53 . consider whether the following criteria apply: • A core class is at the center of some kind of wrapper: that is. implements the Iterable interface). When you see E in Java code. you add items to the List and then access those items either by index or by iterating over the List. In the most common use case. Consider the (real) List interface. it's denoting a parameterized class. Another way you might see a generic class discussed is Class<T>. the code to create a List looks like this: List<E> listReference = new concreteListClass<E>().Integer. and clear) are pretty much the same regardless of the object of which the collection is comprised. it's pretty obvious that a collection fits the bill: • The "thing" is the class of which the collection comprises. java. where T stands for Type.get(aa). you'd do this: Introduction to Java programming. If you're thinking about parameterizing a class. And when you see T. so that's how you'll look at them. • The operations (such as add. to create an ArrayList of. remove. The E. the "thing" at the center of the class might apply widely. but you'll use ArrayList<E>. } } This syntax works for any type of object that is Iterable (that is.

} } SimpleList SimpleList can be parameterized with any Object subclass. with three methods: • add() adds an element to the end of the SimpleList.intro. Parameterizing SimpleList package com.Application main INFO: SimpleList size is : 0 Introduction to Java programming.List. 2010 6:28:58 PM com. sl. log.com/developerWorks/ developerWorks® List<Integer> listOfIntegers = new ArrayList<Integer>().util. To create and use a of.ArrayList. import java. } public int size() { return backingStore.intro.ONE).BigDecimal objects.size(). } public void clear() { backingStore.makotogroup.size()). public class SimpleList<E> { private List<E> backingStore.Application main INFO: SimpleList size is : 1 May 5. public SimpleList() { backingStore = new ArrayList<E>().add(e)) return e. 2010 6:28:58 PM com. • size() returns the current number of elements in the SimpleList. else return null. sl.math.add(BigDecimal. 2010 6:28:58 PM com. Part 2: Constructs for real-world applications Page 41 of 53 .ibm.size()).info("SimpleList size is : " + sl. • clear() completely clears the contents of the SimpleList. you'd do this: public static void main(String[] args) { SimpleList<BigDecimal> sl = new SimpleList<BigDecimal>(). log. } public E add(E e) { if (backingStore.makotogroup.size()). SimpleList: A parameterized class Now suppose you want to create your own parameterized class called SimpleList.clear().makotogroup.Application main INFO: SimpleList size is : 2 May 5.util.clear(). Listing 24 shows the syntax to parameterize SimpleList: Listing 24. sl. log. java. } And you'd get this output: May 5.info("SimpleList size is : " + sl.add(BigDecimal.intro.ZERO).info("SimpleList size is : " + sl.makotogroup.intro. import java. say.

Enumeration. In fact. and methods: package com. you would have defined a set of constant values for a concept (say. public enum Gender { MALE("male"). . public static final String FEMALE = "female". Here's the enum definition for Gender: public enum Gender { MALE. FEMALE("female"). FEMALE } That just scratches the surface of what you can do with enums. } Defining constants with enum Using the enum type makes defining constants much more formal. a new data type was added to the Java language. and it cannot extend (or inherit from) other enums. gender) like so: public class Person { public static final String MALE = "male". enums are much like classes. so they can have constructors. an enum can implement an interface. Before enum was introduced to the Java language.displayName. and also more powerful. private Gender(String displayName) { this. } Whatever code needed to reference that constant value would have been written something like this: public void myMethod() { //.com/developerWorks/ Enum types In JDK 5. Part 2: Constructs for real-world applications Page 42 of 53 . enum represents a set of constant objects that are all related to a particular concept.developerWorks® ibm. . Introduction to Java programming. } } One difference between a class and an enum is that an enum's constructor must be declared private. } public String getDisplayName() { return this. String genderMale = Person.MALE. Not to be confused with java. . attributes. each of which represents a different constant value in that set. //. called enum. private String displayName. .makotogroup.displayName = displayName. However.util.intro.

displayName = displayName. public interface Displayable { public String getDisplayName(). Displayable: package com. You'll learn to use some of its tools to collect and manipulate data from a variety of sources. private Gender(String displayName) { this. Section 10. Working with external data More often than not. and most of them are located in the java. such as a database.io. I/O This section is an overview of the java. is a class that defines a resource on your file system and represents that resource in an abstract way.makotogroup.io package.io package. } @Override public String getDisplayName() { return this. private String displayName. Creating a File object is easy: java. or file storage. } } See Resources to learn more about generics.intro. The Java language gives you many tools to get information from these sources. like so: package com.displayName. the data you use in your Java programs will come from an external data source. files are the most common and often the most convenient. Files Of all the data sources available to your Java applications.intro. } Your Gender enum could implement this interface (as well as any other enum that needed to produce a friendly display name).com/developerWorks/ developerWorks® An enum implements an interface Suppose you define an interface.makotogroup.ibm. FEMALE("female"). public enum Gender implements Displayable { MALE("male"). If you want to read a file in your Java application. direct byte transfer over a socket. you must use streams that parse its incoming bytes into Java language types. Part 2: Constructs for real-world applications Page 43 of 53 .File Introduction to Java programming.

At the highest level of abstraction are character streams and byte streams. writes bytes to an in-memory array. so long as it is a valid file name for your OS. all found in the java. determine whether a resource is a file. Character streams Character streams read (Reader and its subclasses) and write (Writer and its subclasses) 16-bit characters. or symbolic link. f2. This code asks the newly created File object if the file exists: File f2 = new File("/home/steve/testFile. Byte streams read (InputStream and subclasses) and write (OutputStream and subclasses) 8-bit bytes. At the lowest level.io. In other words.exists()) { // File exists.developerWorks® File f = new File("temp... } else { // File doesn't exist.txt"). Some streams handle all kinds of 16-bit characters (Reader and Writer types). Within these hierarchies are several flavors of streams. The first call creates a file called temp. and more.txt").File The real action of Java I/O is in writing to and reading from data sources.. } has some other handy methods that you can use to delete files. Here's a summary of two common byte streams and their usage: • FileInputStream/FileOutputStream: Reads bytes from a file. Create it. writes bytes to a file. create directories (by passing a directory name as the argument to File's constructor). ibm.io package. directory.com/developerWorks/ The File constructor takes the name of the file it will create.. Here's a selected listing of character streams and their usage: Introduction to Java programming.txt"). if (f2. a byte stream can be considered a more raw type of stream. • ByteArrayInputStream/ByteArrayOutputStream: Reads bytes from an inmemory array. streams allow a program to receive bytes from a source or to send output to a destination. Using streams in Java I/O You can access files on the file system using streams. The second call creates a file in a specific location on my Linux system. Process it. File f2 = new File("/home/steve/testFile. whether or not the file that it references even exists. You can pass any String to the constructor of File. which is where streams come in. Part 2: Constructs for real-world applications Page 44 of 53 .txt in the given directory.createNewFile(). Others handle only 8-bit bytes (InputStream and OutputStream types). java.

Listing 25 is an example in reading from a File: Listing 25. I'll focus on the recommended streams for reading and writing files. 2. StringBuilder sb = new StringBuilder(). Part 2: Constructs for real-world applications Page 45 of 53 . • BufferedReader/BufferedWriter: Buffer data while reading or writing another stream. In most cases. Create an InputStreamReader on the File you want to read from. Rather than try to cover streams in their entirety. making read and write operations more efficient. Reading from a File Logger log = Logger. I'll go with the simplest approach: 1. these are character streams. Once again.getMessage()). Reading from a File There are several ways to read from a File. } } finally { reader. } Writing to a File As with reading from a File.read(). } } catch (IOException e) { log. The Writer flavors convert characters to bytes to put them on byte streams. try { InputStream inputStream = new FileInputStream(new File("input. while (c != -1) { sb.ibm. Create a FileOutputStream on the File you want to write to. The Reader flavors read bytes from a byte stream and convert them to characters.close().txt")).getAnonymousLogger(). Arguably the simplest approach is to: 1. there are several ways to write to a File. 2. Listing 26 is an example of writing to a File: Introduction to Java programming.com/developerWorks/ developerWorks® • StringReader/StringWriter: Read and write characters to and from Strings in memory.append(c). Call read() to read one character at a time until you reach the end of the file. try { int c = reader. Call write() to write the character sequence. • InputStreamReader/InputStreamWriter (and subclasses FileReader/FileWriter): Form a bridge between byte streams and character streams.info("Caught exception while processing file: " + e. InputStreamReader reader = new InputStreamReader(inputStream).

developerWorks® Listing 26. Writing to a File

ibm.com/developerWorks/

Logger log = Logger.getAnonymousLogger(); StringBuilder sb = getStringToWriteSomehow(); try { OutputStream outputStream = new FileOutputStream(new File("output.txt")); OutputStreamWriter writer = new OutputStreamWriter(outputStream); try { writer.write(sb.toString()); } finally { writer.close(); } } catch (IOException e) { log.info("Caught exception while processing file: " + e.getMessage()); }

Buffering streams Reading and writing character streams one character at a time is not exactly efficient, so in most cases, you'll probably want to use buffered I/O instead. To read from a file using buffered I/O, the code looks just like Listing 25, except that you wrap the InputStreamReader in a BufferedReader, as shown in Listing 27: Listing 27. Reading from a File with buffered I/O
Logger log = Logger.getAnonymousLogger(); StringBuilder sb = new StringBuilder(); try { InputStream inputStream = new FileInputStream(new File("input.txt")); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String line = reader.readLine(); while (line != null) { sb.append(line); line = reader.readLine(); } } finally { reader.close(); } } catch (IOException e) { log.info("Caught exception while processing file: " + e.getMessage()); }

Writing to a file using buffered I/O is the same: you just wrap the OutputStreamWriter in a BufferedWriter, as shown in Listing 28 Listing 28. Writing to a File with buffered I/O
Logger log = Logger.getAnonymousLogger(); StringBuilder sb = getStringToWriteSomehow(); try { OutputStream outputStream = new FileOutputStream(new File("output.txt")); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); try { writer.write(sb.toString()); } finally { writer.close(); } } catch (IOException e) { log.info("Caught exception while processing file: " + e.getMessage()); }

Introduction to Java programming, Part 2: Constructs for real-world applications

Page 46 of 53

ibm.com/developerWorks/

developerWorks®

I've merely scratched the surface of what's possible with this essential Java library. On your own, try applying what you've learned about files to other data sources.

Section 11. Java serialization
Java serialization is another one the Java platform's essential libraries. Serialization is primarily used for object persistence and object remoting, two use cases where you need to be able to take a snapshot of the state of an object and then reconstitute it at a later time. This section gives you a taste of the Java Serialization API and shows how to use it in your programs.

What is object serialization?
Serialization is a process where the state of an object and its metadata (such as the object's class name and the names of its attributes) are stored in a special binary format. Putting the object into this format — serializing it — preserves all the information necessary to reconstitute (or deserialize) the object whenever you need to do so. There are two primary use cases for object serialization: • Object persistence means storing the object's state in a permanent persistence mechanism such as a database. • Object remoting means sending the object to another computer or system.

java.io.Serializable
The first step to making serialization work is to enable your objects to use the mechanism. Every object you want to be serializable must implement an interface called java.io.Serializable:
import java.io.Serializable; public class Person implements Serializable { // etc... }

The Serializable interface marks the objects of the Person class to the runtime as serializable. Every subclass of Person will also be marked as serializable. Any attributes of an object that are not serializable will cause the Java runtime to throw a NotSerializableException if it tries to serialize your object. You can manage this by using the transient keyword to tell the runtime not to try to serialize
Introduction to Java programming, Part 2: Constructs for real-world applications Page 47 of 53

developerWorks®

ibm.com/developerWorks/

certain attributes. In that case, you are responsible for making sure the attributes are restored so that your object will function properly. Serializing an object Now you'll try an example that combines what you've just learned about Java I/O with what you're learning now about serialization. Suppose you create and populate a Manager object (recall that Manager is in the inheritance graph of Person, which is serializable) and then want to serialize that object to an OutputStream, in this case to a file. That process is shown in Listing 29: Listing 29. Serializing an object
Manager m = new Manager(); m.setEmployeeNumber("0001"); m.setGender(Gender.FEMALE); m.setAge(29); m.setHeight(170); m.setName("Mary D. Boss"); m.setTaxpayerIdentificationNumber("123-45-6789"); log.info("About to write object using serialization... object looks like:"); m.printAudit(log); try { String filename = "Manager-" + m.hashCode() + ".ser"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename)); oos.writeObject(m); log.info("Wrote object..."); } catch (Exception e) { log.log(Level.SEVERE, "Caught Exception processing object", e); }

The first step is to create the object and set some attribute values. Next, you create an OutputStream, in this case a FileOutputStream, and then call writeObject() on that stream. writeObject() is a method that uses Java serialization to serialize an object to the stream. In this example, you are storing the object in a file, but this same technique is used for any type of serialization. Deserializing an object The whole point of serializing an object is to be able to reconstitute, or deserialize, it. Listing 30 reads the file you've just serialized and deserializes its contents, thus restoring the state of the Manager object: Listing 30. Deserializing an object
Manager m = new Manager(); m.setEmployeeNumber("0001"); m.setGender(Gender.FEMALE); m.setAge(29); m.setHeight(170); m.setName("Mary D. Boss"); m.setTaxpayerIdentificationNumber("123-45-6789"); log.info("About to write object using serialization... object looks like:");

Introduction to Java programming, Part 2: Constructs for real-world applications

Page 48 of 53

com/developerWorks/ developerWorks® m. But if you add or remove an attribute. developers were largely responsible for controlling the "wire format" of their objects.io. Java serialization uses a property called serialVersionUID to help you deal with different versions of objects in a serialization scenario.printAudit(log).. log. recompiled it. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))... e). that dynamically generated value will change. and the Java runtime will throw an InvalidClassException. ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename)). m = (Manager)ois. which caused no end of headaches as technology began to evolve. Most of the time."). but accessed by other machines that might have a different version of the code.. you should get in the habit of explicitly declaring a serialVersionUID: import java. marking your objects as serializable is all you'll ever need to worry about when it comes to serialization. by default. When those machines tried to deserialize the object. In cases where you do need to serialize and deserialize your objects explicitly.Serializable.readObject(). try { String filename = "Manager-" + m. To avoid this..hashCode() + ".printAudit(log). public class Person implements Serializable { private static final long serialVersionUID = 20100515. the Java platform uses an algorithm that computes a value for it based on your class's attributes. Part 2: Constructs for real-world applications Page 49 of 53 . log. "Caught Exception processing object". and redistributed the code to every machine in an application cluster. bad things often happened. Suppose you added an attribute to an object.SEVERE.ser".info("Wrote object. and you add and remove attributes to and from them. } For most application purposes. But as your application objects evolve. and position in the local galactic cluster. } catch (Exception e) { log. serialVersionUID Back in the early days of middleware and remote object communication. oos. The object would be stored on a machine with one version of the serialization code. object looks like:").info("Read object using serialization. // etc. its class name.ibm.. } Introduction to Java programming. you can use the technique shown in Listings 29 and 30.log(Level.writeObject(m). serialization takes on a new layer of complexity. that works fine. Java serialization metadata — the information included in the binary serialization format — is sophisticated and solves many of the problems that plagued early middleware developers. m. But it cannot solve every problem. You don't need to declare this property on your objects.

Another topic worthy of exploration is Java 7. any time you add or remove features (meaning attributes and methods) of a class. such as concurrency and persistence. Eventually. A single tutorial can't possibly encompass it all. generics. Conclusion to Part 2 The "Introduction to Java programming" tutorial has covered a significant portion of the Java language. Part 2: Constructs for real-world applications Page 50 of 53 . Introduction to Java programming. You may be wondering when to change this property. If you have one version of the object on one machine that has the attribute removed. but the language is huge. you may also want to explore topics not covered in this introductory tutorial. The short answer is that you should change it whenever you make an incompatible change to the class. you should change its serialVersionUID. Better to get an InvalidClassException on the other end of the wire than an application bug that's due to an incompatible class change. including those too advanced to be explored in this introductory format. and the object gets remoted to a machine with a version of the object where the attribute is expected. See Resources for some good starting points for learning more about Java programming concepts. then things can get weird.com/developerWorks/ I recommend using some kind of scheme for your serialVersionUID version number (I've used the current date in the example above). As a rule of thumb. which will bring many potentially groundbreaking changes to the Java platform. As you continue learning about the Java language and platform. you'll probably want to study further into topics like regular expressions. which usually means you've removed an attribute. Section 12. and you should declare it private static final and of type long. and Java serialization.developerWorks® ibm.

: This developerWorks series provides short introductions to lesser-known (but often introductory) Java programming tips and lore. more maintainable code. JavaWorld. Introduction to Java programming.ibm. 1999): This book is an excellent resource for learning how to write cleaner. how you can get started with it. and where to learn more about it. • Design patterns: Elements of reusable object-oriented software (Erich Gammaet al. February 2002): Understand the difference between checked and runtime exceptions. developerWorks.com. • Eclipse IDE project resources from IBM: Learn what Eclipse is good for.. Part 1" (Eric Allen. as well as IBM value-adds focused on improving Java platform performance. • The developerWorks Java technology zone: Hundreds of articles about every aspect of Java programming. including the Java language specification and Java API documentation. • "Java technology. Addison-Wesley. • The Java Tutorials: Get a comprehensive introduction to the Java language. • "Regular expressions simplify pattern-matching code" (Jeff Friesen.. 1994): Learn more about the Factory pattern. • Java 6: Learn more about JDK 6 and the tools that come with it. IBM style: A new era in Java technology" (Chris Bailey developerWorks. • 5 things you didn't know about . • "Try to catch me: Does exception handling impair performance?" (Tony Sintes.. JavaWorld. February 2003): Explore this extended introduction to regex. • New to Java technology: Check out this compendium of developerWorks resources for beginning Java developers. • Javadoc homepage: Learn the ins and outs of using the Javadoc. Part 2: Constructs for real-world applications Page 51 of 53 . JavaWorld. one of 23 design patterns that continue to define contemporary software development. Get products and technologies • JDK 6: Download JDK 6 from Sun (Oracle). • Refactoring: Improving the Design of Existing Code (Martin Fowler et al. including how to use the command-line tool and how to write your own Doclets that let you create custom formats for your documentation. April 2010): Read about upcoming changes in the official Java SE 7 release. July 2001): This article provides introductory information about exception handling in Java programs. reliability. • "Diagnosing Java code: Java generics without the pain. • "Exception: Don't get thrown for a loss" (Tony Sintes..com/developerWorks/ developerWorks® Resources Learn • Java technology homepage: The official Java site has links to all things related to the Java platform. and serviceability. Addison-Wesley. why it is important. February 2003): This is the first part of an article series introducing generics in Java syntax.

Connect with other developerWorks users while exploring the developer-driven blogs. Discuss • Get involved in the My developerWorks community. groups.developerWorks® ibm. • IBM developer kits: IBM provides a number of Java developer kits for use on popular platforms. Introduction to Java programming. and wikis.com/developerWorks/ • Eclipse: Download the Eclipse IDE for Java Developers. Part 2: Constructs for real-world applications Page 52 of 53 . forums.

Steven Perry is a software developer. Part 2: Constructs for real-world applications Page 53 of 53 . and the IBM developerWorks articles "Joda-Time" and OpenID for Java Web applications. Steve has a passion for writing and mentoring. © Copyright IBM Corporation 2010 (www. he hangs out with his three kids. architect.shtml) Trademarks (www. rides his bike.com/developerworks/ibm/trademarks/) Introduction to Java programming.com/legal/copytrade.ibm." In his spare time. Log4j (O'Reilly).ibm. and general Java nut who has been developing software professionally since 1991.com/developerWorks/ developerWorks® About the author J Steven Perry J.ibm. and teaches yoga. he is the author of Java Management Extensions (O'Reilly). His professional interests range from the inner workings of the JVM to UML modeling and everything in between.

Sign up to vote on this title
UsefulNot useful