java fundamentals sg jah-cj-200

339
Fundamentals of the Java Programming Language JAH-CJ-200 Student Guide Culiacán, Sinaloa México. Version 1.0.0, 2006

Upload: juan-manuel-ramirez

Post on 13-Apr-2016

31 views

Category:

Documents


5 download

DESCRIPTION

libro de java

TRANSCRIPT

Page 1: Java Fundamentals SG JAH-CJ-200

Fundamentals of the Java Programming Language

JAH-CJ-200

Student Guide

Culiacán, Sinaloa México. Version 1.0.0, 2006

Page 2: Java Fundamentals SG JAH-CJ-200

2 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Publishing Information This publication has been produced using Microsoft Word 2000 and Microsoft PowerPoint 2000 for Windows.

Trademarks of Other Companies HotJava browser, Java Development Kit (JDK), Java, Java Servlet, Solaris, Enterprise Java Beans, Java Server Pages, JDK, JSP – Sun Microsystems, Microsoft MAKECAB, Windows operating system, ASP, VB, .NET, VC++, Microsoft Access, Microsoft SQL Server, Microsoft ODBC for Oracle – Microsoft Corp, WinZip – Nico Mak Computing, Inc., Time – Time Warner, JDBC – Javasoft, Oracle – Oracle Corporation, Sybase – Sybase Inc., UDB DB2 – IBM.

September 2006 Edition The information contained in this document is distributed on an ―as is‖ basis without any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment.

This manual was developed for educational purposes only.

Page 3: Java Fundamentals SG JAH-CJ-200

3 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Table of Contents

About This Course

Course Goal

Module 01 Introduction to the Java Programming Language

Objectives What is Java? Goals of Java The Java Programming Language The Java evolution The Java platform The Java execution model Uses of Java Programs Components

Module 02 Developing and Testing a Java Program

Objectives Identifying the Components of a Class

Structuring Classes Class Declaration Variable Declarations and Assignments Comments Methods

Creating and Using a Test Class The main method

Compiling and Executing (Testing) a Program Compiling a Program Executing (Testing) a Program Debugging Tips

Module 03 Writing, Compiling, and Testing a Basic Program Lab Objectives Lab Exercises

Module 04 Declaring, Initializing, and Using Variables

Objectives Identifying Variable Use and Syntax

Uses for Variables Variable Declaration and Initialization

Describing Primitive Data Types Integral Primitive Types

Page 4: Java Fundamentals SG JAH-CJ-200

4 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Floating Point Primitive Types Textual Primitive Type Logical Primitive Type Choosing a Data Type

Declaring Variables and Assigning Values to Variables Naming a Variable Assigning a Value to a Variable Constants Storing Primitive and Constants in Memory

Using Arithmetic Operators to Modify Values Standard Mathematical Operators Increment and Decrement Operators (++ and --) Operator Precedence

Using Promotion and Type Casting Casting primitive types Implicit versus explicit casting Compiler Assumptions for Integral and Floating Point Data Types

Module 05 Using Primitive Types, Operators and Type Casting, in a Program Lab Objectives Lab Exercises

Module 06 Creating and Using Objects

Objectives Declaring Object References, Instantiating Objects, and Initializing Object References

Declaring Object Reference Variables Instantiating an Object Initializing Object Reference Variables Using an Object Reference Variable to Manipulate Data Storing Object Reference Variables in Memory Assigning a Reference From One Variable to Another

Using the String Class Creating a String Object With the new Keyword Creating a String Object Without the new Keyword Storing String Objects in Memory Using Reference Variables for String Objects

Module 07 Objects and Strings Objectives Lab Exercises

Module 08 Using Operators and Decision Constructs Objectives

Page 5: Java Fundamentals SG JAH-CJ-200

5 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using Relational and Conditional Operators Elevator Example Relational Operators Testing Equality Between Strings Conditional Operators

Creating if and if/else Constructs The if Construct Nested if Statements The if/else Construct Chaining if/else Constructs

Using the switch Construct When to Use switch Constructs

Module 09 Control Structures Objectives Lab Exercises

Module 10 Using Loop Constructs

Objectives Creating while Loops

Nested while Loops Developing a for Loop

Nested for Loops Coding a do/while Loop

Nested do/while Loops Comparing Loop Constructs

Module 11 Loop Constructs Lab Objectives Lab Exercises

Module 12 Developing and Using Methods Objectives Creating and Invoking Methods

Basic Form of a Method Invoking a Method from Different Class Invoking a Method in the Same Class Guidelines for Invoking Methods

Passing Arguments and Returning Values Declaring Methods With Arguments Invoking Methods With Return Values Returning a Value Advantages of Method Use

Creating static Methods and Variables Static Methods and Variables in the Java API

Page 6: Java Fundamentals SG JAH-CJ-200

6 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

When to Declare a static Method or Variable Using Method Overloading

Method Overloading and the Java API Uses for Method Overloading

Module 13 Methods Labs Objectives Lab Exercises

Module 14 Implementing Encapsulation and Constructors

Objectives Using Encapsulation

Visibility Modifiers The public Modifier The private Modifier Interface and Implementation Get and Set Methods Encapsulated Elevator

Describing Variable Scope How Instance Variables and Local Variables Appear in Memory

Creating Constructors Default Constructor Overloading Constructors

Module 15 Encapsulation and Constructors Lab Objectives Lab Exercises

Module 16 Creating and Using Arrays

Objectives Creating One-Dimensional Arrays

Declaring a One-Dimensional Array Instantiating a One-Dimensional Array Initializing a One-Dimensional Array Declaring, Instantiating, and Initializing One-Dimensional Arrays Accessing a Value Within an Array Storing One-Dimensional Arrays in Memory

Setting Arrays Values Using the length Attribute and a Loop The length Attribute Setting Array Values Using a Loop

Using the args Array in the main Method Converting String Arguments to Other Types

Describing Two-Dimensional Arrays Declaring a Two-Dimensional Array Instantiating a Two-Dimensional Array

Page 7: Java Fundamentals SG JAH-CJ-200

7 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing a Two-Dimensional Array

Lab Module 17 Arrays Lab Objectives Lab Exercises

Module 18 Implementing Inheritance

Objectives Inheritance

Superclasses and Subclasses Declaring a Subclass

Module 19 Inheritance Lab Objectives Lab Exercises

Page 8: Java Fundamentals SG JAH-CJ-200

8 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

About This Course

Course Goal This course provides first-time programmers an excellent choice for learning programming using the Java Programming language. Keys areas are the significance of the Java programming language, principles of object orientation (OO), and applying those concepts when writing Java code encompassing the essential Java programming functions. At the end of the course, you will be able to write simple Java programs, but will not have extensive programming ability. This course provides a solid basis in the Java programming language on which you can base your continued work and training.

Page 9: Java Fundamentals SG JAH-CJ-200

9 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 01 Introduction to the Java Programming Language Objectives What is Java? Goals of Java The Java Programming Language The Java evolution The Java platform The Java execution model Uses of Java Programs Components

Objectives Upon completion of this module, you should be able to: Describe the history and properties of the Java programming language Explain the Java execution model, including the use of byte code and the Java

virtual machine Outline the types of programs and components that can be built using Java

Page 10: Java Fundamentals SG JAH-CJ-200

10 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

What is Java?What is Java?

• Java is an object-oriented programming language developed

by Sun Microsystems

• Java has a set of standardized class libraries that support

predefined reusable functionality

• Java has a runtime environment that can be embedded in Web

browsers and operating systems

Notes: Java shares characteristics of other object-oriented languages such as C++ and Smalltalk, and has the following advantages: Thread and synchronization support Platform independence Built-in security mechanisms Built-in networking capabilities Facilities for internationalization

Page 11: Java Fundamentals SG JAH-CJ-200

11 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Goals of JavaGoals of Java

• Java was developed to solve several problems with existing

languages

• These issues had an important influence on its development:

– Object-orientation

– Portability

– Performance

– Security

– Internationalization

– Distributed computing

– Dynamic systems

Notes:

Object Orientation: Object orientation has long been considered to be the best paradigm for software development. Java is object-oriented.

Portability: A big problem with any compiled language is that different executables are needed for different platforms. The Java virtual machine runtime environment allows source-level and binary-level portability.

Performance: Portability has been achieved by interpreted languages such as BASIC. The compromise that has been made is that interpreted languages are dramatically slower than compiled languages because they must be interpreted as they run. The Java solution was the JVM and bytecode, which will be discussed in this unit.

Security: Another problem with portable code is its safety. Java has built-in security mechanisms to help prevent malicious programming. For example, a certain type of Java program called an applet has a much more restricted environment in which to run than does an application.

Internationalization: With portability comes the issue of local preferences, such as language, date and time formats, currencies, and so forth. Java provides facilities for internationalization of programs which may allow interaction between the program and the user's local language.

Distributed Computing: To achieve a Web application environment, the language of choice has to have excellent networking capabilities built in, and Java provides these facilities.

Dynamic Systems: Java uses a large number of separate components which are dynamically interchangeable.

Page 12: Java Fundamentals SG JAH-CJ-200

12 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java programming languageThe Java programming language

• Object-oriented

– Java supports software development using the notion of

objects

– Software developed using Java is composed of classes and

objects

Notes: The Java programming language is an object-oriented programming (OOP) language because one of the main goals of the Java programmer is to create objects, pieces of autonomous code, that can interact with other objects to solve a problem. OOP started with the SIMULA-67 programming language in 1967 and has led to popular programming languages, such as C++, upon which the Java programming language is loosely based.

Page 13: Java Fundamentals SG JAH-CJ-200

13 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java programming languageThe Java programming language

• Network capable

– Java supports the development of distributed applications

– Some types of Java applications are designed to be accessed

through a Web browser

Notes: Java has facilities to allow programmers to easily deal with the creation of network connections, and work with network protocols such as HTTP. Applets and Web applications (composed of servlets and JSPs) are two types of Java application that are designed to be accessed through the Web.

Page 14: Java Fundamentals SG JAH-CJ-200

14 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java programming languageThe Java programming language

• Robust

– Many aspects of Java promote the development of reliable

software

• Java uses a pointer model which does not allow direct

access to memory; memory cannot be overwritten

• Secure

– Java authentication is based on public-key encryption

methods

– Java’s pointer model protects private data in objects and

prevents unauthorized applications from accessing data

structures

Notes: Java does not use pointers, and uses true arrays as opposed to pointer arithmetic. Java's implementation of arrays allows subscript checking to be done. Also, because Java does not use pointers, the end of memory buffers cannot be overwritten, and unauthorized access to memory is prevented. Program robustness and security are highly related topics, as both strongly relate to how Java manages access to memory.

Page 15: Java Fundamentals SG JAH-CJ-200

15 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java programming languageThe Java programming language

• Multi-threaded

– Allows your program to run more than one task at the same

time

Notes: The Java programming language supports multithreading, that is performing several tasks at a time, such as querying a database and displaying a user interface. Multithreading allows a Java program to be very efficient in its use of system resources. Threads are also described as lightweight processes; they allow for concurrent paths of execution through code. C and C++ are single-threaded, and allowing applications to have multiple threads can increase the difficulty of writing a program, as such programs must handle concurrent paths of execution through code. Java includes facilities to deal with synchronization.

Page 16: Java Fundamentals SG JAH-CJ-200

16 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java programming languageThe Java programming language

• Compiled and interpreted

– Source code is compiled into machine code for the Java

virtual machine (JVM) by the Java compiler

– Machine code for the JVM is also known as bytecode

– Interpreter of the Java virtual machine interprets and

executes instructions

• Architecture neutral

– Bytecode instructions are architecture neutral because they

run on the JVM, and are not specific to an architecture

– The same application runs on all platforms, provided the

Java virtual machine is installed on that platform

Notes: The Java virtual machine is a piece of software that acts as a virtual CPU, interpreting bytecode instructions and then executing these instructions. Bytecode is platform independent, while the Java virtual machine is specific to a platform. The Java language is not specific to any computer platform, which allows Java programs to be portable. For example, primitive data types, such as integers and floats, have an identical definition over all platforms. Though source and binary code are portable between operating system platforms, the JVM is specific to the operating system where the program runs.

Page 17: Java Fundamentals SG JAH-CJ-200

17 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java programming languageThe Java programming language

• Portable at source and binary level

– One piece of source code gets compiled into one set of

bytecode instructions for the JVM, and can be run on any

platform and architecture without recompiling the code

Notes: Like C and C++ programs, Java programs are also compiled using a Java compiler. However, the resulting format of a compiled Java program is platform-independent Java bytecode instead of CPU-specific machine code. After the bytecode is created, it is interpreted (executed) by a bytecode interpreter called the virtual machine or VM. A virtual machine is a platform-specific program that understands platform-independent bytecode and can execute it on a particular platform. For this reason, the Java programming language is often referred to as an interpreted language, and Java programs are said to be portable or executable on any platform. For Java programs to be platform-independent, a virtual machine called the Java virtual machine (JVM) is required on every platform where your programming will run. The Java virtual machine is responsible for interpreting Java code, loading Java classes, and executing Java programs. However, a Java program needs more than just a Java virtual machine to execute. A Java program also needs a set of standard Java class libraries for the platform. Java class libraries are libraries of pre-written code that can be combined with the code you write to create robust applications. Combined, the JVM software and Java class libraries are referred to as the Java runtime environment (Java RE). Java runtime environments are available from Sun Microsystems for many common platforms.

Page 18: Java Fundamentals SG JAH-CJ-200

18 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Java evolutionJava evolution

• Java is a relatively young language

– It has been in use since 1995

– It was originally designed for consumer electronic devices

• Java has a huge developer base

– There is a vast collection of libraries (from Sun and other

sources)

Notes: The Java programming language originated in 1991 as part of a research project to develop a programming language, called ―Oak,‖ that World bridge the communication gap between many consumer devices, such as video cassette recorders (VCRs) and televisions. Specifically, a team of highly skilled software developers (called the Green team), wanted to create a programming language enabling consumer devices with different central processing units (CPUs) to share the same software enhancements. This initial concept failed after several deals with consumer device companies were unsuccessful. The Green team was forced to find another market for their new programming language. Fortunately, the World Wide Web was becoming popular and the Green team recognized that the Oak language was perfect for developing Web multimedia components to enhance Web pages. These small applications, called applets, became the initial use of the Oak language and programmers using the Internet adopted what became the Java programming language.

Page 19: Java Fundamentals SG JAH-CJ-200

19 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java PlatformThe Java Platform

• A platform is a development or

deployment environment

• The Java platform runs on any

operating system

– Other platforms are

hardware and vendor

specific

• The Java platform provides:

– The Java virtual

machine (JVM)

– Application Programming

Interface (API)

Notes: Java programs make use of the Java API; when completed, programs are compiled into bytecode. This bytecode is interpreted by the Java virtual machine, and that same bytecode can be interpreted by Java virtual machines residing on other computers of different platforms or architectures. A Java program runs on the Java virtual machine; the JVM runs on a real machine, on the host platform.

Page 20: Java Fundamentals SG JAH-CJ-200

20 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java execution modelThe Java execution model

• Compiled language execution model

– Source code is compiled into instructions understood by the

host machine; host machine executes this binary file

Notes: In a compiled language, a compiler translates the source code of a program into a binary file of machine code. The machine code is understood and executed by the hardware and the operating system. Java, however, is compiled into bytecode; bytecode is understood and executed by the Java virtual machine. The Java virtual machine runs on an operating system, and the bytecode is interpreted by the JVM. Java source code is written once, and can be run in any environment which has the Java virtual machine installed. The source code and bytecode remain the same no matter where the program is to be run.

Page 21: Java Fundamentals SG JAH-CJ-200

21 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java execution modelThe Java execution model

• Java execution model

– Source code is compiled into instructions understood by the

JVM; bytecode is then interpreted by the JVM

Notes: Java bytecode can be executed by the Java virtual machine in three ways:

1. Bytecode can be interpreted and executed 2. Bytecode can be translated into executable instructions for the specific platform and

then executed (called just-in-time or JIT compilation) 3. Bytecode can act as the native machine code for a platform built using Java chips;

in this case, no compiler or interpreter is used, and bytecode is executed directly

Page 22: Java Fundamentals SG JAH-CJ-200

22 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The Java execution modelThe Java execution model

Notes:

Page 23: Java Fundamentals SG JAH-CJ-200

23 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses of JavaUses of Java

• Java can be used to build programs and software components

• Programs are stand-alone entities that can run on the Java

virtual machine

– Applications

– Applets

• Components are building blocks used to create programs

– Servlets

– JavaServer Pages (JSPs)

– JavaBeans

– Enterprise JavaBeans (EJBs)

Notes: A component is a building block of larger programs. Ideally, programs are built from components, and components are designed to be reusable by many programs.

Page 24: Java Fundamentals SG JAH-CJ-200

24 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ProgramsPrograms

• Application

– A stand-alone program that can access system resources such

as files

– Does not need to run in a Web browser

– Is explicitly invoked through the command line or menu

selection

– The method main() is the entry point for an application

Notes: An application is a type of program that runs on a single machine or over a network, and interacts with the computer’s operating systems.

Page 25: Java Fundamentals SG JAH-CJ-200

25 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ProgramsPrograms

• Applet

– A Java program that is embedded within a Web page; almost

always graphical

– Security limits access to system resources

– Code executes on the client inside a Web browser

Notes: Applets are different from applications; they are not self-contained programs and are more like applications fragments. Applets run within the browser, not the operating system. An applet is stored on a server, and is transmitted to the client when its HTML <APPLET> tag is accessed. Applets are usually visual programs and have limited access to the client operating system in order to preserve client security.

Page 26: Java Fundamentals SG JAH-CJ-200

26 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ComponentsComponents

• Servlet

– Handles requests from the Web browser and returns

responses

– Creates dynamic content on the server

– Runs inside an application server

• JavaServer Page (JSP)

– HTML page embedded with Java code

– Creates dynamic content on the server instead of on the

browser

– Runs inside an application server

Notes: An application server is a special server which allows you to run enterprise Java components such as servlets, JSPs, and EJBs. Servlet: Servlets are commonly used to interact with Web sites. Typically, a set of HTML pages interacts with the user, and then sends the collected data to the servlet to be processed. It usually interacts with database and other server-side components. Servlets are capable of writing HTML dynamically. JavaServer Page: JSPs are a way of creating HTML dynamically as well. They are in essence HTML pages with special tags that represent Java functions. Servlets and JSPs are Web components that are a part of the Java 2 Enterprise Edition (J2EE) architecture. Servlets and JSPs require special support, and run on a platform, called a Web container, that provides this support. Servlets and JSPs are the building blocks of enterprise Java applications. Though they run the same way and can provide the same functionality, the way servlets and JSPs are coded in Java lends these components to different tasks within an application.

Page 27: Java Fundamentals SG JAH-CJ-200

27 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ComponentsComponents

• JavaBeans

– Java code that has its properties, methods, and events

exposed to promote reuse among developers

– Reusable software component that can be manipulated

visually in a builder tool

Notes: JavaBeans are a software component that can be reused throughout the Java language by many other types of Java programs and components: JSPs, EJBs, and so forth. A JavaBean is simply a class that has been written in a manner that exposes its properties, methods and events in a standard way; it is a class that adheres to certain standards to promote reuse. JavaBeans have many different uses, including being used within enterprise Java applications. Some JavaBeans have a visual representation at run time, while others do not. One use of JavaBeans is to store information that must be passed within an application and allow it to be retrieved by different parts of the application. EJBs are server-side components that are a part of the Java 2 Enterprise Edition (J2EE) architecture. These components are run on a Java-enabled Web server; they also require special support, and are run on a platform, called an EJB container, that provides this support.

Page 28: Java Fundamentals SG JAH-CJ-200

28 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ComponentsComponents

• Enterprise JavaBeans (EJB)

– Distributed objects that allow communication between Java

objects in different JVMs

– Encapsulate the business logic and model of an application

– Run inside an application server

Notes:

Page 29: Java Fundamentals SG JAH-CJ-200

29 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 02 Developing and Testing a Java Program Objectives Identifying the Components of a Class

o Structuring Classes o Class Declaration o Variable Declarations and Assignments o Comments o Methods

Creating and Using a Test Class o The main method

Compiling and Executing (Testing) a Program o Compiling a Program

Executing (Testing) a Program Debugging Tips

Objectives Upon completion of this module, you should be able to: Identify the four components of a class in the Java programming language Use the main method in a test class to run a Java program from the command line Compile and execute a Java program

Page 30: Java Fundamentals SG JAH-CJ-200

30 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Identifying the Components of a ClassIdentifying the Components of a Class

• Classes are the blueprints that you create to define the objects

in a program.

Notes:

An object simply represents any object that you may think of in the "real world". In Java, we define objects by creating a class.

Page 31: Java Fundamentals SG JAH-CJ-200

31 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Structuring ClassesStructuring Classes

• The class declaration

• Attribute variable declarations and initialization (optional)

• Methods (optional)

• Comments (optional)

//Employee.java

public class Employee {

private String id;

private String lastName;

public int getId() {…}

public void setId() {…}

}

//Employee.java

public class Employee {

private String id;

private String lastName;

public int getId() {…}

public void setId() {…}

}

Attributes

Methods

Class declaration

Comments

Notes: Classes are composed of the Java code necessary to instantiate objects, such as Shirt objects. This course divides the code in a Java class file into four separate sections:

The class declaration Attribute variable declarations and initialization (optional) Methods (optional) Comments (optional)

Page 32: Java Fundamentals SG JAH-CJ-200

32 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Structuring ClassesStructuring Classes

//Piano.java

public class Piano {

private int keys = 88;

//this method displays the number of keys of piano

public void displayPianoInformation() {

System.out.println(" A piano has " + keys + " keys.");

} //end of display method

} //end of class

//Piano.java

public class Piano {

private int keys = 88;

//this method displays the number of keys of piano

public void displayPianoInformation() {

System.out.println(" A piano has " + keys + " keys.");

} //end of display method

} //end of class

It’s a class The name of the class

The class body begin’s here

The class body end’s here

Notes: The programming code for a class is contained within a text file that must adhere to a certain structure. The following example shows a Piano class. The Piano class has one attribute variable and one method.

Page 33: Java Fundamentals SG JAH-CJ-200

33 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Class DeclarationClass Declaration

• Syntax:

[modifier] class class_identifier

• Example:

public class Piano

public class Cat

public class Shirt

//Piano.java

public class Shirt {

//write your code here

} //end of class

//Piano.java

public class Shirt {

//write your code here

} //end of class

Notes: For each class, you must write a class declaration. The syntax for declaring a class is: [modifier] class class_identifier where:

[modifier] determines the accessibility that other classes have to this class. The [modifier] is optional (indicated by the square brackets) and can be public, abstract, or final. For now, use the public modifier.

The class keyword tells the compiler that the code block is a class declaration. Keywords are words that are reserved by the Java programming language for certain constructs.

The class_identifier is the name that you give to the class. Class naming guidelines are as follows:

o Class names should be nouns, in mixed case with the first letter of each word capitalized, for example, MyClass.

o Class names should contain whole words. Avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as JVM or UML).

Page 34: Java Fundamentals SG JAH-CJ-200

34 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Class DeclarationClass Declaration

public class Shirt {

public int shirtID = 0; // Default ID for the shirt

public String description = "-description required-"; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

public char colorCode = „U‟;

public double price = 0.0; // Default price for all shirts

public int quantityInStock = 0; // Default quantity for all shirts

// This method displays the values for an item

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

} // end of display method

} // end of class

public class Shirt {

public int shirtID = 0; // Default ID for the shirt

public String description = "-description required-"; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

public char colorCode = „U‟;

public double price = 0.0; // Default price for all shirts

public int quantityInStock = 0; // Default quantity for all shirts

// This method displays the values for an item

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

} // end of display method

} // end of class

Notes: In this course, you will be developing your classes so that the Java programming code you write for each class is in its own text file or source code file. In the Java programming language, source code file names must match the public class name in the source code file and must have a .java extension. For example, the Shirt class must be saved in a file called Shirt.java. The class definition is followed by an open curly brace ({) indicating the beginning of the class_body, the attribute variables, and the methods that compose the class. The braces { } around the class_body define where the class starts and ends.

Page 35: Java Fundamentals SG JAH-CJ-200

35 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Variables declarations and assignmentsVariables declarations and assignments

public int shirtID = 0; // Default ID for the shirt

public String description = "-description required-"; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

public char colorCode = 'U';

public double price = 0.0; // Default price for all shirts

public int quantityInStock = 0; // Default quantity for all shirts

public int shirtID = 0; // Default ID for the shirt

public String description = "-description required-"; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

public char colorCode = 'U';

public double price = 0.0; // Default price for all shirts

public int quantityInStock = 0; // Default quantity for all shirts

Shirt id

Description

Color Code

Price

Quantity in stock

Notes: The attribute variable declarations and assignments block follows the first open curly brace ({). Generally, you set up all of the attribute variables for the class after this brace. The Shirt class code example contains five attribute variable declarations, one for a shirt ID, one for a description, one for a color code, one for price, and one for a quantity in stock.

Page 36: Java Fundamentals SG JAH-CJ-200

36 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

CommentsComments

Notes: You should put comments in every class that you create to make it easier to determine what the program is doing. Commenting is particularly important in longer programs developed by large teams where several programmers need to read the code. Commenting helps with the maintenance of a program when new programmers need to determine what the code is doing. Two main styles of comments can be used:

Single-line comments – A // marker tells the compiler to ignore everything to the end of the current line. In long programs, it can be very difficult to find the ending braces of the class. Commenting the structure that each ending brace belongs to makes reading and fixing errors much easier.

Traditional comments – A /* character combination tells the compiler to ignore everything on all lines up to, and including, a comment termination marker (*/). Programmers often use traditional comments to provide details for a large block of code.

There is a third type of comment called a documentation comment. You can use a Java tool, the Javadoc™ software, to create documentation for any of your classes that will be used by other programmers. In fact, all of the class library documentation that comes with the J2SE SDK was created using the javadoc tool. Documentation comments must begin with a forward slash and two asterisks (/**) and end with an asterisk and a forward slash (*/).

Page 37: Java Fundamentals SG JAH-CJ-200

37 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

MethodsMethods

• Syntax:

[modifiers] return_type method_identifier([arguments]){

method_code_block

}

• Example:

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

} // end of display method

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

} // end of display method

Notes: Methods follow the attribute variable declarations in a class. The syntax for methods is: [modifiers] return_type method_identifier ([arguments]) { method_code_block } where:

The [modifiers] represent several unique Java keywords that modify the way methods are accessed. Modifiers are optional (indicated by the square brackets).

The return_type indicates the type of value (if any) that the method returns. If the method returns a value, the type of the value must be declared. Returned values can be used by the calling method. Any method can return at most one value. If the method returns nothing, the keyword void must be used as the return_type.

The method_identifier is the name of the method.

The ([arguments]) represent a list of variables whose values are passed to the method for use by the method. Arguments are optional (as indicated by the square brackets) because methods are not required to accept arguments. Also note that the parentheses are not optional. A method that does not accept arguments is declared with an empty set of parentheses.

The method_code_block is a sequence of statements that the method performs. A wide variety of tasks can take place in the code block or body of the method.

Page 38: Java Fundamentals SG JAH-CJ-200

38 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

MethodsMethods

•Classes in Java may have methods and attributes.

•Methods define actions that a class can perform.

•Attributes describe the class.

•Classes in Java may have methods and attributes.

•Methods define actions that a class can perform.

•Attributes describe the class.

Notes:

Page 39: Java Fundamentals SG JAH-CJ-200

39 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating and Using a Test ClassCreating and Using a Test Class

• Example:

public class ShirtTest {

public static void main (String args[]) {

Shirt myShirt;

myShirt = new Shirt();

myShirt.displayShirtInformation();

}

}

public class ShirtTest {

public static void main (String args[]) {

Shirt myShirt;

myShirt = new Shirt();

myShirt.displayShirtInformation();

}

}

public class Shirt {

public void displayShirtInformation()

{

}

}

public class Shirt {

public void displayShirtInformation()

{

}

}

Shirt.java

ShirtTest.java

Notes: Most of the classes that you create throughout this course cannot be used (executed and tested) by themselves. Instead, you must execute another class to create an object instance of your class before your class can be tested. Throughout this course, you use a test or main class to test each of your classes. Every test class within this course should be named so that it can be recognized as the test class for a particular class you have written. Specifically, each test class name should consist of the name of the class you are testing, followed by the word ―Test.‖ For example, the class designed to test the Shirt class is called ShirtTest. Test classes have two distinct tasks to perform. These are:

Providing a starting point, called the main method, for your program

Creating an object instance of your class and testing its methods

Page 40: Java Fundamentals SG JAH-CJ-200

40 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The main methodThe main method

• Syntax:

public static void main (String args[])

• The main() method is the normal entry point for Java

applications

• To create an application, you write a class definition thatincludes a main() method

Notes: The main method is a special method that the Java virtual machine recognizes as the starting point for every Java program that runs from the command line or from a prompt. Any program that you want to run from a command line or a prompt must have a main method. The syntax for the main method is: public static void main (String args[])

The main method contains two required modifiers, public and static. The main method does not return any values, so it has a return type of void.

The main method has a method identifier (name) of ―main.‖

The main method accepts zero or more objects of type String (String args[]). This syntax allows you to type in values on the command line to be used by your program while it is running.

Page 41: Java Fundamentals SG JAH-CJ-200

41 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The main methodThe main method

• This is the definition of the class OurFirstProgram. The class definition only

contains the method main

• This is the definition of the method main()

• The keyword public indicates it is globally accesible

• The keyword static ensures it is accesible even though no objects of the class

exist

• The keyword void indicates it does not return value

public class OurFirstProgram {

public static void main (String args[]) {

System.out.println("Rome wasn‟t burned in a day!");

}

}

public class OurFirstProgram {

public static void main (String args[]) {

System.out.println("Rome wasn‟t burned in a day!");

}

}

Notes: The code for the method appears between the pair of curly braces. This version of the method has only one executable statement: System.out.println(―Rome wans´t burn in a day!!‖);

System is the name of a standard class that contains objects that encapsulate the standard I/O devices for your system—the keyboard for command-line input and command-line output to the display. It is contained in the package java.lang, so it is always accessible just by using the simple class name System.

The object out represents the standard output stream—the command line on your display screen—and is a data member of the class System. The member, out, is a special kind of member of the System class. Like the method main() in our OurFirstProgram class, it is static. This means that out exists even though there are no objects of type System Using the class name, System, separated from the member name out by a period—System.out—references the out member.

The bit at the rightmost end of the statement, println(―Rome wasn´t burn in a day!!‖), calls the println() method that belongs to the object out, and that outputs the text string that appears between the parentheses to your display. This demonstrates one way in which you can call a class method—by using the object name followed by the method name, with a period separating them. The stuff between the parentheses following the name of a method is information that is passed to the method when it is executed. As we said, for println() it is the text we want to output to the command line.

Page 42: Java Fundamentals SG JAH-CJ-200

42 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Compiling a programCompiling a program

Notes: The process of writing and using a JAVA program is as follows: Writing: define your classes by writing what is called .java files (also known as your

source code). Compiling: send these .java files to the JAVA compiler, which will produce .class

files Running: send one of these .class files to the JAVA interpreter to run your

program. Compiling converts the class files you write into bytecode that can be executed by a Java virtual machine. Remember the rules for naming your Java source files. If a source file contains a public class, the source file must use the same name as the public class, with a .java extension. For example, the class Shirt must be saved in a file called Shirt.java.

Page 43: Java Fundamentals SG JAH-CJ-200

43 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Compiling a programCompiling a program

1. Go the directory where the source code files are stored.

2. Enter the following command for each .java file you want to

compile.

• Syntax:

javac filename

• Example:

javac Shirt.java

Notes: After the compilation has finished, and assuming no compilation errors have occurred, you should have a new file called classname.class in your directory for each source code file that you compiled. If you compile a class that references other objects, the classes for those objects are also compiled (if they have not been compiled already). For example, if you compiled the ShirtTest.java file (which references a Shirt object), you have a Shirt.class and ShirtTest.class file.

Page 44: Java Fundamentals SG JAH-CJ-200

44 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Executing (Testing) a programExecuting (Testing) a program

1. Go the directory where the class files are stored.

2. Enter the following for the class file that contains the main

method.

• Syntax

java classname

• Example

java ShirtTest

Notes: When you have successfully compiled your source code files, you can execute and test them using the Java virtual machine.

Page 45: Java Fundamentals SG JAH-CJ-200

45 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Debugging TipsDebugging Tips

• Check line referenced in error message

• Check for semicolons

• Check for even number of braces

Notes: You will almost always have at least one error in any code you write. Debugging is the term used for fixing errors or bugs in your code. When the compiler reports a syntax error, the error may not be on the line number indicated by the error message. First, check the line for which the error was reported. If that line does not contain syntax errors, check the preceding several lines in the program. The Java compiler generates syntax error messages when the syntax of a program is incorrect. When you are learning how to program, sometimes it is helpful to ―break‖ a working program so you can see the error messages produced by the compiler. Then, when you encounter that error message again, you will have an idea of the error’s cause.

Page 46: Java Fundamentals SG JAH-CJ-200

46 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 03 Writing, Compiling, and Testing a Basic Program Lab Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Become familiar with the structure and parts of a basic Java Program.

Page 47: Java Fundamentals SG JAH-CJ-200

47 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. One.Lab Exercises. One.

1. Create a new class named Quotation.java with one methoddisplay()

public class Quotation {

public void display(String name) {

System.out.println("Welcome to sun Mr/Ms " + name);

}

} //end class

2. Compile the class.

Lab Solutions:

Page 48: Java Fundamentals SG JAH-CJ-200

48 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. One.Lab Exercises. One.

3. Write a test class like this:

public class QuotationTest {

public static void main(String[] args) {

Quotation obj = new Quotation();

obj.display("Raul");

}

}

4. Execute the class

Lab Solutions:

Page 49: Java Fundamentals SG JAH-CJ-200

49 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Two.Lab Exercises. Two.

1. Create a new class Car with the following methods:

– public void start()

– public void stop()

– public int drive(int howlong)

– The method drive() has to return the total distance driven

by the car for the specified time. Use the following formula

to calculate the distance:

distance = howlong*60;

2. Write another class CarOwner and that creates an instance of

the object Car and call its methods. The result of each method

call has to be printed using System.out.println().

Lab Solutions:

Page 50: Java Fundamentals SG JAH-CJ-200

50 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 04 Declaring, Initializing, and Using Variables Objectives Identifying Variable Use and Syntax

o Uses for Variables o Variable Declaration and Initialization

Describing Primitive Data Types o Integral Primitive Types o Floating Point Primitive Types o Textual Primitive Type o Logical Primitive Type o Choosing a Data Type

Declaring Variables and Assigning Values to Variables o Naming a Variable o Assigning a Value to a Variable o Constants o Storing Primitive and Constants in Memory

Using Arithmetic Operators to Modify Values o Standard Mathematical Operators o Increment and Decrement Operators (++ and --) o Operator Precedence

Using Promotion and Type Casting o Casting primitive types o Implicit versus explicit casting o Examples

Objectives Upon completion of this module, you should be able to: Identify the uses for variables and define the syntax for a variable List the eight Java programming language primitive data types Declare, initialize, and use variables and constants according to Java programming

language guidelines and coding standards Modify variable values using operators Use promotion and type casting

Page 51: Java Fundamentals SG JAH-CJ-200

51 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Identifying Variable Use and SyntaxIdentifying Variable Use and Syntax

public class PianoKeys {

public static void main(String[] args) {

int keys = 88;

System.out.println("A piano has " + keys + " keys.");

}

}

public class PianoKeys {

public static void main(String[] args) {

int keys = 88;

System.out.println("A piano has " + keys + " keys.");

}

}

Notes: A variable is a name for a location in memory used to hold a data value. A variable declaration instructs the compiler to reserve a portion of main memory space large enough to hold a particular type of value and indicates the name by which we refer to that location. Consider the program PianoKeys, shown above. The first line of the main method is the declaration of a variable named keys that holds an integer (int) value. The declaration also gives keys an initial value of 88. If an initial value is not specified for a variable, the value is undefined. Most Java compilers give errors or warnings if you attempt to use a variable before you’ve explicitly given it a value.

Page 52: Java Fundamentals SG JAH-CJ-200

52 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Identifying Variable Use and SyntaxIdentifying Variable Use and Syntax

public class Geometry {

public static void main(String[] args) {

int sides = 7; // declaration with initialization

System.out.println("A heptagon has " + sides + " sides.");

sides = 10; // assignment statement

System.out.println("A decagon has " + sides + " sides.");

sides = 12;

System.out.println("A dodecagon has " + sides + " sides.");

}

}

public class Geometry {

public static void main(String[] args) {

int sides = 7; // declaration with initialization

System.out.println("A heptagon has " + sides + " sides.");

sides = 10; // assignment statement

System.out.println("A decagon has " + sides + " sides.");

sides = 12;

System.out.println("A dodecagon has " + sides + " sides.");

}

}

Notes: A variable can store only one value of its declared type. A new value overwrites the old one. In this case, when the value 10 is assigned to sides, the original value 7 is overwritten and lost forever. However, when a reference is made to a variable, such as when it is printed, the value of the variable is not changed. The Java language is strongly typed, meaning that we are not allowed to assign a value to a variable that is inconsistent with its declared type. Trying to combine incompatible types will generate an error when you attempt to compile the program. Therefore, the expression on the right-hand side of an assignment statement must evaluate to a value compatible with the type of the variable on the left-hand side.

Page 53: Java Fundamentals SG JAH-CJ-200

53 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses for variablesUses for variables

• Holding unique data for an object instance

• Assigning the value of one variable to another

• Representing values within a mathematical expression

• Printing the values to the screen

• Holding references to other objects

Notes: Examples: id = 428890; price = 2.35F; myChar = ´t´; isOpen = false; The = operator assigns the value on the right side to the item on the left side. The operator should be read as is assigned to.

Page 54: Java Fundamentals SG JAH-CJ-200

54 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Variable Declaration and InitializationVariable Declaration and Initialization

• Syntax (attribute or instance variables):

[modifiers] type identifier = value;

• Syntax (local variables):

type identifier;

• Syntax (local variables)

type identifier = value;

Notes: Attribute variable declarations and initialization follow the same general syntax. The syntax for attribute variables declaration and initialization is: [modifiers] type identifier = value; Local variables can be declared and initialized separately (on separate lines of code) or in a single line of code. The syntax for declaring a variable inside of a method is:

type identifier; The syntax for initializing a variable inside of a method is:

identifier = value; The syntax for declaring and initializing a variable inside of a method is:

type identifier = value;

Page 55: Java Fundamentals SG JAH-CJ-200

55 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Describing Primitive Data TypesDescribing Primitive Data Types

• Integral types (byte, short, int, and long)

• Floating point types (float and double)

• Textual type (char)

• Logical type (boolean)

Notes: Many of the values in Java programs are stored as primitive data types. These are the eight primitive types built into the Java programming language. The sizes of the primitives are defined by the JVM. They are the same on all platforms.

Page 56: Java Fundamentals SG JAH-CJ-200

56 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Integral Primitive TypesIntegral Primitive Types

• Signed whole numbers

• Initialized to zero

Notes: There are four integral primitive types in the Java programming language, identified by the keywords byte, short, int, and long. These types store numbers that do not have decimal points. When you specify a literal value for a long type, put a capital L to the right of the value to explicitly state that it is a long type. Integer literals are assumed by the compiler to be of type int unless you specify otherwise using an L indicating long type. The Shirt class contains two integral types, int, to hold the default value for a shirt ID and the quantity in stock, respectively: public int shirtID = 0; // Default ID for the shirt public int quantityInStock = 0; // Default quantity for all shirts

Page 57: Java Fundamentals SG JAH-CJ-200

57 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Integral Primitive TypesIntegral Primitive Types

Notes: For each of the binary numbers shown here, the leftmost bit is the sign bit, marked with an s. When the sign bit is 0 the number is positive, and when it is 1 the number is negative. Binary negative numbers are represented in what is called 2’s complement form.

Page 58: Java Fundamentals SG JAH-CJ-200

58 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Integral Primitive TypesIntegral Primitive Types

public class IntegralType {

public static void main( String args[] ) {

byte age = 12;

short idCourse = 1230;

int javaProgrammers = 2300000;

long worldPeople = 5000000000L;

System.out.println(worldPeople);

}

}

public class IntegralType {

public static void main( String args[] ) {

byte age = 12;

short idCourse = 1230;

int javaProgrammers = 2300000;

long worldPeople = 5000000000L;

System.out.println(worldPeople);

}

}

Notes: If you want to define an integer literal of type long, you need to append an L to the value. The values 1L, -9999L, and 123456789L are all of the type long

Page 59: Java Fundamentals SG JAH-CJ-200

59 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Floating Point Primitive TypesFloating Point Primitive Types

• “General” numbers (can have fractional parts)

• Initialized to zero

Notes: There are two types for floating point numbers, float and double. They are used to store numbers with values to the right of the decimal point. As with the different integer types, these share functionality but differ in size. It is not possible to state the largest or smallest value that each of these can hold because they allow variable accuracy depending on the magnitude of the number. (That is, the number can hold X number of digits, but the placement of the decimal point determines whether it is an extremely large number, or whether it is a small number like pi) When you specify a literal value for a float type, put a capital F (float) to the right of the value to explicitly state that it is a float type, not a double type. Literal values for floating point types are assumed to be of type double unless you specify otherwise, using the F indicating float type.

Page 60: Java Fundamentals SG JAH-CJ-200

60 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Floating Point Primitive TypesFloating Point Primitive Types

public class Tax {

public static void main( String args[] ) {

double price = 20;

float tax = 0.15f;

double total;

total = price * tax;

System.out.println( total );

}

}

public class Tax {

public static void main( String args[] ) {

double price = 20;

float tax = 0.15f;

double total;

total = price * tax;

System.out.println( total );

}

}

Notes: Floating-point literals are of type double by default, so 1.0 and 345.678 are both of type double. When you want to specify a value of type float, you just append and f, or an F, to the value, so 1.0f and 345.678F are both literals of type float.

Page 61: Java Fundamentals SG JAH-CJ-200

61 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Textual Primitive TypesTextual Primitive Types

• Any unsigned Unicode character is a char primitive data type

• A character is a single Unicode character between two single

quotes

• Initialized to zero (\u0000)

Notes: Another data type you use for storing and manipulating data is single-character information. The primitive type used for storing a single character, such as a y is char, which is 16 bits in size. You can store only one character in a char variable. If you want to store whole words or phrases you use an object type (not primitive type) called String. When you assign a literal value to a char variable, such as t, you must use single quotation marks around the character: ’t’ Using single quotation marks around the character clarifies for the compiler that the t is just the literal value t, rather than a variable t that represents another value. The char type does not store the actual character you type, such as the t shown. The char representation is reduced to a series of bits that corresponds to a character. The number-character mappings are set up in the character set that the programming language uses. The Java programming language uses a 16-bit character set called Unicode that can store all the necessary displayable characters from the vast majority of languages used in the modern world. Therefore, your programs can be written so that they work correctly and display the correct language for most countries. Unicode contains a subset of ASCII (the first 128 characters).

Page 62: Java Fundamentals SG JAH-CJ-200

62 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Textual Primitive TypesTextual Primitive Types

public class PrintChar {

public static void main( String args[] ) {

char c = 'x';

int i = c;

System.out.println( "Print: " + c );

System.out.println( "Print: " + i );

c = 88;

System.out.println( "Print: " + c );

}

}

public class PrintChar {

public static void main( String args[] ) {

char c = 'x';

int i = c;

System.out.println( "Print: " + c );

System.out.println( "Print: " + i );

c = 88;

System.out.println( "Print: " + c );

}

}

Notes: Variables of type char store a single character code. They each occupy 16 bits, or 2 bytes, in memory because all characters in Java are stored as Unicode.

Page 63: Java Fundamentals SG JAH-CJ-200

63 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Logical Primitive TypesLogical Primitive Types

• boolean values are distinct in Java

• An int value can NOT be used in place of a boolean

• A boolean can store either true or false

• Initialized to false

Notes: Variables of type boolean can store only:

The Java programming language literals true or false

The results of an expression that only evaluates to true or false. For example, if the variable answer is equal to 42, then the expression ―if answer < 42‖ evaluates to a false result.

Page 64: Java Fundamentals SG JAH-CJ-200

64 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Logical Primitive TypesLogical Primitive Types

public class CatDog {

public static void main( String args[] ) {

boolean personWithDog = true;

boolean personWithCat = false;

System.out.println("personWithDog is "+personWithDog);

System.out.println("personWithCat is "+personWithCat);

}

}

public class CatDog {

public static void main( String args[] ) {

boolean personWithDog = true;

boolean personWithCat = false;

System.out.println("personWithDog is "+personWithDog);

System.out.println("personWithCat is "+personWithCat);

}

}

Notes: Variables of type boolean can have only of two values, true or false. The values true and false are boolean literals.

Page 65: Java Fundamentals SG JAH-CJ-200

65 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Naming a VariableNaming a Variable

• Rules:

– Variable identifiers must start with either an uppercase or

lowercase letter, an underscore (_), or a dollar sign ($).

– Variable identifiers cannot contain punctuation, spaces, or

dashes.

– Java keywords cannot be used.

• Guidelines:

– Begin each variable with a lowercase letter; subsequent

words should be capitalized, such as myVariable.

– Chose names that are mnemonic and that indicate to the

casual observer the intent of the variable.

Notes: Just as with a class or method, you must assign each variable in your program an identifier or a name. Remember, the purpose of the variable is to act as a mechanism for storing and retrieving values. Therefore, you should make variable identifiers simple but descriptive. For example, if you store the value of an item ID, you might name the variable myID, itemID, itemNumber, or anything else that clarifies the use of the variable to yourself, and to others reading your program. The Java programming language is a case-sensitive programming language. Case sensitivity means distinguishing between the uppercase and lowercase representations of each alphabetical character. The Java programming language considers two characters in your code to be different if their capitalization differs. For example, a variable called order is different from a variable called Order.

Page 66: Java Fundamentals SG JAH-CJ-200

66 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Assigning a Value to a VariableAssigning a Value to a Variable

• Example:

double price = 12.99;

• Example (boolean):

boolean isOpen = false;

Notes: You can assign a value to a variable at the time the variable is declared or you can assign the variable later. To assign a value to a variable during declaration, add an equal sign after the declaration followed by the value to be assigned. For example, the price attribute variable in the Shirt class could be assigned the value 12.99 as the price for a Shirt object. double price = 12.99; An example of boolean variable declaration and assignment is: boolean isOpen = false; The = operator assigns the value on the right side to the item on the left side. The = operator should be read as ―is assigned to.‖ In a previous example you could say, ―12.99 is assigned to price.‖ Attribute variables are automatically initialized: integral types are set to 0, floating point types are set to 0.0, the char type is set to \u0000, and the boolean type is set to false. However, you should explicitly initialize your attribute variables so that other people can read your code. Local variables (declared within a method) must be explicitly initialized before being used.

Page 67: Java Fundamentals SG JAH-CJ-200

67 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring and Initializing Several Variables in One Line of CodeDeclaring and Initializing Several Variables in One Line of Code

• Syntax:

type identifier = value [, identifier = value];

• Example:

double price = 0.0, wholesalePrice = 0.0;

int miles = 0, //One mile is 8 furlong

furlong = 0, //One furlong is 220 yards

yards = 0, //One yard is 3 feet

feet = 0;

Notes: You can declare one or more variables on the same line of code, but only if they are all of the same type. The syntax for declaring several variables in one line of code is: type identifier = value [, identifier = value]; Therefore, if there is a separate retail price and wholesale price in the Shirt class, they might be declared as follows: double price = 0.0, wholesalePrice = 0.0;

Page 68: Java Fundamentals SG JAH-CJ-200

68 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Additional Ways to Declare Variables and Assign Values to VariabAdditional Ways to Declare Variables and Assign Values to Variablesles

• Assigning literal values:

int ID = 0;

float pi = 3.14F;

char myChar = ‟G‟;

boolean isOpen = false;

• Assigning the value of one variable to another variable:

int ID = 0;

int saleID = ID;

float casePrice = 189.99F;

float price = casePrice;

Notes: Explicit data values that appear in your program are called literals. Each literal will also be of a particular type: int, float, double, etc.

Page 69: Java Fundamentals SG JAH-CJ-200

69 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Additional Ways to Declare Variables and Assign Values to VariabAdditional Ways to Declare Variables and Assign Values to Variablesles

• Assigning the result of an expression to integral, floating point,

or Boolean variables

float numberOrdered = 908.5F;

float casePrice = 19.99F;

float price = (casePrice * numberOrdered);

int hour = 12;

boolean isOpen = (hour > 8);

• Assigning the return value of a method call to a variable

Notes:

Page 70: Java Fundamentals SG JAH-CJ-200

70 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ConstantsConstants

• Variable (can change):

double salesTax = 6.25;

• Constant (cannot change):

final double SALES_TAX = 6.25;

final int FEET_PER_YARD = 3;

final double MM_PER_INCH = 25.4;

• A final variable may not modified once it has been assigned a

value.

• Guideline – Constants should be capitalized with words

separated by an underscore (_).

Notes: A variable that is declared using the final modifier denotes its inability to have its value changed once initialized. Use all capital letters and underscores for identifier.

Page 71: Java Fundamentals SG JAH-CJ-200

71 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Storing Primitive and Constants in MemoryStoring Primitive and Constants in Memory

Notes: When you use a literal value or create a variable or constant and assign it a value, the value is stored in the memory of the computer. The figure illustrates that local variables are stored separately (on the stack) from attribute variables on the heap. Objects and their attribute variables and methods are usually stored in heap memory. Heap memory is dynamically allocated memory chunks containing information used to hold objects (including their attribute variables and methods) while they are needed by your program. Other variables are usually stored in stack memory. Stack memory stores items that are only used for a brief period of time (shorter than the life of an object), such as variables declared inside of a method.

Page 72: Java Fundamentals SG JAH-CJ-200

72 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Standard Mathematical OperatorsStandard Mathematical Operators

Notes: Arithmetic operators are used to indicate arithmetic operations like addition, subtraction, multiplication, division, and modulo operations. The + operator is used to indicate the addition operation. It is used for adding values stored in two or more variables. The following expression illustrates the use of the + operator: a + b The - operator is used to indicate the subtraction operation. It is used for subtracting a value stored in one variable from a value stored in another variable. The following expression illustrates the use of the – operator: a - b The * operator is used to indicate the multiplication operation. It is used for multiplying values stored in two variables. The following expression illustrates the use of the *operator: a * b The / operator is used to indicate the division operation. It is used to divide a value stored in one variable by a value stored in another variable. The following expression illustrates the use of the / operator: a / b

Page 73: Java Fundamentals SG JAH-CJ-200

73 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Page 74: Java Fundamentals SG JAH-CJ-200

74 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Standard Mathematical OperatorsStandard Mathematical Operators

Notes: The % operator is used to indicate the modulo operation. It is used to find the remainder after dividing a value stored in one variable by a value stored in another variable. The following expression illustrates the use of the % operator: a % b

Page 75: Java Fundamentals SG JAH-CJ-200

75 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Standard Mathematical OperatorsStandard Mathematical Operators

public class Fruit {

public static void main(String[] args) {

// Declare and initialize three variables

int numOranges = 5; // Count of oranges

int numApples = 10; // Count of apples

int numFruit = 0; // Count of fruit

//Calculate the total fruit count

numFruit=numOranges+numApples;

// Display the result

System.out.println(“A totally fruity program”);

System.out.println(“Total fruit is “ + numFruit);

}

}

public class Fruit {

public static void main(String[] args) {

// Declare and initialize three variables

int numOranges = 5; // Count of oranges

int numApples = 10; // Count of apples

int numFruit = 0; // Count of fruit

//Calculate the total fruit count

numFruit=numOranges+numApples;

// Display the result

System.out.println(“A totally fruity program”);

System.out.println(“Total fruit is “ + numFruit);

}

}

Notes: The first three statements in main() declare the variables numOranges, numApples, and numFruit to be of type int and initialize them to the values 5, 10, and 0, respectively. The next statement adds the values stored in numOranges and numApples, and stores the result, 15, in the variable numFruit. We then generate some output from the program.

Page 76: Java Fundamentals SG JAH-CJ-200

76 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Standard Mathematical OperatorsStandard Mathematical Operators

public class TempConverter {

public static void main(String[] args) {

final int BASE = 32;

final double CONVERSION_FACTOR = 9.0 / 5.0;

int celsiusTemp = 24; // value to convert

double fahrenheitTemp;

fahrenheitTemp = celsiusTemp * CONVERSION_FACTOR + BASE;

System.out.println("Celsius Temperature: "

+ celsiusTemp);

System.out.println("Fahrenheit Equivalent: "

+ fahrenheitTemp);

}

}

public class TempConverter {

public static void main(String[] args) {

final int BASE = 32;

final double CONVERSION_FACTOR = 9.0 / 5.0;

int celsiusTemp = 24; // value to convert

double fahrenheitTemp;

fahrenheitTemp = celsiusTemp * CONVERSION_FACTOR + BASE;

System.out.println("Celsius Temperature: "

+ celsiusTemp);

System.out.println("Fahrenheit Equivalent: "

+ fahrenheitTemp);

}

}

Notes:

Page 77: Java Fundamentals SG JAH-CJ-200

77 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Increment and Decrement Operators (++ and Increment and Decrement Operators (++ and ----))

Notes: A common requirement in programs is to add or subtract 1 from the value of a variable. You can do this by using the + operator, as follows: age = age + 1; However, incrementing or decrementing by 1 is such a common action that there are specific unary operators for it: the increment (++) and decrement (--) operators. These operators can come before (pre-increment and pre-decrement) or after (post-increment and post-decrement) a variable. Use these operators within an expression cautiously. With the prefix form, the operation (increment or decrement) is applied before any subsequent calculations or assignments. With the postfix form, the operation is applied after the subsequent calculations or operations, so that the original value is used in subsequent calculations or assignments, not the updated value.

Page 78: Java Fundamentals SG JAH-CJ-200

78 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Increment and Decrement Operators (++ and Increment and Decrement Operators (++ and ----))

Notes:

Page 79: Java Fundamentals SG JAH-CJ-200

79 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Increment and Decrement Operators (++ and Increment and Decrement Operators (++ and ----))

54y = x--5

44y = --x5

56y = x++5

66y = ++x5

Final value of xFinal value of yExpressionInitial value of x

Notes:

Page 80: Java Fundamentals SG JAH-CJ-200

80 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Increment and Decrement Operators (++ and Increment and Decrement Operators (++ and ----))

public class UnaryOperators {

public static void main(String args[ ]) {

int y;

int x = 5;

y = ++x;

System.out.println("x = " + x + "\ty = " + y);

x = 5;

y = x++;

System.out.println("x = " + x + "\ty = " + y);

}

}

public class UnaryOperators {

public static void main(String args[ ]) {

int y;

int x = 5;

y = ++x;

System.out.println("x = " + x + "\ty = " + y);

x = 5;

y = x++;

System.out.println("x = " + x + "\ty = " + y);

}

}

Notes:

Page 81: Java Fundamentals SG JAH-CJ-200

81 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Operator precedenceOperator precedence

• Rules of precedence:

1. Operators within a pair of parentheses

2. Increment and decrement operators

3. Multiplication and division operators, evaluated from left to

right

4. Addition and subtraction operators, evaluated from left to

right

• Example of need for rules of precedence (is the answer 34 or

9?):

c = 25 - 5 * 4 / 2 - 10 + 4;

Notes: To make mathematical operations consistent, the Java programming language follows the standard mathematical rules for operator precedence. Operators are processed in the following order:

1. Operators within a pair of parentheses 2. Increment and decrement operators 3. Multiplication and division operators, evaluated from left to right 4. Addition and subtraction operators, evaluated from left to right

If standard mathematical operators of the same precedence appear successively in a statement, the operators are evaluated from left to right.

Page 82: Java Fundamentals SG JAH-CJ-200

82 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Operator precedenceOperator precedence

Notes:

Page 83: Java Fundamentals SG JAH-CJ-200

83 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using ParenthesesUsing Parentheses

• Examples:

c = (((25 - 5) * 4) / (2 - 10)) + 4;

c = ((20 * 4) / (2 - 10)) + 4;

c = (80 / (2 - 10)) + 4;

c = (80 / -8) + 4;

c = -10 + 4;

c = -6;

Notes:

Page 84: Java Fundamentals SG JAH-CJ-200

84 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Casting primitive types Casting primitive types

• Java is a strictly typed language

• Assigning the wrong type of value to a variable could result in a

compile error or a JVM exception

• Casting a value allows it to be treated as another type

• The JVM can implicitly promote from a narrower type to a wider

type

• To change to a narrower type, you must cast explicitly

Notes: The Java language permits conversions between integer values and floating-point values. In addition, because every character corresponds to a number in the Unicode encoding, values of the char type may be converted to and from the integer and floating-point types. The boolean type is the only primitive type that cannot be converted to or from another primitive type in Java. There are two types of conversions: widening and narrowing conversions. Widening conversions occur when a value of one type is converted to a type that is represented with more bits, therefore having a larger range. Widening conversions are performed by Java automatically when you assign an int literal value to a double variable or a char literal to an int variable. Narrowing conversions occur when a value is converted to a type that is represented with fewer bits. Narrowing conversions are more risky; since you are converting from a type of a wider range to a smaller range, you risk losing data. For example, you may convert an int literal value of 21 to a byte, but you could not properly convert an int literal value of 1099 to a byte, since the byte type has a possible range of values from -128 to 127. However, if you must do a narrowing conversion, you may use a cast to do so by putting the name of the desired type (the result type) in parentheses before the value to be converted. These examples cast an int literal value to a byte: int i = 25; byte b = (byte) i;

Page 85: Java Fundamentals SG JAH-CJ-200

85 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

This example casts a double literal value to an int: int i = (int) 25.123; // The resulting value of i will be 25

Page 86: Java Fundamentals SG JAH-CJ-200

86 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Implicit versus explicit casting Implicit versus explicit casting

• Casting is automatically done when no loss of information is

possible

• An explicit cast is required when there is a "potential" loss of

accuracy

Notes: In some circumstances, the compiler changes the type of a variable to a type that supports a larger size value. This action is referred to a promotion. Some promotions occur automatically by the compiler if data would not be lost by doing so. These promotions include:

If you assign a smaller type (on the right of the =) to a larger type (on the left of the =)

If you assign an integral type to a floating point type (because there are no decimal places to lose)

The following example contains a literal (an int) that will automatically be promoted to another type (a long) to before the value (6) is assigned to the variable (big of type long). The following examples show what will be automatically promoted by the compiler and what will not be. long big = 6; Because 6 is an int type, promotion works because the int value is converted to a long value. Type casting lowers the range of a value, quite literally chopping it down to a smaller size, by changing the type of the value. For example, by converting a long value to an int value. You do this so that you can use methods that accept only certain types as arguments, so that you can assign values to a variable of a smaller data type, or to save memory.

Page 87: Java Fundamentals SG JAH-CJ-200

87 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Put the target_type (the type the value is being type cast to) in parentheses in front of the item that you are type casting. The syntax for type casting a value is: identifier = (target_type) value where:

The identifier is the name you assign to the variable.

The value is the value you want to assign to the identifier.

The (target_type) is the type to which you want to type cast the value. Notice that the target_type must be in parentheses.

Page 88: Java Fundamentals SG JAH-CJ-200

88 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ExamplesExamples

byte b = 3;

int x = b;

byte a;

int b = 3;

a = (byte)b;

int num1 = 53; // 32 bits of memory to hold the value

int num2 = 47; // 32 bits of memory to hold the value

byte num3; // 8 bits of memory reserved

num3 = (num1 + num2); // causes compiler error

Notes: Assigning a variable or an expression to another variable can lead to a mismatch between the data types of the calculation and the storage location you are using to save the result. Specifically, the compiler will either recognize that precision will be lost and not allow you to compile the program, or the result will be incorrect. To fix this problem, variable types have to either be promoted to a larger size type or type cast to a smaller size type. For example, consider the following assignment: int num1 = 53; // 32 bits of memory to hold the value int num2 = 47; // 32 bits of memory to hold the value byte num3; // 8 bits of memory reserved num3 = (num1 + num2); // causes compiler error This code should work, because a byte, while smaller than an int, is large enough to store a value of 100. However, the compiler will not make this assignment and, instead, issues a ―possible loss of precision‖ error because a byte value is smaller than an int value. To fix this problem, you can either type cast the right side data type down to match the left side data type, or declare the variable on the left side (num3) to be a larger data type, such as an int. This problem is fixed by changing num3 to a int: int num1 = 53; int num2 = 47; int num3; num3 = (num1 + num2);

Page 89: Java Fundamentals SG JAH-CJ-200

89 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ExamplesExamples

int num1 = 53; // 32 bits of memory to hold the value

int num2 = 47; // 32 bits of memory to hold the value

byte num3; // 8 bits of memory reserved

num3 = (byte)(num1 + num2); // no data loss

Notes:

Page 90: Java Fundamentals SG JAH-CJ-200

90 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

ExamplesExamples

short s = 259;

byte b = s; // Compiler error

System.out.println(“s = ” + s + “, b = ” + b);

short s = 259;

byte b = (byte)s; // Explicit cast

System.out.println(“s = ” + s + “, b = ” + b);

1100000010000000

11000000

b = (byte)s

Notes: Casting means explicitally telling Java to make a conversion. A casting operation may widen or narrow its argument. To cast, just precede a value with the paranthesized name of desired type.

Page 91: Java Fundamentals SG JAH-CJ-200

91 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Examples Examples

public class ExplicitCasting {

public static void main( String args[] ) {

byte b;

int i = 266; //0000000100001010

b = (byte)i; // 00001010

System.out.println("byte to int is " + b );

}

}

public class ExplicitCasting {

public static void main( String args[] ) {

byte b;

int i = 266; //0000000100001010

b = (byte)i; // 00001010

System.out.println("byte to int is " + b );

}

}

Notes: When this code is executed, the number 266 (binary 100001010) must be squeezed into a single byte. This is accomplished by preserving the low-order byte of the value and discarding the rest.

Page 92: Java Fundamentals SG JAH-CJ-200

92 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Page 93: Java Fundamentals SG JAH-CJ-200

93 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 05 Using Primitive Types, Operators and Type Casting, in a Program Lab Objectives Lab Exercises

Objectives Upon completion of this module, you should be able to: Write the code to declare, assign values to, and use variables in a program Practice using operators and type-casting

Page 94: Java Fundamentals SG JAH-CJ-200

94 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

1. Create a class called Rectangle.java, define a variable

called length of type int and define another variable called

width of type int.

2. Assign length equals to 10 and width equals to 2.

3. In the main method create an instance of the Rectangle object.

Define a variable called area of type int, compute and print the

area of the rectangle. For example:

Rectangle rectangle = new Rectangle();

int area = rectangle.length * rectangle.width;

System.out.println(“Area : ” + area);

4. Compile an run the program.

Solutions to Lab Exercises:

Page 95: Java Fundamentals SG JAH-CJ-200

95 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 06 Creating and Using Objects

Objectives

o Declaring Object References, Instantiating Objects, and Initializing Object References

o Declaring Object Reference Variables o Instantiating an Object o Initializing Object Reference Variables o Using an Object Reference Variable to Manipulate Data o Storing Object Reference Variables in Memory o Assigning a Reference From One Variable to Another

Using the String Class o Creating a String Object With the new Keyword o Creating a String Object Without the new Keyword o Storing String Objects in Memory o Using Reference Variables for String Objects

Objectives Upon completion of this module, you should be able to: Declare, instantiate, and initialize object reference variables Compare how object reference variables are stored in relation to primitive variables Use a class (the String class) included in the Java SDK

Page 96: Java Fundamentals SG JAH-CJ-200

96 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

Notes:

The class is the basis for object-oriented programming.

The data and the operations on the data are encapsulated in a class.

The data variables and the methods in a class are called class members.

Variables, which hold the data (or point to it in case of reference variables), are said to represent the state of an object (that may be created out of the class), and the methods constitute its behavior.

Page 97: Java Fundamentals SG JAH-CJ-200

97 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

The phrase "to create an

instance of an object“ means

to create a copy of this object

in the computer's memory

according to the definition of

its class.

Notes:

Page 98: Java Fundamentals SG JAH-CJ-200

98 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

Class Object (Instance)

Notes:

Page 99: Java Fundamentals SG JAH-CJ-200

99 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring Object References, Instantiating Objects, and InitialiDeclaring Object References, Instantiating Objects, and Initializing Object zing Object

ReferencesReferences

A primitive variable holds the value of the data

item, while a reference variable holds the

memory address where the data item (object) is

stored.

Notes: Object reference variables are variables containing an address to an object in memory. A letter is like a reference variable because it has an address pointing to a particular building object. The illustration demonstrates addresses pointing to different houses.

Page 100: Java Fundamentals SG JAH-CJ-200

100 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring Object References, Instantiating Objects, and InitialiDeclaring Object References, Instantiating Objects, and Initializing Object zing Object

ReferencesReferences

public class ShirtTest {

public static void main (String args[]) {

Shirt myShirt = new Shirt();

myShirt.displayShirtInformation();

}

}

public class ShirtTest {

public static void main (String args[]) {

Shirt myShirt = new Shirt();

myShirt.displayShirtInformation();

}

}

public class Shirt {

public int shirtID = 0;

public String description = "-description required-"; public char colorCode = „U‟;

public double price = 0.0;

public int quantityInStock = 0;

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

}

}

public class Shirt {

public int shirtID = 0;

public String description = "-description required-"; public char colorCode = „U‟;

public double price = 0.0;

public int quantityInStock = 0;

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

}

}

Notes: The example shows a ShirtTest class that creates one variable, an object reference variable (myShirt), and initializes the variable to point to an instance of the Shirt class. When the reference variable has been created and initialized, it can be used to invoke the displayShirtInformation method of the Shirt object. Declaring and initializing a reference variable is very similar to declaring and initializing a primitive type variable. The only difference is that you must create an object instance (from a class) for the reference variable to point to before you can initialize the object instance. To declare, instantiate, and initialize an object reference variable:

1. Declare a reference to the object by specifying its identifier and the type of object that the reference points to (the class of the object).

2. Create the object instance using the new keyword. 3. Initialize the object reference variable by assigning the object to the object reference

variable.

Page 101: Java Fundamentals SG JAH-CJ-200

101 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring Object Reference VariablesDeclaring Object Reference Variables

• Syntax:

Classname identifier;

• Example:

Shirt myShirt;

Circle x;

Cat gardfiel;

Notes: To declare an object reference variable, state the class that you want to create an object from, then select the name you want to use to refer to the object. The syntax for declaring object reference variables is: Classname identifier; where: The Classname is the class or type of object referred to with the object reference. The identifier is the name you assigned to the variable of type Classname.

Page 102: Java Fundamentals SG JAH-CJ-200

102 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Instantiating an ObjectInstantiating an Object

• Syntax:

new Classname();

Notes: After you declare the object reference, you can create the object that you refer to. The syntax for instantiating an object is: new Classname(); where: The new keyword creates an object instance from a class. The Classname is the class or type of object being created.

Page 103: Java Fundamentals SG JAH-CJ-200

103 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing Object Reference VariablesInitializing Object Reference Variables

The assignment operator

• Examples:

myShirt = new Shirt();

Notes: The final step in creating an object reference variable is to initialize the object reference variable by assigning the newly created object to the object reference variable. Just as with variable assignment or initialization, you do this with the equal sign (=). The syntax for initializing an object to an object reference variable is: identifier = new Classname(); For example, the ShirtTest class assigns the newly created Shirt object to the myShirt object reference variable. You can say ―The myShirt object reference points to a Shirt object.‖ myShirt = new Shirt(); When you have created a valid object instance, you can use it to manipulate an object’s data or call an object’s methods.

Page 104: Java Fundamentals SG JAH-CJ-200

104 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using an Object Reference Variable to Manipulate DataUsing an Object Reference Variable to Manipulate Data

• Example:

public class ShirtTest2 {

public static void main (String args[]) {

Shirt myShirt;

myShirt = new Shirt();

myShirt.size = „L‟;

myShirt.price = 29.99F;

myShirt.longSleeved = true;

myShirt.displayShirtInformation();

}

}

public class ShirtTest2 {

public static void main (String args[]) {

Shirt myShirt;

myShirt = new Shirt();

myShirt.size = „L‟;

myShirt.price = 29.99F;

myShirt.longSleeved = true;

myShirt.displayShirtInformation();

}

}

public class Shirt {

public int shirtID = 0;

public String description = "-description required-";

public char colorCode = „U‟;

public double price = 0.0;

public int quantityInStock = 0;

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

}

}

public class Shirt {

public int shirtID = 0;

public String description = "-description required-";

public char colorCode = „U‟;

public double price = 0.0;

public int quantityInStock = 0;

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " + quantityInStock);

}

}

1. Declare a reference.

2. Create the object.

3. Assign values.

Notes: You use the dot (.) operator with an object reference to manipulate the values or to invoke the methods of a specific object.

Page 105: Java Fundamentals SG JAH-CJ-200

105 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using an Object Reference Variable to Manipulate DataUsing an Object Reference Variable to Manipulate Data

public class ShirtTestTwo {

public static void main (String args[]) {

Shirt myShirt = new Shirt();

Shirt yourShirt = new Shirt();

myShirt.displayShirtInformation();

yourShirt.displayShirtInformation();

myShirt.colorCode=‟R‟;

yourShirt.colorCode=‟G‟;

myShirt.displayShirtInformation();

yourShirt.displayShirtInformation();

}

}

public class ShirtTestTwo {

public static void main (String args[]) {

Shirt myShirt = new Shirt();

Shirt yourShirt = new Shirt();

myShirt.displayShirtInformation();

yourShirt.displayShirtInformation();

myShirt.colorCode=‟R‟;

yourShirt.colorCode=‟G‟;

myShirt.displayShirtInformation();

yourShirt.displayShirtInformation();

}

}

Notes: In this example, the declaration, instantiation, and initialization for each reference is performed on a single line of code. The declaration is on the left side of the equal sign while the instantiation of the object is on the right side of the equal sign. The equal sign assigns the newly instantiated object to the newly declared object reference. After the object references are created, each object is manipulated independently. Specifically, the object that the myShirt reference points to is given a colorCode value of ―R‖ for red while the object that the yourShirt reference points to is given a colorCode value of ―G‖ for green.

Page 106: Java Fundamentals SG JAH-CJ-200

106 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using an Object Reference Variable to Manipulate DataUsing an Object Reference Variable to Manipulate Data

public class AlarmClock {

public void snooze() {

System.out.println("ZZZZZ");

}

}

public class AlarmClock {

public void snooze() {

System.out.println("ZZZZZ");

}

}

public class AlarmClockTest {

public static void main(String[] args) {

AlarmClock aClock = new AlarmClock();

aClock.snooze();

}

}

public class AlarmClockTest {

public static void main(String[] args) {

AlarmClock aClock = new AlarmClock();

aClock.snooze();

}

}

Notes:

Page 107: Java Fundamentals SG JAH-CJ-200

107 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using an Object Reference Variable to Manipulate DataUsing an Object Reference Variable to Manipulate Data

public class AlarmClock {

public void snooze(long snoozeInterval) {

System.out.println("ZZZZZ for: " + snoozeInterval);

}

}

public class AlarmClock {

public void snooze(long snoozeInterval) {

System.out.println("ZZZZZ for: " + snoozeInterval);

}

}

public class AlarmClockTest {

public static void main(String[] args) {

AlarmClock aClock = new AlarmClock();

//Pass in the snooze interval when you call the method

aClock.snooze(10000); //Snooze for 10000 msecs

}

}

public class AlarmClockTest {

public static void main(String[] args) {

AlarmClock aClock = new AlarmClock();

//Pass in the snooze interval when you call the method

aClock.snooze(10000); //Snooze for 10000 msecs

}

}

Notes:

Page 108: Java Fundamentals SG JAH-CJ-200

108 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using a Object Reference Variable to Manipulate DataUsing a Object Reference Variable to Manipulate Data

public class Circle {

private int radius;

}

public class Circle {

private int radius;

}

public class ShapeTester {

public static void main(String args[]) {

Circle x;

x = new Circle();

System.out.println(x);

}

}

public class ShapeTester {

public static void main(String args[]) {

Circle x;

x = new Circle();

System.out.println(x);

}

}

Notes:

Page 109: Java Fundamentals SG JAH-CJ-200

109 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using an Object Reference Variable to Manipulate DataUsing an Object Reference Variable to Manipulate Data

public class Circle {

private int radius;

}

public class Circle {

private int radius;

}

public class ShapeTester {

public static void main(String args[]) {

Circle x;

Rectangle y;

x = new Circle();

y = new Rectangle();

System.out.println(x + " " + y);

}

}

public class ShapeTester {

public static void main(String args[]) {

Circle x;

Rectangle y;

x = new Circle();

y = new Rectangle();

System.out.println(x + " " + y);

}

}

public class Rectangle {

public double width = 10.128;

public double height = 5.734;

}

public class Rectangle {

public double width = 10.128;

public double height = 5.734;

}

Notes:

Page 110: Java Fundamentals SG JAH-CJ-200

110 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Storing Object Reference Variables in MemoryStoring Object Reference Variables in Memory

public static void main (String args[]) {

int counter;

counter = 10;

Shirt myShirt = new Shirt ( );

}

public static void main (String args[]) {

int counter;

counter = 10;

Shirt myShirt = new Shirt ( );

}

Notes: While primitive variables hold values, object reference variables hold the location (memory address) of objects in memory. Memory addresses are usually written in hexadecimal notation, beginning with a 0x (for example, 0x334009). These addresses are unique for each object and are assigned while a program runs. The figure shows how the primitive variable and object reference variables are stored differently. Local object reference variables and their values are stored in stack memory while the objects that they point to are stored in heap memory. The myShirt and yourShirt object reference variables contain addresses referring to different Shirt objects.

Page 111: Java Fundamentals SG JAH-CJ-200

111 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Assigning an Object Reference From One Variable to AnotherAssigning an Object Reference From One Variable to Another

1 Shirt myShirt = new Shirt();

2 Shirt yourShirt = new Shirt();

3 myShirt = yourShirt;

Notes:

Page 112: Java Fundamentals SG JAH-CJ-200

112 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Assigning an Object Reference From One Variable to AnotherAssigning an Object Reference From One Variable to Another

public class Cat {

} Cat A = new Cat();

Cat B = A;

Notes:

Page 113: Java Fundamentals SG JAH-CJ-200

113 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Assigning an Object Reference From One Variable to AnotherAssigning an Object Reference From One Variable to Another

Notes:

Page 114: Java Fundamentals SG JAH-CJ-200

114 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing thethe StringString ClassClass

• The String type is a class, and not a primitive data type

• A String literal is made up of any number of characters between

double quotes:

• String objects can be initialized in other ways:

Notes: The String class is one of the many classes included in the Java class libraries. The String class provides you with the ability to store a sequence of characters. You will use the String class frequently throughout your programs. Therefore, it is important to understand some of the special characteristics of strings in the Java programming language. There are a number of ways to create and initialize a String object. One way is to use the new keyword to create a String object and, at the same time, define the string with which to initialize that object: String myName = new String(―Fred Smith‖);

Page 115: Java Fundamentals SG JAH-CJ-200

115 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing thethe StringString ClassClass

• The String class is immutable, which means that its value cannot

be changed one an object of String type is created.

• We can use the varius characters in the String class to do the

following:

– Examine the varius characters that make up a string

– Search for a given sub-string within another string

– Compare two strings

– Create another string that has all the characters of the given

string in upper or lower case

• All string values referred by String objects are stored in the

string pool. When we create two String objects and assign tothem a value, for example “hello”, there is only one string with

the value “hello” create in the string pool. Both the String

objects refer to the same value “hello” in the string pool.

Notes:

Page 116: Java Fundamentals SG JAH-CJ-200

116 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

StoringStoring StringString ObjectsObjects in in MemoryMemory

Notes:

Page 117: Java Fundamentals SG JAH-CJ-200

117 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

StoringStoring StringString ObjectsObjects in in MemoryMemory

• A String variable is simply a variable that stores a reference to

an object of the class String

Notes:

Page 118: Java Fundamentals SG JAH-CJ-200

118 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing ReferenceReference Variables Variables forfor StringString ObjectsObjects

public class StringMutation {

public static void main(String[] args) {

String phrase = new String("Change is inevitable");

String mutation1, mutation2, mutation3, mutation4;

System.out.println("Original string: \"" + phrase + "\"");

System.out.println("Length of string: " + phrase.length());

mutation1 = phrase.concat(", except from vending machines.");

mutation2 = mutation1.toUpperCase();

mutation3 = mutation2.replace('E', 'X');

mutation4 = mutation3.substring(3, 30);

// Print each mutated string

System.out.println("Mutation #1: " + mutation1);

System.out.println("Mutation #2: " + mutation2);

System.out.println("Mutation #3: " + mutation3);

System.out.println("Mutation #4: " + mutation4);

System.out.println("Mutated length: " + mutation4.length());

}

}

public class StringMutation {

public static void main(String[] args) {

String phrase = new String("Change is inevitable");

String mutation1, mutation2, mutation3, mutation4;

System.out.println("Original string: \"" + phrase + "\"");

System.out.println("Length of string: " + phrase.length());

mutation1 = phrase.concat(", except from vending machines.");

mutation2 = mutation1.toUpperCase();

mutation3 = mutation2.replace('E', 'X');

mutation4 = mutation3.substring(3, 30);

// Print each mutated string

System.out.println("Mutation #1: " + mutation1);

System.out.println("Mutation #2: " + mutation2);

System.out.println("Mutation #3: " + mutation3);

System.out.println("Mutation #4: " + mutation4);

System.out.println("Mutated length: " + mutation4.length());

}

}

Notes:

Page 119: Java Fundamentals SG JAH-CJ-200

119 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing ReferenceReference Variables Variables forfor StringString ObjectsObjects

public class StringEqual {

public static void main(String[] args) {

String str1 = "Hello Dear!";

String str2 = "Hello Dear!";

String str3 = new String("Hello Dear!");

if (str1.equals(str2)) {

System.out.println("str1 and str2 refer to identical

strings.");

} else {

System.out.println("str1 and str2 refer to non-identical

strings.");

}

if (str1 == str3) {

System.out.println("str1 and str3 refer to the same

string.");

} else {

System.out.println("str1 and str3 refer to different

strings.");

}

}

}

public class StringEqual {

public static void main(String[] args) {

String str1 = "Hello Dear!";

String str2 = "Hello Dear!";

String str3 = new String("Hello Dear!");

if (str1.equals(str2)) {

System.out.println("str1 and str2 refer to identical

strings.");

} else {

System.out.println("str1 and str2 refer to non-identical

strings.");

}

if (str1 == str3) {

System.out.println("str1 and str3 refer to the same

string.");

} else {

System.out.println("str1 and str3 refer to different

strings.");

}

}

}

Notes:

Page 120: Java Fundamentals SG JAH-CJ-200

120 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing ReferenceReference Variables Variables toto ManipulateManipulate DataData

public class JoinStrings {

public static void main(String[] args) {

String firstString = “Many “;

String secondString = “hands “;

String thirdString = “make light work”;

String myString; // Variable to store results

// Join three strings and store the result

myString = firstString + secondString + thirdString;

System.out.println(myString);

// Convert an integer to String and join with two other strings

int numHands = 99;

myString = numHands + “ “ + secondString + thirdString;

System.out.println(myString);

// Combining a string and integers

myString = “fifty five is “ + 5 + 5;

System.out.println(myString);

// Combining integers and a string

myString = 5 + 5 + “ is ten”;

System.out.println(myString);

}

}

public class JoinStrings {

public static void main(String[] args) {

String firstString = “Many “;

String secondString = “hands “;

String thirdString = “make light work”;

String myString; // Variable to store results

// Join three strings and store the result

myString = firstString + secondString + thirdString;

System.out.println(myString);

// Convert an integer to String and join with two other strings

int numHands = 99;

myString = numHands + “ “ + secondString + thirdString;

System.out.println(myString);

// Combining a string and integers

myString = “fifty five is “ + 5 + 5;

System.out.println(myString);

// Combining integers and a string

myString = 5 + 5 + “ is ten”;

System.out.println(myString);

}

}

Notes:

Page 121: Java Fundamentals SG JAH-CJ-200

121 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing ReferenceReference Variables Variables frofro StoringStoring ObjectsObjects

Notes:

Page 122: Java Fundamentals SG JAH-CJ-200

122 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing ReferenceReference Variables Variables forfor StoringStoring ObjectsObjects

Notes: The essential difference between the two is that the first statement always has at least one operand of type String, so the operation is one of string concatenation, whereas in the second statement the first operation is an arithmetic addition because both operands are integers. In the first statement, each of the integers is converted to type String individually. In the second, the numerical values are added, and the result, 10, is converted to a string representation to allow the literal ― is ten‖ to be concatenated.

Page 123: Java Fundamentals SG JAH-CJ-200

123 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

UsingUsing ReferenceReference Variables Variables forfor StoringStoring ObjectsObjects

Notes: The String object itself is distinct from the variable you use to refer to it. In the same way as you saw with array objects, the variable myString stores a reference to a String object, not the object itself, so in other words, a String variable records where the String object is in memory. When you declare and initialize myString, it references the object corresponding to the initializing string literal. When you execute the assignment statement, the original reference is overwritten by the reference to the new string and the old string is discarded. The variable myString then contains a reference to the new string. String objects are said to be immutable—which just means that they cannot be changed. This means that you cannot extend or otherwise modify the string that an object of type String represents. When you execute a statement that combines existing String objects, you are always creating a new String object as a result. When you change the string referenced by a String variable, you throw away the reference to the old string and replace it with a reference to a new one. The distinction between a String variable and the string it references is not apparent most of the time.

Page 124: Java Fundamentals SG JAH-CJ-200

124 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 07 Objects and Strings Lab Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Create instances of a class and manipulate these instances in several ways. Make use of the String class and its methods

Page 125: Java Fundamentals SG JAH-CJ-200

125 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

1. Create a class called BankAccount.

2. Enter the following code:

public class BankAccount {

// these are the instance variables

private int balance;

private int accountNumber;

private String accountName;

// this is the constructor

public BankAccount(int num, String name) {

balance = 0;

accountNumber = num;

accountName = name;

}

Solutions to Labs Exercises:

Page 126: Java Fundamentals SG JAH-CJ-200

126 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

// the code for the methods starts here

public int getBalance() { return balance;}

public void credit(int amount){balance=balance+amount; }

public void debit(int amount) {balance = balance - amount;}

public String toString() {

return ("#######################\n" + "Account number: “

+ accountNumber + "\nAccount name: "

+ accountName

+ "\nBalance: $" + balance

+ "\n#######################");

}

}

Solutions to Lab Exercises:

Page 127: Java Fundamentals SG JAH-CJ-200

127 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

3. Create a BankAccount in another Test program (BankTest). The instance is named savings. For example:

BankAccount savings = new BankAccount(121,"John Doe");

4. Create another BankAccount instance named cheque. For example:

BankAccount cheque = new BankAccount(122,"John Perez");

Solutions to Lab Exercises:

Page 128: Java Fundamentals SG JAH-CJ-200

128 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

5. Call methods of the objects and see what effect they have.

savings.credit(1000);

System.out.println(savings);

cheque.credit(500);

System.out.println(cheque);

cheque.credit(1500);

System.out.println(cheque);

cheque.debit(200);

System.out.println(cheque);

Solutions to Lab Exercises:

Page 129: Java Fundamentals SG JAH-CJ-200

129 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

6. Assign one object reference to another object reference by assigning savings to a new instance named myAccount

BankAccount myAccount;

myAccount = cheque;

System.out.println(myAccount);

7. Make sure that you understand what is happening here!

Solutions to Lab Exercises:

Page 130: Java Fundamentals SG JAH-CJ-200

130 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 08 Using Operators and Decision Constructors Objectives Using Relational and Conditional Operators

o Elevator Example o Relational Operators o Testing Equality Between Strings o Conditional Operators

Creating if and if/else Constructs o The if Construct o Nested if Statements o The if/else Construct o Chaining if/else Constructs

Using the switch Construct o When to Use switch Constructs

Objectives Upon completion of this module, you should be able to: Identify relational and conditional operators Create if and if/else constructs Use the switch construct

Page 131: Java Fundamentals SG JAH-CJ-200

131 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using Relational and Conditional OperatorsUsing Relational and Conditional Operators

Notes: In addition to arithmetic operators, such as plus (+) and increment (++), the Java programming language provides several relational operators including < and > for less than and greater than and && for AND. These operators are used when you want your program to execute different blocks or branches of code depending on different conditions, such as checking if the value of two variables is the same.

Page 132: Java Fundamentals SG JAH-CJ-200

132 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Elevator ExampleElevator Example

public class Elevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

public class Elevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

Notes: An elevator has many functions. The functions of the elevator are: The doors of the elevator can open (the openDoor method) The doors of the elevator can close (the closeDoor method) The elevator can go up one floor (the goUp method) The elevator can go down one floor (the goDown method)

Page 133: Java Fundamentals SG JAH-CJ-200

133 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Elevator ExampleElevator Example

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

Notes:

Page 134: Java Fundamentals SG JAH-CJ-200

134 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Elevator Test ClassElevator Test Class

public class ElevatorTest {

public static void main(String args[]) {

Elevator myElevator = new Elevator();

myElevator.openDoor();

myElevator.closeDoor();

myElevator.goDown();

myElevator.goUp();

myElevator.goUp();

myElevator.goUp();

myElevator.openDoor();

myElevator.closeDoor();

myElevator.goDown();

myElevator.openDoor();

myElevator.closeDoor();

myElevator.goDown();

myElevator.openDoor();

}

}

public class ElevatorTest {

public static void main(String args[]) {

Elevator myElevator = new Elevator();

myElevator.openDoor();

myElevator.closeDoor();

myElevator.goDown();

myElevator.goUp();

myElevator.goUp();

myElevator.goUp();

myElevator.openDoor();

myElevator.closeDoor();

myElevator.goDown();

myElevator.openDoor();

myElevator.closeDoor();

myElevator.goDown();

myElevator.openDoor();

}

}

Notes:

Page 135: Java Fundamentals SG JAH-CJ-200

135 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Relational OperatorsRelational Operators

• Relational operators are used for comparing two values stored ina variable.

Notes: Relational operators compare two values to determine their relationship. The result of all relational operators is a boolean value. Boolean values can be either true or false. For example, all of the examples in the previous table yield a boolean result of true.

Page 136: Java Fundamentals SG JAH-CJ-200

136 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Conditional Operators

• Usually conditional operators are used in combination with

relational operators to determine if a condition is true of false

• These operators require two operators. Hence they are called

binary operators

Notes: For AND operations, true AND true produces true. Any other combination produces false. For OR operations false OR false produces false. Any other combination produces true. As with all operations, the two operands must be of compatible types. So, if either operand is of boolean type, both must be. Java does not permit you to cast any type to Boolean; instead you must use comparisons or methods that return boolean values.

Page 137: Java Fundamentals SG JAH-CJ-200

137 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if ConstructThe if Construct

• An if construct lets you perform certain statements if a

condition is true

• Syntax:

if (boolean_expression) {

code_block;

} // end of if construct

// program continues here

Notes: An if statement, or an if construct, executes a block of code if an expression is true. There are a few variations on the basic if construct. However, the simplest and most common is: if (boolean_expression) { code_block; } // end of if construct // program continues here where: The boolean_expression is a combination of relational operators, conditional

operators, and values resulting in a value of true or false. The code_block represents the lines of code that are executed if expression is true.

First, the boolean_expression is tested. If the expression is true, then the code_block is executed. If boolean_expression is not true, the program skips to the brace marking the end of the if construct code block.

Page 138: Java Fundamentals SG JAH-CJ-200

138 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if ConstructThe if Construct

public class Coffee {

private static int hour=9;

public static void main(String args[]) {

if(hour>=8 && hour<12) {

System.out.println(“Drink coffee”);

}

}

}

public class Coffee {

private static int hour=9;

public static void main(String args[]) {

if(hour>=8 && hour<12) {

System.out.println(“Drink coffee”);

}

}

}

Notes: The example shows the code for deciding whether to drink coffee, bases on wheter it is morning (between 8:00 AM and 12:00 PM, on a military time system).

Page 139: Java Fundamentals SG JAH-CJ-200

139 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if ConstructThe if Construct

public class IfElevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

public class IfElevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

Notes:

Page 140: Java Fundamentals SG JAH-CJ-200

140 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if ConstructThe if Construct

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

if(currentFloor == MIN_FLOORS) {

System.out.println(“Cannot Go down”);

}

if(currentFloor > MIN_FLOORS) {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

}

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

if(currentFloor == MIN_FLOORS) {

System.out.println(“Cannot Go down”);

}

if(currentFloor > MIN_FLOORS) {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

}

Notes:

Page 141: Java Fundamentals SG JAH-CJ-200

141 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if ConstructThe if Construct

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

Notes:

Page 142: Java Fundamentals SG JAH-CJ-200

142 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Nested if StatementsNested if Statements

public class NestedIfElevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

public class NestedIfElevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

Notes:

Page 143: Java Fundamentals SG JAH-CJ-200

143 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Nested if StatementsNested if Statements

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

if (currentFloor == MIN_FLOORS) {

System.out.println(“Cannot Go down”);

}

if (currentFloor > MIN_FLOORS) {

if (!doorOpen) {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

}

}

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

if (currentFloor == MIN_FLOORS) {

System.out.println(“Cannot Go down”);

}

if (currentFloor > MIN_FLOORS) {

if (!doorOpen) {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

}

}

Notes:

Page 144: Java Fundamentals SG JAH-CJ-200

144 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Nested if StatementsNested if Statements

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

Notes:

Page 145: Java Fundamentals SG JAH-CJ-200

145 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if/else ConstructThe if/else Construct

• Syntax:

if (boolean_expression) {

code_block;

} // end of if construct

else {

code_block;

} // end of else construct

// program continues here

Notes: Often, you want one block of code to be executed if the expression is true and another block of code to be executed if the expression is false. You can use an if construct to execute a code block if the expression is true with an else construct that only executes if the expression is false. The syntax for an if/else construct is: if (boolean_expression) { code_block; } // end of if construct else { code_block; } // end of else construct // program continues here

where: The boolean_expression is a combination of relational operators, conditional

operators, and values resulting in a value of true or false. The code_block represents the lines of code that are executed if expression is true.

Page 146: Java Fundamentals SG JAH-CJ-200

146 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if ConstructThe if Construct

public class CoffeeIfElse {

private static int hour=9;

public static void main(String args[]) {

if(hour>=8 && hour<12) {

System.out.println(“Drink coffee”);

}

else {

System.out.println(“Drink tea”);

}

//continue here

}

}

public class CoffeeIfElse {

private static int hour=9;

public static void main(String args[]) {

if(hour>=8 && hour<12) {

System.out.println(“Drink coffee”);

}

else {

System.out.println(“Drink tea”);

}

//continue here

}

}

Notes:

Page 147: Java Fundamentals SG JAH-CJ-200

147 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if/else ConstructThe if/else Construct

public class IfElseElevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

public class IfElseElevator {

public boolean doorOpen=false; // Doors are closed by default

public int currentFloor = 1; // All elevators start on first floor

public final int MAX_FLOORS = 10;

public final int MIN_FLOORS = 1;

public void openDoor() {

System.out.println(“Opening door.”);

doorOpen = true;

System.out.println(“Door is open.”);

}

public void closeDoor() {

System.out.println(“Closing door.”);

doorOpen = false;

System.out.println(“Door is closed.”);

}

Notes:

Page 148: Java Fundamentals SG JAH-CJ-200

148 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if/else ConstructThe if/else Construct

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

if (currentFloor == MIN_FLOORS) {

System.out.println(“Cannot Go down”);

}

else {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

}

public void goUp() {

System.out.println(“Going up one floor.”);

currentFloor++;

System.out.println(“Floor: “ + currentFloor);

}

public void goDown() {

if (currentFloor == MIN_FLOORS) {

System.out.println(“Cannot Go down”);

}

else {

System.out.println(“Going down one floor.”);

currentFloor--;

System.out.println(“Floor: “ + currentFloor);

}

}

Notes:

Page 149: Java Fundamentals SG JAH-CJ-200

149 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The if/else ConstructThe if/else Construct

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

public int getFloor() {

return currentFloor;

}

public boolean checkDoorStatus() {

return doorOpen;

}

}

Notes:

Page 150: Java Fundamentals SG JAH-CJ-200

150 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Chaining if/else ConstructsChaining if/else Constructs

• Syntax:

if (boolean_expression) {

code_block;

} // end of if construct

else if (boolean_expression){

code_block;

} // end of else if construct

else {

code_block;

}

// program continues here

Notes: You can chain if and else constructs together to state multiple outcomes for several different expressions. The syntax for a chained if/else construct is: if (boolean_expression) { code_block; } // end of if construct else if (boolean_expression){ code_block; } // end of else if construct else { code_block; } // program continues here where: The boolean_expression is a combination of relational operators, conditional

operators, and values resulting in a value of true or false. The code_block represents the lines of code that are executed if expression is true.

Page 151: Java Fundamentals SG JAH-CJ-200

151 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Chaining if/else ConstructsChaining if/else Constructs

public class IfElseDemo {

public static void main(String[] args) {

int testscore = 76;

char grade;

if (testscore >= 90) {

grade = 'A';

} else if (testscore >= 80) {

grade = 'B';

} else if (testscore >= 70) {

grade = 'C';

} else if (testscore >= 60) {

grade = 'D';

} else {

grade = 'F';

}

System.out.println("Grade = " + grade);

}

}

public class IfElseDemo {

public static void main(String[] args) {

int testscore = 76;

char grade;

if (testscore >= 90) {

grade = 'A';

} else if (testscore >= 80) {

grade = 'B';

} else if (testscore >= 70) {

grade = 'C';

} else if (testscore >= 60) {

grade = 'D';

} else {

grade = 'F';

}

System.out.println("Grade = " + grade);

}

}

Notes: The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.

Page 152: Java Fundamentals SG JAH-CJ-200

152 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Chaining if/else ConstructsChaining if/else Constructs

public class IfElseDate {

public int month = 10;

public void calculateNumDays() {

if (month == 1 || month == 3 || month == 5 || month == 7 ||

month == 8 || month == 10 || month == 12) {

System.out.println(“There are 31 days in that month.”);

}

else if (month == 2) {

System.out.println(“There are 28 days in that month.”);

}

else if (month == 4 || month == 6 || month == 9 || month == 11) {

System.out.println(“There are 30 days in that month.”);

}

else {

System.out.println(“Invalid month.”);

}

}

}

public class IfElseDate {

public int month = 10;

public void calculateNumDays() {

if (month == 1 || month == 3 || month == 5 || month == 7 ||

month == 8 || month == 10 || month == 12) {

System.out.println(“There are 31 days in that month.”);

}

else if (month == 2) {

System.out.println(“There are 28 days in that month.”);

}

else if (month == 4 || month == 6 || month == 9 || month == 11) {

System.out.println(“There are 30 days in that month.”);

}

else {

System.out.println(“Invalid month.”);

}

}

}

Notes:

Page 153: Java Fundamentals SG JAH-CJ-200

153 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the switch ConstructUsing the switch Construct

• Tests a single variable for several alternative values and

executes the corresponding case

• Any case without break will “fall through”

– Next case will also be executed

• default clause handles values not explicitly handled by a case

Notes: Another keyword used in decision-making is the switch keyword. The switch construct helps you avoid confusing code because it simplifies the organization of the various branches of code that can be executed.

Page 154: Java Fundamentals SG JAH-CJ-200

154 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the switch ConstructUsing the switch Construct

• A switch works with the byte, short, char, and int primitive data

types.

• Syntax:

switch (variable) {

case literal_value:

code_block;

[break;]

case another_literal_value:

code_block;

[break;]

[default:]

code_block;

}

Notes: The syntax for the switch construct is: switch (variable) { case literal_value: code_block; [break;] case another_literal_value: code_block; [break;] [default:] code_block; } where: The switch keyword indicates a switch statement. The variable is the variable of which you want to test the value. The variable can be only of type char, byte, short, or int. The case keyword indicates a value you are testing. The combination of the case

keyword and a literal_value is referred to as a case label. The literal_value is any valid value that a variable might contain. You can have a case label for each value you want to test. Literal values cannot be

variables, expressions, or method calls. Literal values can be constants (final

Page 155: Java Fundamentals SG JAH-CJ-200

155 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

variables like MAX_NUMBER defined somewhere else), literals (like ’A’ or 10), or both

The [break;] statement is an optional keyword that causes the flow of code to immediately exit the switch statement. Without a break statement, all code_blocks following the accepted case statement are executed (until a break statement or the end of the switch construct is reached).

The default keyword indicates a default code_block that is executed if all of the other cases are not met. The default case label is similar to an else construct in an if/else statement. The default case is optional.

Page 156: Java Fundamentals SG JAH-CJ-200

156 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the switch ConstructUsing the switch Construct

public class SwitchDemo {

public static void main(String[] args) {

int month = 8;

switch (month) {

case 1:System.out.println("January");break;

case 2:System.out.println("February");break;

case 3:System.out.println("March");break;

case 4:System.out.println("April");break;

case 5:System.out.println("May");break;

case 6:System.out.println("June");break;

case 7:System.out.println("July");break;

case 8:System.out.println("August");break;

case 9:System.out.println("September");break;

case 10:System.out.println("October");break;

case 11:System.out.println("November");break;

case 12:System.out.println("December");break;

default:System.out.println("Invalid month.");break;

}

}

}

public class SwitchDemo {

public static void main(String[] args) {

int month = 8;

switch (month) {

case 1:System.out.println("January");break;

case 2:System.out.println("February");break;

case 3:System.out.println("March");break;

case 4:System.out.println("April");break;

case 5:System.out.println("May");break;

case 6:System.out.println("June");break;

case 7:System.out.println("July");break;

case 8:System.out.println("August");break;

case 9:System.out.println("September");break;

case 10:System.out.println("October");break;

case 11:System.out.println("November");break;

case 12:System.out.println("December");break;

default:System.out.println("Invalid month.");break;

}

}

}

Notes:

Page 157: Java Fundamentals SG JAH-CJ-200

157 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the switch Construct

System.out.println(“There are 28 days in that month.”);

break;

case 4:

case 6:

case 9:

case 11:

System.out.println(“There are 30 days in that month.”);

break;

default:

System.out.println(“Invalid month.”);

break;

}

}

}

System.out.println(“There are 28 days in that month.”);

break;

case 4:

case 6:

case 9:

case 11:

System.out.println(“There are 30 days in that month.”);

break;

default:

System.out.println(“Invalid month.”);

break;

}

}

}

Notes:

Page 158: Java Fundamentals SG JAH-CJ-200

158 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the switch ConstructUsing the switch Construct

public class SwitchDemo2 {

public static void main(String[] args) {

int month = 2;int year = 2000;int numDays = 0;

switch (month) {

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12: numDays = 31;break;

case 4:

case 6:

case 9:

case 11:numDays = 30;break;

case 2: if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))

numDays = 29;

else numDays = 28; break;

default: System.out.println("Invalid month."); break;

}

System.out.println("Number of Days = " + numDays);

}

}

public class SwitchDemo2 {

public static void main(String[] args) {

int month = 2;int year = 2000;int numDays = 0;

switch (month) {

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12: numDays = 31;break;

case 4:

case 6:

case 9:

case 11:numDays = 30;break;

case 2: if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))

numDays = 29;

else numDays = 28; break;

default: System.out.println("Invalid month."); break;

}

System.out.println("Number of Days = " + numDays);

}

}

Notes:

Page 159: Java Fundamentals SG JAH-CJ-200

159 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

When to Use switch ConstructsWhen to Use switch Constructs

• Equality tests

• Tests against a single variable, such as customerStatus

• Tests against the value of an int, short, byte, or char

• type

Notes: The switch construct is only for testing equality, not for testing whether values are greater or less than a single value. You cannot use the switch construct to test against more than one value, and you can only use it with integral data types. The switch construct can be considered for: Equality tests Tests against a single variable, such as customerStatus Tests against the value of an int, short, byte, or char type

Page 160: Java Fundamentals SG JAH-CJ-200

160 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 09 Control Structures Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Create classes that use if and if/else constructs. Using the switch construct in decision-making programs

Page 161: Java Fundamentals SG JAH-CJ-200

161 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

1. Create a class called DayOfWeek with one variable that can

only contain a value from 1 to 7. Where:

– The number 1 represents Monday (beginning of the week).

– The number 7 represents Sunday (end of the week).

2. In the DayOfWeek class, create a displayDay method that uses if/else constructs to inspect the value of the number of days

and displays the corresponding day of the week. The

displayDay method should also display an error message if an

invalid number is used.

Solutions to Lab Exercises:

Page 162: Java Fundamentals SG JAH-CJ-200

162 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab ExercisesLab Exercises

1. Create a class called DayOfWeek02 with one variable

containing a value from 1 to 7, where:

– The number 1 represents Monday (beginning of the week).

– The number 7 represents Sunday (end of the week).

2. In the DayOfWeek02 class, create a displayDay method that uses a switch construct to inspect the value for the number of

days and displays the corresponding day of the week. The

displayDay method should also display an error message if an

invalid number is used.

Solution to Lab Exercises:

Page 163: Java Fundamentals SG JAH-CJ-200

163 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Page 164: Java Fundamentals SG JAH-CJ-200

164 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Page 165: Java Fundamentals SG JAH-CJ-200

165 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 10

Using loop constructs Objectives Creating while loops

o Nested while loops Developing a for loop

o Nested for Loops Coding a do/while Loop

o Nested do/while Loops o Comparing Loop Constructs

Objectives Upon completion of this module, you should be able to: Create while loops Develop for loops Create do/while loops

Page 166: Java Fundamentals SG JAH-CJ-200

166 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating while LoopsCreating while Loops

• The while loop is used to perform a set of operations

repeateadly till some condition is satisfied, or to perform a set

of operations infinitely

• Syntax:

while(boolean_expression) {

code_block;

} // end of while construct

// program continues here

Notes: A while loop iterates through a code block while an expression yields a value of true. The syntax for a while loop is: while (boolean_expression) { code_block; } // end of while construct // program continues here All loops have the following components:

The boolean_expression is an expression that evaluates to true or false. This expression is processed before each iteration of the loop.

The code_block represents lines of code that are executed if the boolean_expression is true.

The while loop is a zero-to-many iterative loop, the boolean_expression part of the loop is processed before the body of the loop, and, if it is immediately false, then the body will not be processed at all.

Page 167: Java Fundamentals SG JAH-CJ-200

167 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating while LoopsCreating while Loops

public class WhileCountDown {

public static void main(String args[]) {

int count = 10;

while(count>=0) {

System.out.println(count);

count--;

}

System.out.println(“Blast Off.”);

}

}

public class WhileCountDown {

public static void main(String args[]) {

int count = 10;

while(count>=0) {

System.out.println(count);

count--;

}

System.out.println(“Blast Off.”);

}

}

Notes: The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

Page 168: Java Fundamentals SG JAH-CJ-200

168 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating while LoopsCreating while Loops

public class WhileElevator {

//instance variables

public void openDoor() {…}

public void closeDoor() {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

while (currentFloor != desiredFloor)

if (currentFloor < desiredFloor) {

goUp();

} else {

goDown();

}

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

public class WhileElevator {

//instance variables

public void openDoor() {…}

public void closeDoor() {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

while (currentFloor != desiredFloor)

if (currentFloor < desiredFloor) {

goUp();

} else {

goDown();

}

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

Notes: The following code example shows a setFloor method that contains a while loop that helps to move an elevator up or down.

Page 169: Java Fundamentals SG JAH-CJ-200

169 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Nested while LoopsNested while Loops

• Example potential solution:public class WhileRectangle {

public int height = 3;

public int width = 10;

public void displayRectangle() {

int colCount = 0;

int rowCount = 0;

while (rowCount < height) {

colCount=0;

while (colCount < width) {

System.out.print(“@”);

colCount++;

}

System.out.println();

rowCount++;

}

}

}

public class WhileRectangle {

public int height = 3;

public int width = 10;

public void displayRectangle() {

int colCount = 0;

int rowCount = 0;

while (rowCount < height) {

colCount=0;

while (colCount < width) {

System.out.print(“@”);

colCount++;

}

System.out.println();

rowCount++;

}

}

}

Notes: The code prints a rectangle of @ symbols, ten columns wide by three row long (three rows composed of 10 @ symbols each). Printing each row is done by the inner loop; the outer loop prints that code three times.

Page 170: Java Fundamentals SG JAH-CJ-200

170 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Developing a for LoopDeveloping a for Loop

• The for loop is used to perform a set of operations repeatdly

until some condition is satisfied, or to perform a set of

operations infinitely

• Syntax:

for (initialize[,initialize]; boolean_expression;

update[,update]) {

code_block;

}

Notes: The for loop allows your program to loop through a sequence of statements for a predetermined number of times. The for loop operates in exactly the same way as the while loop, including the fact that it is a zero-to-many loop, but it has a more centralized structure for counting through a range of values. The syntax for the for loop is: for (initialize[,initialize]; boolean_expression; update[,update]) { code_block; } where:

The initialize[,initialize] portion of the for construct contains statements that initialize variables (such as loop counters) used throughout the loop. This section of code is processed once, before any other part of the loop. Separate multiple variables with commas.

The boolean_expression is an expression that evaluates to true or false. This expression is processed before each iteration of the loop.

The update[,update] section is where variables (loop counters) are updated (incremented or decremented). This section is processed after the body but before each subsequent re-test of the boolean_expression. Separate multiple variables with commas.

The code_block represents lines of code that are executed if the boolean_expression is true.

Page 171: Java Fundamentals SG JAH-CJ-200

171 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Developing a for LoopDeveloping a for Loop

public class ForLoop {

public static void main(String[] args) {

int limit = 20; // Sum from 1 to this value

int sum = 0; // Accumulate sum in this variable

// Loop from 1 to the value of limit, adding 1 each cycle

for(int i = 1; i <= limit; i++) {

sum += i; // Add the current value of i to sum

}

System.out.println(“sum = “ + sum);

}

}

public class ForLoop {

public static void main(String[] args) {

int limit = 20; // Sum from 1 to this value

int sum = 0; // Accumulate sum in this variable

// Loop from 1 to the value of limit, adding 1 each cycle

for(int i = 1; i <= limit; i++) {

sum += i; // Add the current value of i to sum

}

System.out.println(“sum = “ + sum);

}

}

Notes:

Page 172: Java Fundamentals SG JAH-CJ-200

172 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Developing a for LoopDeveloping a for Loop

• Example:

Notes:

Page 173: Java Fundamentals SG JAH-CJ-200

173 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Developing a for LoopDeveloping a for Loop

public class ForElevator {

//instance variables

public void openDoor() {…}

public void closeDoor() {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

if (currentFloor > desiredFloor) {

for (int down = currentFloor; down != desiredFloor; --down) {

goDown();

}

} else {

for (int up = currentFloor; up != desiredFloor; ++up) {

goUp();

}

}

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

public class ForElevator {

//instance variables

public void openDoor() {…}

public void closeDoor() {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

if (currentFloor > desiredFloor) {

for (int down = currentFloor; down != desiredFloor; --down) {

goDown();

}

} else {

for (int up = currentFloor; up != desiredFloor; ++up) {

goUp();

}

}

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

Notes: The following code example shows a setFloor method that contains a for loop.

Page 174: Java Fundamentals SG JAH-CJ-200

174 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Nested for LoopsNested for Loops

public class ForRectangle {

public int height = 3;

public int width = 10;

public void displayRectangle() {

for (int rowCount = 0; rowCount < height; rowCount++) {

for (int colCount = 0; colCount < width; colCount++) {

System.out.print(“@”);

}

System.out.println();

}

}

}

public class ForRectangle {

public int height = 3;

public int width = 10;

public void displayRectangle() {

for (int rowCount = 0; rowCount < height; rowCount++) {

for (int colCount = 0; colCount < width; colCount++) {

System.out.print(“@”);

}

System.out.println();

}

}

}

Notes:

Page 175: Java Fundamentals SG JAH-CJ-200

175 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Coding a do/while LoopCoding a do/while Loop

• The do-while loop is used to perform a set of operations

repeatedly until some condition is satisfied, or to perform a set

of operations infinitely

• Syntax:

do {

code_block;

}

while(boolean_expression);// Semicolon is

// mandatory.

Notes: The do/while loop is a one-to-many iterative loop: The condition is at the bottom of the loop and is processed after the body. The body of the loop is therefore processed at least once. If you want the statement or statements in the body to be processed at least once, use a do/while loop instead of a while or for loop. The syntax for the do/while loop is as follows: do { code_block; } while (boolean_expression);// Semicolon is mandatory. where:

The code_block represents lines of code that are executed more than once if the boolean_expression is true.

The boolean_expression is an expression that evaluates to true or false. The boolean_expression is processed after each iteration of the loop.

The semicolon after the boolean_expression is mandatory because the boolean_expression is at the end of the loop. Conversely, a semicolon is not needed at the end of a while loop because the boolean_expression is at the beginning of the loop leading into the code_block terminated by a right curly brace.

Page 176: Java Fundamentals SG JAH-CJ-200

176 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Coding a do/while LoopCoding a do/while Loop

public class DoWhileElevator {

//instance variables

public void openDoor() {…}

public void closeDoor {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

do {

if (currentFloor < desiredFloor) {

goUp();

}

if (currentFloor > desiredFloor) {

goDown();

}

}

while (currentFloor != desiredFloor);

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

public class DoWhileElevator {

//instance variables

public void openDoor() {…}

public void closeDoor {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

do {

if (currentFloor < desiredFloor) {

goUp();

}

if (currentFloor > desiredFloor) {

goDown();

}

}

while (currentFloor != desiredFloor);

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

Notes: The code example shows a setFloor method that contains a while loop that helps to move an elevator up or down.

Page 177: Java Fundamentals SG JAH-CJ-200

177 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Page 178: Java Fundamentals SG JAH-CJ-200

178 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Nested do/while Loops

public class DoWhileRectangle {

public int height = 3;

public int width = 10;

public void displayRectangle() {

int rowCount = 0;

int colCount = 0;

do {

colCount = 0;

do {

System.out.print(“@”);

colCount++;

}while (colCount < width);

System.out.println();

rowCount++;

}while (rowCount < height);

}

}

public class DoWhileRectangle {

public int height = 3;

public int width = 10;

public void displayRectangle() {

int rowCount = 0;

int colCount = 0;

do {

colCount = 0;

do {

System.out.print(“@”);

colCount++;

}while (colCount < width);

System.out.println();

rowCount++;

}while (rowCount < height);

}

}

Notes:

Page 179: Java Fundamentals SG JAH-CJ-200

179 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Comparing Loop Constructs

• Use the while loop to iterate indefinitely through statements

and to perform the statements zero or more times.

• Use the do/while loop to iterate indefinitely through statements

and to perform the statements one or more times.

• Use the for loop to step through statements a predefined number

of times.

Notes:

Page 180: Java Fundamentals SG JAH-CJ-200

180 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Comparing Loop Constructs

Notes:

Page 181: Java Fundamentals SG JAH-CJ-200

181 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 11 Loop Constructs Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Write classes that use while loops. Write classes that use for loops. Write classes that use do/while loops.

Page 182: Java Fundamentals SG JAH-CJ-200

182 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises 1Lab Exercises 1

1. Write a class called Counter that contains a method called

displayCount that:

– Counts from 1 to MAX_COUNT, where MAX_COUNT is a

variable that you must declare and initilize to any number by

using a while loop

– Displays the count

2. Compile your program.

3. Use the CounterTest.class file to test your program.

Solution to Lab Exercises:

Page 183: Java Fundamentals SG JAH-CJ-200

183 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Two.Lab Exercises. Two.

1. Write a class called CounterTwo that contains a method called

displayCount that:

– Counts from 1 to the value of the MAX_COUNT constant,

where the MAX_COUNT constant is a variable that you must

declare and initilize to any number, using a for loop.

– Displays the count

2. Compile your program.

3. Use the CounterTwoTest.class file to test your program.

Solution to Lab Exercises:

Page 184: Java Fundamentals SG JAH-CJ-200

184 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Lab Exercises. Three.Three.

1. Write a class called CounterThree containing a method called

displayCount that:

– Counts from 1 to the value of the MAX_COUNT constant,

where the MAX_COUNT constant is a variable that you must

declare and initilize to any number, using a do/while loop

– Displays the count

2. Compile your program.

3. Use the CounterThreeTest.class file to test your program.

Solution to Lab Exercises:

Page 185: Java Fundamentals SG JAH-CJ-200

185 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 12 Developing and Using Methods Objectives Creating and Invoking Methods

o Basic Form of a Method o Invoking a Method from Different Class o Invoking a Method in the Same Class o Guidelines for Invoking Methods

Passing Arguments and Returning Values o Declaring Methods With Arguments o Invoking Methods With Return Values o Returning a Value o Advantages of Method Use

Creating static Methods and Variables o Static Methods and Variables in the Java API o When to Declare a static Method or Variable

Using Method Overloading o Method Overloading and the Java API o Uses for Method Overloading

Objectives Upon completion of this module, you should be able to: Describe the advantages of methods and define worker and calling methods Declare and invoke a method Compare object and static methods Use overloaded methods

Page 186: Java Fundamentals SG JAH-CJ-200

186 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

• Objects are self-contained entities that are made up of both

data and functions that operate on the data

– An object often models the real world

• Data is encapsulated by objects

– Encapsulation means enclosing, hiding, or containing

– Implementation details of functions are also encapsulated

Notes:

Page 187: Java Fundamentals SG JAH-CJ-200

187 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

• Here is a person, Jim

• Jim has a quantity of money

• How can you determine how much money Jim has?

• Recall that:

– Data is represented inside the inner circle

– Functions accessing that data surround the data in the outer circle

Notes:

Page 188: Java Fundamentals SG JAH-CJ-200

188 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

• Objects communicate by sending messages

– getMoneyTotal and getName are examples of messages that

can be sent to the person object, Jim

• Sending messages is the only way that objects can communicate

Notes:

Page 189: Java Fundamentals SG JAH-CJ-200

189 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

colour = anUmbrella.getColour();

anUmbrella.setColour("blue");

homer.eat(donuts);

Notes:

Page 190: Java Fundamentals SG JAH-CJ-200

190 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

• Sending a message is a different concept than calling a function

– Calling a function indicates that you have identified the actual

implementation code that you want to run at the time of the

function call

– Sending a message is just a request for a service from an object;

the object determines what to do

– Different objects may interpret the same message differently

Notes:

Page 191: Java Fundamentals SG JAH-CJ-200

191 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

• Message

– A message is a request for a service.

• Method

– A method is the implementation of the service requested by

the message

– In procedural languages, these are known as procedures or

functions

• A message is typically sent from one object to another; it does

not imply what actual code will be executed

• A method is the code that will be executed in response to a

message that is sent to an object

Notes:

Page 192: Java Fundamentals SG JAH-CJ-200

192 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

IntroductionIntroduction

public double getMoneyTotal() {

double totalMoney = 0.0;

totalMoney = totalMoney +

(.25*quarters);

totalMoney = totalMoney + (.10*dimes);

totalMoney = totalMoney + (.05*nickels);

totalMoney = totalMoney + (.01*pennies);

return totalMoney;

}

Notes:

Page 193: Java Fundamentals SG JAH-CJ-200

193 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating and Invoking MethodsCreating and Invoking Methods

• Methods define how an object responds to messages

• Methods define the behavior of the class

• Syntax:

[modifiers] return_type method_identifier ([arguments])

{

method_code_block

}

Notes: Most of the code you write for a class is contained within one or more methods. Methods let you divide the work that your program does into separate logical tasks or behaviors. The syntax of all method declarations is as follows: [modifiers] return_type method_identifier ([arguments]) { method_code_block } where:

The [modifiers] represent several Java keywords that modify the way methods are used. Modifiers are optional (as indicated by the square brackets).

The return_type is the type of value returned from a method that can be used elsewhere in the program. Methods can return only one item (literal value, variable, object reference, and so on). If nothing is to be returned, the keyword void must be specified as the return type.

The method_identifier is the name of the method.

The ([arguments]) represent a list of variables whose values are passed to the method for use by the method. Arguments are optional (indicated by the square brackets); many methods do not accept arguments.

The method_code_block is a sequence of statements that the method performs. A wide variety of tasks can take place in the code block or body of a method.

Page 194: Java Fundamentals SG JAH-CJ-200

194 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Basic Form of a MethodBasic Form of a Method

public void displayShirtInformation( ) {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: "

+ quantityInStock);

} // end of display method

public void displayShirtInformation( ) {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: "

+ quantityInStock);

} // end of display method

modifier keyword return type method name method arguments

Notes: The basic form of a method accepts no arguments and returns nothing. The display method from the Shirt class is a basic method.

Page 195: Java Fundamentals SG JAH-CJ-200

195 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking a Method From a Different ClassInvoking a Method From a Different Class

public class ShirtTest {

public static void main (String args[]) {

Shirt myShirt;

myShirt = new Shirt();

myShirt.displayShirtInformation();

}

}

public class ShirtTest {

public static void main (String args[]) {

Shirt myShirt;

myShirt = new Shirt();

myShirt.displayShirtInformation();

}

}

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " +

quantityInStock);

} // end of display method

public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID);

System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);

System.out.println("Shirt price: " + price);

System.out.println("Quantity in stock: " +

quantityInStock);

} // end of display method

Notes: To invoke, or execute, a method in a different class, you can use the dot (.) operator with an object reference variable just as you do to access the public variables of an object. In this example, an object reference variable called myShirt is declared and initialized to a Shirt object. The myShirt object reference variable then invokes the display method within the Shirt object.

Page 196: Java Fundamentals SG JAH-CJ-200

196 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking a Method From a Different ClassInvoking a Method From a Different Class

• Example:public class CountFlips {

public static void main (String[] args) {

final int NUM_FLIPS = 1000;

int heads = 0, tails = 0;

Coin myCoin = new Coin(); // instantiate the Coin object

for (int count=1; count <= NUM_FLIPS; count++) {

myCoin.flip();

if (myCoin.isHeads())

heads++;

else

tails++;

}

System.out.println ("The number flips: " + NUM_FLIPS);

System.out.println ("The number of heads: " + heads);

System.out.println ("The number of tails: " + tails);

}

}

public class CountFlips {

public static void main (String[] args) {

final int NUM_FLIPS = 1000;

int heads = 0, tails = 0;

Coin myCoin = new Coin(); // instantiate the Coin object

for (int count=1; count <= NUM_FLIPS; count++) {

myCoin.flip();

if (myCoin.isHeads())

heads++;

else

tails++;

}

System.out.println ("The number flips: " + NUM_FLIPS);

System.out.println ("The number of heads: " + heads);

System.out.println ("The number of tails: " + tails);

}

}

Notes:

Page 197: Java Fundamentals SG JAH-CJ-200

197 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking a Method From a Different ClassInvoking a Method From a Different Class

• Example:import java.util.Random;

public class Coin {

private final int HEADS = 0;

private final int TAILS = 1;

private int face;

public Coin () {

flip();

}

public void flip () {

face = (int) (Math.random() * 2);

}

public boolean isHeads () {

return (face == HEADS);

}

}

import java.util.Random;

public class Coin {

private final int HEADS = 0;

private final int TAILS = 1;

private int face;

public Coin () {

flip();

}

public void flip () {

face = (int) (Math.random() * 2);

}

public boolean isHeads () {

return (face == HEADS);

}

}

Notes:

Page 198: Java Fundamentals SG JAH-CJ-200

198 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Calling and Worker MethodsCalling and Worker Methods

Notes:

A calling method tells an object to do something for you, with one of its methods. Calling methods often contain normal method processes, in addition to calling the worker method.

The object contains worker methods to do work for you. Might take input information, might return one piece of information.

Page 199: Java Fundamentals SG JAH-CJ-200

199 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Calling and Worker MethodsCalling and Worker Methods

public class One {

public static void main(String args[]) {

Two twoRef = new Two();

twoRef.workerMethod();

}

}

public class One {

public static void main(String args[]) {

Two twoRef = new Two();

twoRef.workerMethod();

}

}

public class Two {

public void workerMethod() {

int i = 42;

int j = 24;

}

}

public class Two {

public void workerMethod() {

int i = 42;

int j = 24;

}

}

Calling

method

Worker

method

Notes: You need to write code within a calling method that tells an object to so something for you, with one of its methods. You need a class that has some methods that complete tasks you want done. This is the worker method. This method might or might not require additional information when its run. It also might return one piece of information to the calling method.

Page 200: Java Fundamentals SG JAH-CJ-200

200 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Calling and Worker MethodsCalling and Worker Methods

public class CallingClass {

public static void main(String args[]) {

WorkerClass workerObject = new WorkerClass();

workerObject.worker1();

workerObject.worker2();

}

}

public class CallingClass {

public static void main(String args[]) {

WorkerClass workerObject = new WorkerClass();

workerObject.worker1();

workerObject.worker2();

}

}

public class WorkerClass {

public void worker1() {

int id = 44559;

System.out.println(“The id is ” + id);

}

public void worker2() {

float price = 29.99f;

System.out.println(“The price is ” + price);

}

}

public class WorkerClass {

public void worker1() {

int id = 44559;

System.out.println(“The id is ” + id);

}

public void worker2() {

float price = 29.99f;

System.out.println(“The price is ” + price);

}

}

Notes: The example shows a very basic program, to highlight the separation of the worker and calling methods. These calling method just call two methods in WorkerClass; those two methods print the values of variables set in their methods.

Page 201: Java Fundamentals SG JAH-CJ-200

201 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking a Method in the Same ClassInvoking a Method in the Same Class

• Calling a method in the same class is quite simple; write the

calling method declaration code and include the name of the

worker method and its arguments, if any.

public class DisclaimerOneFile {

public void callMethod() {

//calls the printDisclaimer method

printDisclaimer();

}

public void printDisclaimer() {

System.out.println(“Hello Culiacan”);

}

}

public class DisclaimerOneFile {

public void callMethod() {

//calls the printDisclaimer method

printDisclaimer();

}

public void printDisclaimer() {

System.out.println(“Hello Culiacan”);

}

}

Notes:

Page 202: Java Fundamentals SG JAH-CJ-200

202 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking a Method in the Same ClassInvoking a Method in the Same Class

public class Elevator {

//instance variables

public void openDoor() {…}

public void closeDoor() {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

while (currentFloor != desiredFloor)

if (currentFloor < desiredFloor) {

goUp();

}

else {

goDown();

}

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

public class Elevator {

//instance variables

public void openDoor() {…}

public void closeDoor() {…}

public void goUp() {…}

public void goDown() {…}

public void setFloor(int desiredFloor) {

while (currentFloor != desiredFloor)

if (currentFloor < desiredFloor) {

goUp();

}

else {

goDown();

}

}

public int getFloor() {…}

public boolean checkDoorStatus() {…}

}

Notes:

Page 203: Java Fundamentals SG JAH-CJ-200

203 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Guidelines for Invoking MethodsGuidelines for Invoking Methods

• There is no limit to the number of method calls that a calling

method can make.

• The calling method and the worker method can be in the same

class or in different classes.

• The way you invoke the worker method is different,

depending on whether it is in the same class or in a different

class from the calling method.

• You can invoke methods in any order. Methods do not need to

be completed in the order in which they are listed in the class

where they are declared (the class containing the worker

methods).

Notes:

Page 204: Java Fundamentals SG JAH-CJ-200

204 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Passing Arguments and Returning ValuesPassing Arguments and Returning Values

Notes: Methods can be invoked by a calling method with a list of arguments (variables or values to be used by the worker method). Additionally, methods can return a value to the calling method that can be used in the calling method.

Page 205: Java Fundamentals SG JAH-CJ-200

205 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Passing Arguments and Returning ValuesPassing Arguments and Returning Values

Notes:

Page 206: Java Fundamentals SG JAH-CJ-200

206 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring Methods With ArgumentsDeclaring Methods With Arguments

• Example:public void setFloor(int desiredFloor) {

while (currentFloor != desiredFloor) {

if (currentFloor < desiredFloor) {

goUp();

}

else {

goDown();

}

}

}

• Example:public void multiply(int NumberOne, int NumberTwo)

Notes: To write a method declaration that accepts one or more arguments, list one or more type and variable pairs within the parentheses of the method declaration.

Page 207: Java Fundamentals SG JAH-CJ-200

207 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking Methods With ArgumentsInvoking Methods With Arguments

public class GetInfo2 {

public static void main(String args[]) {

//makes a Shirt object

Shirt2 theShirt = new Shirt2();

//calls the printInfo method

theShirt.printInfo(44339,‟L‟);

}

public class GetInfo2 {

public static void main(String args[]) {

//makes a Shirt object

Shirt2 theShirt = new Shirt2();

//calls the printInfo method

theShirt.printInfo(44339,‟L‟);

}

public class Shirt2 {

int id;

char size;

public void printInfo(int shirtId, char shirtSize) {

id = shirtId; //assign arguments to variables

size = shirtSize;

System.out.println(id);

System.out.println(size);

}

}

public class Shirt2 {

int id;

char size;

public void printInfo(int shirtId, char shirtSize) {

id = shirtId; //assign arguments to variables

size = shirtSize;

System.out.println(id);

System.out.println(size);

}

}

Notes:

Page 208: Java Fundamentals SG JAH-CJ-200

208 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Invoking Methods With ArgumentsInvoking Methods With Arguments

public class Arguments {

public void passArguments() {

subtract( 3.14159f, 9f );

}

public void subtract( float first , float second ) {

if((first-second)>=0) {

System.out.println(“Positive”);

}

else {

System.out.println(“Negative”);

}

}

}

public class Arguments {

public void passArguments() {

subtract( 3.14159f, 9f );

}

public void subtract( float first , float second ) {

if((first-second)>=0) {

System.out.println(“Positive”);

}

else {

System.out.println(“Negative”);

}

}

}

Notes:

Page 209: Java Fundamentals SG JAH-CJ-200

209 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring Methods With Return ValuesDeclaring Methods With Return Values

• Declaration:

public int sum(int numberOne, int numberTwo)

Notes: Most of the method declarations that you have seen do not have a return value (void). However, many of the methods you will create will have return values and many methods in the Java class libraries also have return values. To declare a method that returns a value, place the type of the value you want the method to return in front of the method identifier.

Page 210: Java Fundamentals SG JAH-CJ-200

210 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Returning a ValueReturning a Value

• Example:

public int sum(int numberOne, int numberTwo) {

int sum = numberOne + numberTwo;

return sum;

}

• Example:

public int getFloor() {

return currentFloor;

}

Notes:

Page 211: Java Fundamentals SG JAH-CJ-200

211 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Receiving Return ValuesReceiving Return Values

Notes:

Page 212: Java Fundamentals SG JAH-CJ-200

212 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Receiving Return ValuesReceiving Return Values

public class ReceiveValues {

public static void main(String args[]) {

AddsValues adder = new AddsValues();

int sum = adder.returnSum();

}

}

public class ReceiveValues {

public static void main(String args[]) {

AddsValues adder = new AddsValues();

int sum = adder.returnSum();

}

}

public class AddsValues {

public int returnSum() {

int x = 4;

int y = 17;

return(x + y);

}

}

public class AddsValues {

public int returnSum() {

int x = 4;

int y = 17;

return(x + y);

}

}

Notes:

Page 213: Java Fundamentals SG JAH-CJ-200

213 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Advantages of Method UseAdvantages of Method Use

• Methods make programs more readable and easier to maintain.

• Methods make development and maintenance quicker.

• Methods are central to reusable software.

• Methods allow separate objects to communicate and to

distribute the work performed by the program.

• Remember:

Notes:

Page 214: Java Fundamentals SG JAH-CJ-200

214 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating static Methods and VariablesCreating static Methods and Variables

• Variables having the same value for all instances of a class are

called class variables

• Class variables are also sometimes referred to as static variables

public class Student {

//class variables

static int maxIdAssigned;

//instance variable

private int id;

//constructor

public Student() {

this.id = maxIdAssigned;

maxIdAssigned++;

}

}

public class Student {

//class variables

static int maxIdAssigned;

//instance variable

private int id;

//constructor

public Student() {

this.id = maxIdAssigned;

maxIdAssigned++;

}

}

Notes: Local variables are declared inside a method and instance variables are declared in a class but not inside a method. An instance variable is accessed through a particular instance (an object) of a class. In general, each object has distinct memory space for each variable so that each object can have a distinct value for that variable. A static variable or class variable, is shared among all instances of a class. There is only one copy of a static variable for all objects of a class. Therefore, changing the value of a static variable in one object changes it for all of the others.

Page 215: Java Fundamentals SG JAH-CJ-200

215 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating static Methods and VariablesCreating static Methods and Variables

• Certain methods defined in a class can operate only on class

variables

• We can invoke these methods directly using the class name

without creating an instance

• Such methods are known as class methods, or static methods

• The main method of a Java program must be declared with the

static modifier; this is so main can be executed by the

interpreter without instantiating an object from the class that

contains main.

Notes:

Page 216: Java Fundamentals SG JAH-CJ-200

216 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating static Methods and VariablesCreating static Methods and Variables

• Example:public class CountInstances {

public static void main (String[] args) {

Slogan obj;

obj = new Slogan ("Remember the Alamo.");

System.out.println (obj);

obj = new Slogan ("Don't Worry. Be Happy.");

System.out.println (obj);

obj = new Slogan ("Live Free or Die.");

System.out.println (obj);

obj = new Slogan ("Talk is Cheap.");

System.out.println (obj);

obj = new Slogan ("Write Once, Run Anywhere.");

System.out.println (obj);

System.out.println();

System.out.println ("Slogans created: " + Slogan.getCount());

}

}

public class CountInstances {

public static void main (String[] args) {

Slogan obj;

obj = new Slogan ("Remember the Alamo.");

System.out.println (obj);

obj = new Slogan ("Don't Worry. Be Happy.");

System.out.println (obj);

obj = new Slogan ("Live Free or Die.");

System.out.println (obj);

obj = new Slogan ("Talk is Cheap.");

System.out.println (obj);

obj = new Slogan ("Write Once, Run Anywhere.");

System.out.println (obj);

System.out.println();

System.out.println ("Slogans created: " + Slogan.getCount());

}

}

Notes:

Page 217: Java Fundamentals SG JAH-CJ-200

217 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating static Methods and VariablesCreating static Methods and Variables

• Example:public class Slogan {

private String phrase;

private static int count = 0;

public Slogan (String str) {

phrase = str;

count++;

}

public String toString() {

return phrase;

}

public static int getCount () {

return count;

}

}

public class Slogan {

private String phrase;

private static int count = 0;

public Slogan (String str) {

phrase = str;

count++;

}

public String toString() {

return phrase;

}

public static int getCount () {

return count;

}

}

Notes:

Page 218: Java Fundamentals SG JAH-CJ-200

218 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating static Methods and VariablesCreating static Methods and Variables

Notes: Static fields, also called class variables—A given class will have only one copy of each of its static fields or class variables, and these will be shared between and among all the objects of the class. Each class variable exists even if no objects of the class have been created. Class variables belong to the class, and they can be referenced by any object or class method, not just methods belonging to instances of that class. If the value of a static field is changed, the new value is available equally in all the objects of the class. This is quite different from non-static fields, where changing a value for one object does not affect the values in other objects. A static field must be declared using the keyword static preceding the type name.

Page 219: Java Fundamentals SG JAH-CJ-200

219 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Static Methods and Variables in the Java APIStatic Methods and Variables in the Java API

• Examples:

• The Math class

• The System class

Notes: Certain Java class libraries, such as the System class, contain only static methods and variables. The System class contains utility methods for handling operating system-specific tasks (they do not operate on an object instance). For example, the getProperties method of the System class gets information about the computer you are using. There are several classes in the Java API that are utility classes. These classes contain static methods that are useful for objects of all types. Examples of utility classes and methods are:

The Math class. This class contains methods and variables for performing basic numeric operations, such as the elementary exponential, logarithm, square root, and trigonometric functions.

The System class. This class contains methods and variables for performing system-level functions, such as retrieving environment variable information from your operating system.

Page 220: Java Fundamentals SG JAH-CJ-200

220 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Static Methods and Variables in the Java APIStatic Methods and Variables in the Java API

• Examples:

public class Get {

public static void main (String[] args) {

StaticExample ex = new StaticExample();

ex.getNumber();

}

public class Get {

public static void main (String[] args) {

StaticExample ex = new StaticExample();

ex.getNumber();

}

public class StaticExample {

public void getNumber() {

System.out.println(“A random number: ”

+ Math.random());

}

}

public class StaticExample {

public void getNumber() {

System.out.println(“A random number: ”

+ Math.random());

}

}

Notes: An example of a common static method is Math.random(); most of the Math methods included with the Java API are static. The example calls Math.random().

Page 221: Java Fundamentals SG JAH-CJ-200

221 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Static Methods and Variables in the Java APIStatic Methods and Variables in the Java API

• Examples:

// Determines the roots of a quadratic equation.

public class Quadratic {

public static void main (String[] args) {

int a, b, c; // ax^2 + bx + c

a = 5; // the coefficient of x squared

b = 7; // the coefficient of x

c = 2; // the constant

// Use the quadratic formula to compute the roots.

// Assumes a positive discriminant.

double discriminant = Math.pow(b, 2) - (4 * a * c);

double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);

double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);

System.out.println ("Root #2: " + root2);

}

}

// Determines the roots of a quadratic equation.

public class Quadratic {

public static void main (String[] args) {

int a, b, c; // ax^2 + bx + c

a = 5; // the coefficient of x squared

b = 7; // the coefficient of x

c = 2; // the constant

// Use the quadratic formula to compute the roots.

// Assumes a positive discriminant.

double discriminant = Math.pow(b, 2) - (4 * a * c);

double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);

double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);

System.out.println ("Root #2: " + root2);

}

}

Notes:

Page 222: Java Fundamentals SG JAH-CJ-200

222 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

When to declare a static method or variableWhen to declare a static method or variable

• Performing the operation on an individual object or associating

the variable with a specific object type is not important.

• Accessing the variable or method before instantiating an object

is important.

• The method or variable does not logically belong to an object,

but possibly belongs to a utility class, such as the Math class,

included in the Java API.

Notes:

Page 223: Java Fundamentals SG JAH-CJ-200

223 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses for Method OverloadingUses for Method Overloading

• Java allows us to have two or more methods with the same name inside

the same class

• As with constructors, the overloaded methods should also have

different number of parameters, or have different data types for the

parameters

• This feature of Java is called method overloading

• The compiler will detect errors at the compilation time if two methods

in a class have the same name and have the same number and type of

parameters

Notes: In the Java programming language, there can be several methods in a class that have the same name but different arguments (different method signatures). This concept is called method overloading. Just as you can distinguish between two students in the same class named Jim by calling them ―Jim in the green shirt‖ and ―Jim with the beeper,‖ you can distinguish between two methods by their name and arguments.

Page 224: Java Fundamentals SG JAH-CJ-200

224 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using Method Overloading

• Example overloaded methods:

public class OverloadTest {

public static void main(String args[]) {

MethodOverloadingDemo md = new MethodOverloadingDemo();

md.printToScreen(53,8965);

md.printToScreen(68, 'g');

md.printToScreen('f', 74);

md.printToScreen(64, 36, 'h');

md.printToScreen(85, 'd', (float)745.3, "true");

}

}

public class OverloadTest {

public static void main(String args[]) {

MethodOverloadingDemo md = new MethodOverloadingDemo();

md.printToScreen(53,8965);

md.printToScreen(68, 'g');

md.printToScreen('f', 74);

md.printToScreen(64, 36, 'h');

md.printToScreen(85, 'd', (float)745.3, "true");

}

}

Notes:

Page 225: Java Fundamentals SG JAH-CJ-200

225 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using Method Overloading

• Example overloaded methods:

public class MethodOverloadingDemo {

public void printToScreen(int a, int b) {

System.out.println(a);

System.out.println(b);

}

public void printToScreen(int a, char c) {

System.out.println(a);

System.out.println(c);

}

public void printToScreen(char c, int a) {

System.out.println(c);

System.out.println(a);

}

public class MethodOverloadingDemo {

public void printToScreen(int a, int b) {

System.out.println(a);

System.out.println(b);

}

public void printToScreen(int a, char c) {

System.out.println(a);

System.out.println(c);

}

public void printToScreen(char c, int a) {

System.out.println(c);

System.out.println(a);

}

Notes:

Page 226: Java Fundamentals SG JAH-CJ-200

226 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using Method Overloading

• Example overloaded methods:

public void printToScreen(int a, int b, int c) {

System.out.println(a);

System.out.println(b);

System.out.println(c);

}

public void printToScreen(int a, char c, float f, String s) {

System.out.println(a);

System.out.println(c);

System.out.println(f);

System.out.println(s);

}

}

public void printToScreen(int a, int b, int c) {

System.out.println(a);

System.out.println(b);

System.out.println(c);

}

public void printToScreen(int a, char c, float f, String s) {

System.out.println(a);

System.out.println(c);

System.out.println(f);

System.out.println(s);

}

}

Notes:

Page 227: Java Fundamentals SG JAH-CJ-200

227 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Method Overloading and the Java APIMethod Overloading and the Java API

Notes:

Page 228: Java Fundamentals SG JAH-CJ-200

228 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses for Method OverloadingUses for Method Overloading

• Examples:

public int sum(int numberOne, int numberTwo)

public int sum(int numberOne, int numberTwo, int numberThree)

public int sum(int numberOne, int numberTwo,int numberThree, int

numberFour)

Notes:

Page 229: Java Fundamentals SG JAH-CJ-200

229 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses for Method OverloadingUses for Method Overloading

public class ShirtTwo {

public int shirtID = 0; // Default ID for the shirt

public String description = “-description required-”; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

public char colorCode = „U‟;

public double price = 0.0; // Default price for all items

public int quantityInStock = 0; // Default quantity for all items

public void setShirtInfo(int ID, String desc, double cost, char color){

shirtID = ID;

description = desc;

price = cost;

colorCode = color;

}

public class ShirtTwo {

public int shirtID = 0; // Default ID for the shirt

public String description = “-description required-”; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

public char colorCode = „U‟;

public double price = 0.0; // Default price for all items

public int quantityInStock = 0; // Default quantity for all items

public void setShirtInfo(int ID, String desc, double cost, char color){

shirtID = ID;

description = desc;

price = cost;

colorCode = color;

}

Notes:

Page 230: Java Fundamentals SG JAH-CJ-200

230 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses for Method OverloadingUses for Method Overloading

public void setShirtInfo(int ID, String desc, double cost, char color,

int quantity){

shirtID = ID;

description = desc;

price = cost;

colorCode = color;

quantityInStock = quantity;

}

// This method displays the values for an item

public void display() {

System.out.println(“Item ID: “ + shirtID);

System.out.println(“Item description:” + description);

System.out.println(“Color Code: “ + colorCode);

System.out.println(“Item price: “ + price);

System.out.println(“Quantity in stock: “ + quantityInStock);

} // end of display method

} // end of class

public void setShirtInfo(int ID, String desc, double cost, char color,

int quantity){

shirtID = ID;

description = desc;

price = cost;

colorCode = color;

quantityInStock = quantity;

}

// This method displays the values for an item

public void display() {

System.out.println(“Item ID: “ + shirtID);

System.out.println(“Item description:” + description);

System.out.println(“Color Code: “ + colorCode);

System.out.println(“Item price: “ + price);

System.out.println(“Quantity in stock: “ + quantityInStock);

} // end of display method

} // end of class

Notes:

Page 231: Java Fundamentals SG JAH-CJ-200

231 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Uses for Method OverloadingUses for Method Overloading

public class ShirtTwoTest {

public static void main (String args[]) {

ShirtTwo shirtOne = new ShirtTwo();

ShirtTwo shirtTwo = new ShirtTwo();

ShirtTwo shirtThree = new ShirtTwo();

shirtOne.setShirtInfo(100, “Button Down”, 12.99);

shirtTwo.setShirtInfo(101, “Long Sleeve Oxford”, 27.99, „G‟);

shirtThree.setShirtInfo(102, “Shirt Sleeve T-Shirt”, 9.99, „B‟, 50);

shirtOne.display();

shirtTwo.display();

shirtThree.display();

}

}

public class ShirtTwoTest {

public static void main (String args[]) {

ShirtTwo shirtOne = new ShirtTwo();

ShirtTwo shirtTwo = new ShirtTwo();

ShirtTwo shirtThree = new ShirtTwo();

shirtOne.setShirtInfo(100, “Button Down”, 12.99);

shirtTwo.setShirtInfo(101, “Long Sleeve Oxford”, 27.99, „G‟);

shirtThree.setShirtInfo(102, “Shirt Sleeve T-Shirt”, 9.99, „B‟, 50);

shirtOne.display();

shirtTwo.display();

shirtThree.display();

}

}

Notes:

Page 232: Java Fundamentals SG JAH-CJ-200

232 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 13 Methods Labs Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Create classes and objects Invoke methods of a class Overload methods in a class

Page 233: Java Fundamentals SG JAH-CJ-200

233 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. OneLab Exercises. One

1. Write a Shirt class that has a price, item ID, and type (suchas Oxford or polo). Declare methods that return those threevalues. (These are get methods).

2. Write another class that calls and prints those values.3. You will need to create two files, one called Shirt.java that

declares the shirt variables and methods, and one calledCreateShirt.java that calls the methods and prints thevalues.

Solution to Lab Exercises:

Page 234: Java Fundamentals SG JAH-CJ-200

234 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Two.Lab Exercises. Two.

1. Define a method called sayHello in class Methodcall, provided in the skeleton code, that has no arguments and no return value. Make the body of the method simply print "Hello."

public class Methodcall {

public static void main(String[] args) {

new Methodcall().start(); // students: ignore this

}

public void start() { // a test harness for two methods

//

}

// Define method sayHello with no arguments and no return value

// Make it print "Hello".

// Define method addTwo with an int parameter and int return type

// Make it add 2 to the parameter and return it.

}

Solution to Lab Exercises:

Page 235: Java Fundamentals SG JAH-CJ-200

235 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Two.Lab Exercises. Two.

• Make the start method of Methodcall call sayHello().

• Define a method called addTwo that takes an integer argument, adds 2 to it, and returns that result.

• In the start method of Methodcall, define a local integer variable and initialize it to the result of calling addTwo(3). Print out the variable; that is, print out the result of the method call. Define another local integer variable initialize it to the result of calling addTwo(19). Print out its result.

Solution to Lab Exercises:

Page 236: Java Fundamentals SG JAH-CJ-200

236 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Three.Lab Exercises. Three.

1. Write a Java program that has the classes Area and User. Area has overloaded static methods by the name area() that can be used to calculate the area of a circle, triangle, rectangle and a cylinder. User uses the methods of Area to calculate the area of different geometric figures and prints it to the standard output.

2. Write a class called Area.

3. Write four overloaded methods named area that take different numbers and type of data types as parameters. These methods are used to calculate the area of a circle, triangle, rectangle and cylinder.

Solution to Lab Exercises:

Page 237: Java Fundamentals SG JAH-CJ-200

237 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Three.Lab Exercises. Three.

4. Write a class called User that invokes the different versions of area() in Area class with sample values as parameters. The return value is printed on to the standard output.

• Area of circle = 3.14 * radius * radius

• Area of triangle = 0.5 * base * height

• Area of rectangle = length * breadth

• Area of cylinder = 3.14 * radius * radius * height

Solution to Lab Exercises:

Page 238: Java Fundamentals SG JAH-CJ-200

238 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 14 Implementing Encapsulation and Constructors Objectives Using Encapsulation

o Visibility Modifiers o The public Modifier o The private Modifier o Interface and Implementation o Get and Set Methods o Encapsulated Elevator

Describing Variable Scope o How Instance Variables and Local Variables Appear in Memory

Creating Constructors o Default Constructor o Overloading Constructors

Objectives Upon completion of this module, you should be able to: Use encapsulation to protect data Create constructors to initialize objects

Page 239: Java Fundamentals SG JAH-CJ-200

239 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using EncapsulationUsing Encapsulation

• Encapsulation separates the external aspects of an object from

the internal implementation details

• Internal changes need not affect external interface

Hide

implementation

from clients.

Clients depend

on interface

Notes: Encapsulation separates the external aspects of an object, which are accessible to other objects, from the internal implementation details of the object, which are hidden from other objects. The advantage of encapsulation, which hides implementation detail, is that the class might change. If the only changes take place in the hidden implementation and if the new interface is compatible with the original, programs using the changed class are unaffected. In addition, the implementation can change without affecting the interface.

Page 240: Java Fundamentals SG JAH-CJ-200

240 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using EncapsulationUsing Encapsulation

Notes: In pure OO systems, all attributes are private and can be changed or accessed only through public operations Most or all variables should kept private. Variables are modified by methods of their own class. Implementation can change without changing the interface.

Page 241: Java Fundamentals SG JAH-CJ-200

241 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using EncapsulationUsing Encapsulation

Notes: In object-oriented programming, the term encapsulation refers to the hiding of data within a class (a safe ―capsule‖) and making it available only through certain methods. Encapsulation is important because it makes it easier for other programmers to use your classes and protects certain data within a class from being modified inappropriately. The figure illustrates the concept of encapsulation by showing a safe that has a public interface (a combination lock) that, when used correctly, allows access to private contents.

Page 242: Java Fundamentals SG JAH-CJ-200

242 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The public ModifierThe public Modifier

• You can put the public modifier in front of a member variable or

method to mean that code in any other class can use that part of

the object.

public class PublicExample {

public static void main(String args[]) {

PublicClass pc = new PublicClass();

pc.publicInt = 27;

pc.publicMethod();

}

}

public class PublicExample {

public static void main(String args[]) {

PublicClass pc = new PublicClass();

pc.publicInt = 27;

pc.publicMethod();

}

} public class PublicClass {

public int publicInt;

public void publicMethod() {

System.out.println(publicInt);

}

}

public class PublicClass {

public int publicInt;

public void publicMethod() {

System.out.println(publicInt);

}

}

Notes: Attributes and methods can have modifiers, such as public, that indicate the levels of access other objects can have to the attribute or method. The most commonly used modifiers are public and private.

Page 243: Java Fundamentals SG JAH-CJ-200

243 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The public ModifierThe public Modifier

public int currentFloor=1;

public void setFloor(int desiredFloor) {

...

}

Notes: The public modifier allows the class, its attributes, and methods, to be visible to any object in your program. The figure illustrates an elevator in a hotel with free (public) access to any floor in a building, including areas where visitors or unregistered guests might not be welcome.

Page 244: Java Fundamentals SG JAH-CJ-200

244 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The public ModifierThe public Modifier

• Example:

public class PublicElevator {

public boolean doorOpen=false;

public int currentFloor = 1;

public final int TOP_FLOOR = 5;

public final int BOTTOM_FLOOR = 1;

}

public class PublicElevator {

public boolean doorOpen=false;

public int currentFloor = 1;

public final int TOP_FLOOR = 5;

public final int BOTTOM_FLOOR = 1;

}

Notes: The following code example illustrates the problems introduced when all of the attributes in a program are public. All of the attributes are public, which permits their values to be changed without any error checking.

Page 245: Java Fundamentals SG JAH-CJ-200

245 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The public ModifierThe public Modifier

• Example:

public class PublicElevatorTest {

public static void main(String args[]) {

PublicElevator pubElevator = new PublicElevator();

pubElevator.doorOpen = true; //passengers get on

pubElevator.doorOpen = false; //doors close

//go down to floor 0 (below bottom of building)

pubElevator.currentFloor--;

pubElevator.currentFloor++;

//jump to floor 7 (only 5 floors in building)

pubElevator.currentFloor = 7;

pubElevator.doorOpen = true; //passengers get on/off

pubElevator.doorOpen = false;

pubElevator.currentFloor = 1; //go to the first floor

public class PublicElevatorTest {

public static void main(String args[]) {

PublicElevator pubElevator = new PublicElevator();

pubElevator.doorOpen = true; //passengers get on

pubElevator.doorOpen = false; //doors close

//go down to floor 0 (below bottom of building)

pubElevator.currentFloor--;

pubElevator.currentFloor++;

//jump to floor 7 (only 5 floors in building)

pubElevator.currentFloor = 7;

pubElevator.doorOpen = true; //passengers get on/off

pubElevator.doorOpen = false;

pubElevator.currentFloor = 1; //go to the first floor

Notes: The code example illustrates how a program could be written to directly access the attributes of a PublicElevator object, resulting in several problems. Because the PublicElevator class does not use encapsulation, the PublicElevatorTest class can change the values of its attributes freely and in many undesirable ways.

Page 246: Java Fundamentals SG JAH-CJ-200

246 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The public ModifierThe public Modifier

pubElevator.doorOpen = true; //passengers get on/off

pubElevator.currentFloor++; //elevator moves with door open

pubElevator.doorOpen = false;

pubElevator.currentFloor--;

pubElevator.currentFloor--;

}

}

pubElevator.doorOpen = true; //passengers get on/off

pubElevator.currentFloor++; //elevator moves with door open

pubElevator.doorOpen = false;

pubElevator.currentFloor--;

pubElevator.currentFloor--;

}

}

Notes: Generally, you should use the public modifier only on methods and attribute variables that you want to be accessed directly by other objects.

Page 247: Java Fundamentals SG JAH-CJ-200

247 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The private ModifierThe private Modifier

• Put the private modifier in front of a member variable or

method if you do not want any classses outside the object’s

class to use that part of an object.

public class PrivateExample {

public static void main(String args[]) {

PrivateClass pc = new PublicClass();

pc.privateInt = 27;

pc.privateMethod();

}

}

public class PrivateExample {

public static void main(String args[]) {

PrivateClass pc = new PublicClass();

pc.privateInt = 27;

pc.privateMethod();

}

} public class PrivateClass {

private int privateInt;

private void privateMethod() {

System.out.println(privateInt);

}

}

public class PrivateClass {

private int privateInt;

private void privateMethod() {

System.out.println(privateInt);

}

}

X

X

Notes: The private modifier allows objects of a given class, their attributes, and operations to be inaccessible by other objects.

Page 248: Java Fundamentals SG JAH-CJ-200

248 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The private ModifierThe private Modifier

private int currentFloor=1;

private void calculateCapacity() {

...

}

Notes: The figure illustrates an elevator that has private access to certain floors. By having private access to some floors, people and property on those floors are protected from being accessed by unregistered guests or visitors.

Page 249: Java Fundamentals SG JAH-CJ-200

249 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The private ModifierThe private Modifier

• Example:

public class PrivateElevator1 {

private boolean doorOpen=false;

private int currentFloor = 1;

private final int TOP_FLOOR = 5;

private final int BOTTOM_FLOOR = 1;

}

public class PrivateElevator1 {

private boolean doorOpen=false;

private int currentFloor = 1;

private final int TOP_FLOOR = 5;

private final int BOTTOM_FLOOR = 1;

}

Notes: The code example illustrates how to encapsulate the data within the previous elevator example to ensure that the data is not modified inappropriately. The PrivateElevator1 class only consists of private attribute variables.

Page 250: Java Fundamentals SG JAH-CJ-200

250 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The private ModifierThe private Modifier

• Example:

public class PrivateElevator1Test {

public static void main(String args[]) {

PrivateElevator1 privElevator = new PrivateElevator1();

/**************************************************

* The following lines of code will not compile *

* because they attempt to access private *

* variables.

***************************************************/

privElevator.doorOpen = true; //passengers get on

privElevator.doorOpen = false; //doors close

//go down to currentFloor 0 (below bottom of building)

privElevator.currentFloor--;

privElevator.currentFloor++;

public class PrivateElevator1Test {

public static void main(String args[]) {

PrivateElevator1 privElevator = new PrivateElevator1();

/**************************************************

* The following lines of code will not compile *

* because they attempt to access private *

* variables.

***************************************************/

privElevator.doorOpen = true; //passengers get on

privElevator.doorOpen = false; //doors close

//go down to currentFloor 0 (below bottom of building)

privElevator.currentFloor--;

privElevator.currentFloor++;

Notes: In the code example, an object reference attempts to modify the private variables in the PrivateElevator1 class. The code in the prior code example does not compile because the main method in the PrivateElevator1Test class is attempting to change the value of private attributes in the PrivateElevator1 class. The PrivateElevator1 class is not very useful, however, because there is no way to modify the values of the class. In an ideal program, most or all of the attributes of a class are kept private. Private attributes cannot be modified or viewed directly by classes outside their own class, they can only be modified or viewed by methods of that class. These methods should contain code and business logic to make sure that inappropriate values are not assigned to the variable for an attribute.

Page 251: Java Fundamentals SG JAH-CJ-200

251 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

The private ModifierThe private Modifier

//jump to currentFloor 7 (only 5 floors in building)

privElevator.currentFloor = 7;

privElevator.doorOpen = true; //passengers get on/off

privElevator.doorOpen = false;

privElevator.currentFloor = 1; //go to the first floor

privElevator.doorOpen = true; //passengers get on/off

privElevator.currentFloor++; //elevator moves with door open

privElevator.doorOpen = false;

privElevator.currentFloor--;

privElevator.currentFloor--;

}

}

//jump to currentFloor 7 (only 5 floors in building)

privElevator.currentFloor = 7;

privElevator.doorOpen = true; //passengers get on/off

privElevator.doorOpen = false;

privElevator.currentFloor = 1; //go to the first floor

privElevator.doorOpen = true; //passengers get on/off

privElevator.currentFloor++; //elevator moves with door open

privElevator.doorOpen = false;

privElevator.currentFloor--;

privElevator.currentFloor--;

}

}

Notes:

Page 252: Java Fundamentals SG JAH-CJ-200

252 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

Notes: The public method and attribute variable declarations are often referred to as the interface to a class because they are the only elements that another class can use. The details on how a class completes an operation within a method is called the implementation of the method. A goal of good OO programming is to create public methods and attribute variable declarations so that the implementation can change without affecting the interface. The figure illustrates the interface of an elevator and two separate implementations. While many elevators around the world might have the same interface, they can have different implementations. When classes are encapsulated, other objects interact with only a few parts (methods) of every other class. For example, a programmer can change the code block for a print method as much as needed, but if the declaration of the print method does not change, then the code that refers to that declaration does not need to change either.

Page 253: Java Fundamentals SG JAH-CJ-200

253 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

• Example:

public class PrivateShirt1 {

private int shirtID = 0; // Default ID for the shirt

private String description = “-description required-”; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

private char colorCode = „U‟;

private double price = 0.0; // Default price for all items

private int quantityInStock = 0; // Default quantity for all items

public char getColorCode() {

return colorCode;

}

public class PrivateShirt1 {

private int shirtID = 0; // Default ID for the shirt

private String description = “-description required-”; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

private char colorCode = „U‟;

private double price = 0.0; // Default price for all items

private int quantityInStock = 0; // Default quantity for all items

public char getColorCode() {

return colorCode;

}

Notes: The example contains a PrivateShirt1 class with private attributes and a public method for getting and setting the colorCode variable.

Page 254: Java Fundamentals SG JAH-CJ-200

254 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

• Example:

public void setColorCode(char newCode) {

colorCode = newCode;

}

//Additional get and set methods for shirtID, description,

// price, and quantityInStock would follow

} // end of class

public void setColorCode(char newCode) {

colorCode = newCode;

}

//Additional get and set methods for shirtID, description,

// price, and quantityInStock would follow

} // end of class

Notes: While this code is syntactically correct, the setcolorCode method does not contain the logic to ensure that the correct values are set.

Page 255: Java Fundamentals SG JAH-CJ-200

255 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

• Example:

public class PrivateShirt1Test {

public static void main (String args[]) {

PrivateShirt1 privShirt = new PrivateShirt1();

char colorCode;

// Set a valid colorCode

privShirt.setColorCode(„R‟);

colorCode = privShirt.getColorCode();

// The PrivateShirtTest1 class can set a valid colorCode

System.out.println(“Color Code: “ + colorCode);

// Set an invalid color code

privShirt.setColorCode(„Z‟);

colorCode = privShirt.getColorCode();

//The PrivateShirtTest1 class can set an invalid colorCode

System.out.println(“Color Code: “ + colorCode);

}

}

public class PrivateShirt1Test {

public static void main (String args[]) {

PrivateShirt1 privShirt = new PrivateShirt1();

char colorCode;

// Set a valid colorCode

privShirt.setColorCode(„R‟);

colorCode = privShirt.getColorCode();

// The PrivateShirtTest1 class can set a valid colorCode

System.out.println(“Color Code: “ + colorCode);

// Set an invalid color code

privShirt.setColorCode(„Z‟);

colorCode = privShirt.getColorCode();

//The PrivateShirtTest1 class can set an invalid colorCode

System.out.println(“Color Code: “ + colorCode);

}

}

Notes: The test class in the following code example successfully sets an invalid color code in a PrivateShirt1 object. This class can set an invalid code because the PrivateShirt1 class is not properly encapsulated to prevent invalid codes from being set.

Page 256: Java Fundamentals SG JAH-CJ-200

256 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

• Example:

public class PrivateShirt2 {

private int shirtID = 0; // Default ID for the shirt

private String description = “-description required-”; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

private char colorCode = „U‟;

private double price = 0.0; // Default price for all items

private int quantityInStock = 0; // Default quantity for all items

public char getColorCode() {

return colorCode;

}

public class PrivateShirt2 {

private int shirtID = 0; // Default ID for the shirt

private String description = “-description required-”; // default

// The color codes are R=Red, B=Blue, G=Green, U=Unset

private char colorCode = „U‟;

private double price = 0.0; // Default price for all items

private int quantityInStock = 0; // Default quantity for all items

public char getColorCode() {

return colorCode;

}

Notes:

Page 257: Java Fundamentals SG JAH-CJ-200

257 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

public void setColorCode(char newCode) {

switch (newCode) {

case „R‟:

case „G‟:

case „B‟:

colorCode = newCode;

break;

default:

System.out.println(“Invalid colorCode. Use R, G, or B”);

}

}

// Additional get and set methods for shirtID, description,

// price, and quantityInStock would follow

} // end of class

public void setColorCode(char newCode) {

switch (newCode) {

case „R‟:

case „G‟:

case „B‟:

colorCode = newCode;

break;

default:

System.out.println(“Invalid colorCode. Use R, G, or B”);

}

}

// Additional get and set methods for shirtID, description,

// price, and quantityInStock would follow

} // end of class

Notes: Following is another version of the PrivateShirt1 class. However, before setting the value, this class ensures that any value that it receives is valid. The setColorCode method verifies that a valid color code is set using a switch statement. If an invalid color code is passed to the setColorCode method, an error is displayed. After you have written a class encapsulating its data using the private keyword and getter and setter methods, you can write a class that invokes these getter and setter methods to access the object’s values.

Page 258: Java Fundamentals SG JAH-CJ-200

258 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

• Example:public class PrivateShirt2Test {

public static void main (String args[]) {

PrivateShirt2 privShirt = new PrivateShirt2();

char colorCode;

// Set a valid colorCode

privShirt.setColorCode(„R‟);

colorCode = privShirt.getColorCode();

// The PrivateShirtTest2 class can set a valid colorCode

System.out.println(“Color Code: “ + colorCode);

public class PrivateShirt2Test {

public static void main (String args[]) {

PrivateShirt2 privShirt = new PrivateShirt2();

char colorCode;

// Set a valid colorCode

privShirt.setColorCode(„R‟);

colorCode = privShirt.getColorCode();

// The PrivateShirtTest2 class can set a valid colorCode

System.out.println(“Color Code: “ + colorCode);

Notes:

Page 259: Java Fundamentals SG JAH-CJ-200

259 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Interface and ImplementationInterface and Implementation

// Set an invalid color code

privShirt.setColorCode(„Z‟);

colorCode = privShirt.getColorCode();

// The PrivateShirtTest2 class cannot set an invalid colorCode.

// Color code is still R

System.out.println(“Color Code: “ + colorCode);

}

} //end class

// Set an invalid color code

privShirt.setColorCode(„Z‟);

colorCode = privShirt.getColorCode();

// The PrivateShirtTest2 class cannot set an invalid colorCode.

// Color code is still R

System.out.println(“Color Code: “ + colorCode);

}

} //end class

Notes:

Page 260: Java Fundamentals SG JAH-CJ-200

260 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

• Example:

public class PrivateElevator2 {

private boolean doorOpen=false;

private int currentFloor = 1;

private int weight = 0;

final int CAPACITY = 1000;

final int TOP_FLOOR = 5;

final int BOTTOM_FLOOR = 1;

public void openDoor() {

doorOpen = true;

}

public class PrivateElevator2 {

private boolean doorOpen=false;

private int currentFloor = 1;

private int weight = 0;

final int CAPACITY = 1000;

final int TOP_FLOOR = 5;

final int BOTTOM_FLOOR = 1;

public void openDoor() {

doorOpen = true;

}

Notes: The code example illustrates how to encapsulate the elevator program to prevent problems with its use.

Page 261: Java Fundamentals SG JAH-CJ-200

261 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

public void closeDoor() {

CalculateCapacity();

if (weight <= CAPACITY) {

doorOpen = false;

}

else {

System.out.println(“The elevator has exceeded capacity.”);

System.out.println(“Doors will remain open until someone exits!”);

}

}

public void closeDoor() {

CalculateCapacity();

if (weight <= CAPACITY) {

doorOpen = false;

}

else {

System.out.println(“The elevator has exceeded capacity.”);

System.out.println(“Doors will remain open until someone exits!”);

}

}

Notes:

Page 262: Java Fundamentals SG JAH-CJ-200

262 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

public void goUp() {

if (!doorOpen) {

if (currentFloor < TOP_FLOOR) {

currentFloor++;

System.out.println(currentFloor);

}

else {

System.out.println(“Already on top floor.”);

}

}

else {

System.out.println(“Doors still open!”);

}

}

public void goUp() {

if (!doorOpen) {

if (currentFloor < TOP_FLOOR) {

currentFloor++;

System.out.println(currentFloor);

}

else {

System.out.println(“Already on top floor.”);

}

}

else {

System.out.println(“Doors still open!”);

}

}

Notes:

Page 263: Java Fundamentals SG JAH-CJ-200

263 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

public void goDown() {

if (!doorOpen) {

if (currentFloor > BOTTOM_FLOOR) {

currentFloor--;

System.out.println(currentFloor);

}

else {

System.out.println(“Already on bottom floor.”);

}

}

else {

System.out.println(“Doors still open!”);

}

}

public void goDown() {

if (!doorOpen) {

if (currentFloor > BOTTOM_FLOOR) {

currentFloor--;

System.out.println(currentFloor);

}

else {

System.out.println(“Already on bottom floor.”);

}

}

else {

System.out.println(“Doors still open!”);

}

}

Notes:

Page 264: Java Fundamentals SG JAH-CJ-200

264 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

public void setFloor(int desiredFloor) {

if((desiredFloor >= BOTTOM_FLOOR) && (desiredFloor<=TOP_FLOOR)) {

while (currentFloor != desiredFloor) {

if (currentFloor < desiredFloor) {

goUp();

}

else {

goDown();

}

}

}

else {

System.out.println(“Invalid Floor”);

}

}

public void setFloor(int desiredFloor) {

if((desiredFloor >= BOTTOM_FLOOR) && (desiredFloor<=TOP_FLOOR)) {

while (currentFloor != desiredFloor) {

if (currentFloor < desiredFloor) {

goUp();

}

else {

goDown();

}

}

}

else {

System.out.println(“Invalid Floor”);

}

}

Notes:

Page 265: Java Fundamentals SG JAH-CJ-200

265 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

• Example:public int getFloor() {

return currentFloor;

}

public boolean getDoorStatus() {

return doorOpen;

}

}

public int getFloor() {

return currentFloor;

}

public boolean getDoorStatus() {

return doorOpen;

}

}

Notes:

Page 266: Java Fundamentals SG JAH-CJ-200

266 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

• Example:public int getFloor() {

return currentFloor;

}

public boolean getDoorStatus() {

return doorOpen;

}

}

public int getFloor() {

return currentFloor;

}

public boolean getDoorStatus() {

return doorOpen;

}

}

Notes: The code example illustrates how to access the attribute variables in the PrivateElevator2 class using public methods.

Page 267: Java Fundamentals SG JAH-CJ-200

267 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

privElevator.goDown();

privElevator.goDown();

int curFloor = privElevator.getFloor();

if (curFloor != 5 && ! privElevator.getDoorStatus()) {

privElevator.setFloor(5);

}

privElevator.setFloor(10);

privElevator.openDoor();

}

}

privElevator.goDown();

privElevator.goDown();

int curFloor = privElevator.getFloor();

if (curFloor != 5 && ! privElevator.getDoorStatus()) {

privElevator.setFloor(5);

}

privElevator.setFloor(10);

privElevator.openDoor();

}

}

Notes:

Page 268: Java Fundamentals SG JAH-CJ-200

268 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

public class PrivateElevator2Test {

public static void main(String args[]) {

PrivateElevator2 privElevator = new PrivateElevator2();

privElevator.openDoor();

privElevator.closeDoor();

privElevator.goDown();

privElevator.goUp();

privElevator.goUp();

privElevator.openDoor();

privElevator.closeDoor();

privElevator.goDown();

privElevator.openDoor();

privElevator.goDown();

privElevator.closeDoor();

public class PrivateElevator2Test {

public static void main(String args[]) {

PrivateElevator2 privElevator = new PrivateElevator2();

privElevator.openDoor();

privElevator.closeDoor();

privElevator.goDown();

privElevator.goUp();

privElevator.goUp();

privElevator.openDoor();

privElevator.closeDoor();

privElevator.goDown();

privElevator.openDoor();

privElevator.goDown();

privElevator.closeDoor();

Notes:

Page 269: Java Fundamentals SG JAH-CJ-200

269 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Encapsulated ElevatorEncapsulated Elevator

privElevator.goDown();

privElevator.goDown();

int curFloor = privElevator.getFloor();

if (curFloor != 5 && ! privElevator.getDoorStatus()) {

privElevator.setFloor(5);

}

privElevator.setFloor(10);

privElevator.openDoor();

}

}

privElevator.goDown();

privElevator.goDown();

int curFloor = privElevator.getFloor();

if (curFloor != 5 && ! privElevator.getDoorStatus()) {

privElevator.setFloor(5);

}

privElevator.setFloor(10);

privElevator.openDoor();

}

}

Notes:

Page 270: Java Fundamentals SG JAH-CJ-200

270 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Describing Variable ScopeDescribing Variable Scope

• All variables are not available throughout a program

• Variable scope means where a variabe can be used

public class Person2 {

// begin scope of int age

private int age = 34;

public void displayName() {

// begin scope of String name

String name = “Peter Simmons”;

System.out.println(“My name is “+ name + “ and I am “ + age );

} // end scope of String name

public String getName () {

return name; // this causes an error

}

} // end scope of int age

public class Person2 {

// begin scope of int age

private int age = 34;

public void displayName() {

// begin scope of String name

String name = “Peter Simmons”;

System.out.println(“My name is “+ name + “ and I am “ + age );

} // end scope of String name

public String getName () {

return name; // this causes an error

}

} // end scope of int age

Notes:

Page 271: Java Fundamentals SG JAH-CJ-200

271 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Describing Variables ScopeDescribing Variables Scope

• Local variables are:

– Variables that are defined inside a method and are called

local, automatic, temporary, or stack variables

– Variables that are created when the method is executed are

destroyed when the method is exited

– Local variables require explicit initialization

– Member and class variables are automatically initialized

Notes:

Page 272: Java Fundamentals SG JAH-CJ-200

272 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Variable Scope ExampleVariable Scope Example

Notes:

Page 273: Java Fundamentals SG JAH-CJ-200

273 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

How Instance Variables and Local Variables Appear in MemoryHow Instance Variables and Local Variables Appear in Memory

Notes:

Page 274: Java Fundamentals SG JAH-CJ-200

274 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Constructors of a ClassConstructors of a Class

• The constructor is essentially used to initialize a newly created

object of that particular type

• All classes written in Java have at least one constructor

• If the programmer does not define any constructor for a class,

then the class will have the default constructor created by the

Java runtime system

• The default constructor accepts no arguments

• It has an empty implementation, and does nothing

• Java allow us to have as many constructors as required with the

same name, the only difference being the number or the type of

arguments for a class. This is called constructor overloading

Notes:

Page 275: Java Fundamentals SG JAH-CJ-200

275 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating ConstructorsCreating Constructors

• To define a constructor use the same name as the class and give no

return type

public class Hat {

private String type;

public Hat(String hatType) {

type = hatType;

}

public class Hat {

private String type;

public Hat(String hatType) {

type = hatType;

}

public class Order {

Hat hat1 = new

Hat(“Fedora”);

}

public class Order {

Hat hat1 = new

Hat(“Fedora”);

}

Notes:

Page 276: Java Fundamentals SG JAH-CJ-200

276 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Default ConstructorsDefault Constructors

public class MyClass {

int x;

MyClass() {

x = 10;

}

}

public class MyClass {

int x;

MyClass() {

x = 10;

}

}

public class ConstructorDemo {

public static void main(String[] args ) {

MyClass t1 = new MyClass();

MyClass t2 = new MyClass();

System.out.println(t1.x + " " + t2.x);

}

}

public class ConstructorDemo {

public static void main(String[] args ) {

MyClass t1 = new MyClass();

MyClass t2 = new MyClass();

System.out.println(t1.x + " " + t2.x);

}

}

Notes:

Page 277: Java Fundamentals SG JAH-CJ-200

277 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Overloading ConstructorsOverloading Constructors

public class MyClassTwo {

int x;

MyClassTwo() {

x = 10;

}

MyClassTwo(int i) {

x = i;

}

}

public class MyClassTwo {

int x;

MyClassTwo() {

x = 10;

}

MyClassTwo(int i) {

x = i;

}

}

public class ParametrizedConstructorDemo {

public static void main(String[] args) {

MyClassTwo t1 = new MyClassTwo(10);

MyClassTwo t2 = new MyClassTwo(88);

System.out.println(t1.x + " " + t2.x);

}

}

public class ParametrizedConstructorDemo {

public static void main(String[] args) {

MyClassTwo t1 = new MyClassTwo(10);

MyClassTwo t2 = new MyClassTwo(88);

System.out.println(t1.x + " " + t2.x);

}

}

Notes:

Page 278: Java Fundamentals SG JAH-CJ-200

278 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Overloading ConstructorsOverloading Constructors

public class Student {

private int id = 0;

private String name;

public Student() {

}

public Student(int a) {

id = a;

}

public Student(int a, String aName) {

id = a;

name = aName;

}

public void setValues(int sid, String sName) {

id = sid;

name = sName;

}

public static void main(String[] args) {

Student s = new Student(1,"John");

}

}

public class Student {

private int id = 0;

private String name;

public Student() {

}

public Student(int a) {

id = a;

}

public Student(int a, String aName) {

id = a;

name = aName;

}

public void setValues(int sid, String sName) {

id = sid;

name = sName;

}

public static void main(String[] args) {

Student s = new Student(1,"John");

}

}

Notes:

Page 279: Java Fundamentals SG JAH-CJ-200

279 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 15 Encapsulation and Constructors Lab Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Create classes, and objects Invoke methods of a class Overload constructors

Page 280: Java Fundamentals SG JAH-CJ-200

280 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. One.Lab Exercises. One.

1. Declare a Customer class with variables for a salutation (such

as Ms.), first name, middle name, last name, and address, with

three constructors:

• One creates a new customer with no values

• One takes a salutation (such as Ms.), first name, middle

name, and last name

2. Test the program with a CustomerTest.java program

Solution to Lab Exercises:

Page 281: Java Fundamentals SG JAH-CJ-200

281 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Two.Lab Exercises. Two.

1. Make a class called Rectangle that represents a rectangle usingprivate width and height variables. Make the following publicmethods:

• getHeight returns the height of the rectangle

• getWidth returns the witdh of the rectangle

• setHeight verifies the data and assigns the new value to theheight

• setWidth verifies the data and assigns the new value to thewidth

• getArea returns the area of the rectangle

• getPerimeter returns the perimeter of rectangle

• draw draws the rectangle using asterisks(*’s) as the drawingcharacter

2. Write the main method in another class TestRectangle to test the

Rectangle class (call the methods, and so on).

Solution to Lab Exercises:

Page 282: Java Fundamentals SG JAH-CJ-200

282 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Solution to Lab Exercises:

Page 283: Java Fundamentals SG JAH-CJ-200

283 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 16 Creating and Using Arrays Objectives Creating One-Dimensional Arrays

o Declaring a One-Dimensional Array o Instantiating a One-Dimensional Array o Initializing a One-Dimensional Array o Declaring, Instantiating, and Initializing One-Dimensional Arrays o Accessing a Value Within an Array o Storing One-Dimensional Arrays in Memory

Setting Arrays Values Using the length Attribute and a Loop o The length Attribute o Setting Array Values Using a Loop

Using the args Array in the main Method o Converting String Arguments to Other Types

Describing Two-Dimensional Arrays o Declaring a Two-Dimensional Array o Instantiating a Two-Dimensional Array o Initializing a Two-Dimensional Array

Objectives Upon completion of this module, you should be able to: Code one-dimensional arrays Set array values using the length attribute and a loop Pass arguments to the main method for use in a program Create two-dimensional arrays

Page 284: Java Fundamentals SG JAH-CJ-200

284 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating OneCreating One--Dimensional ArraysDimensional Arrays

• An array is a simple but powerful programming language

construct used to group and organize data. When writing a

program that manages a large amount of information, such as a

list of 100 ages, it is not practical to declare separate variables

for each piece of data. Arrays solve this problem by letting us

declare one variable that can hold multiple, individually

accessible values.

int ageOne = 27;

int ageTwo = 12;

int ageThree = 82;

int ageFour = 70;

int ageFive = 54;

int ageTen = 42;

Notes: Arrays are commonly used efficient data structures. They allows to group data together in an efficient manner. The Java programming language allows you to group multiple values of the same type (lists) using one-dimensional arrays. Arrays are useful when you have related pieces of data (such as the ages for several people), but you do not want to create separate variables to hold each piece of data.

Page 285: Java Fundamentals SG JAH-CJ-200

285 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating OneCreating One--Dimensional ArraysDimensional Arrays

• Arrays are used to hold many values of the same data type

• The index of an array is used to identify each element of the

array

• Arrays also enable us to easily perform various functions like

sorting, searching, merging, etc

• Arrays can store only one type of value, where the type is any

data type supported by Java

Notes:

Page 286: Java Fundamentals SG JAH-CJ-200

286 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Creating OneCreating One--Dimensional ArraysDimensional Arrays

Notes: You can create an array of primitive types, such as int, or an array of references to object types, such as Shirt. Each part of the array is an element. If you declare an array of 100 int types, there are 100 elements. You can access each specific element within the array using its location or index in the array.

Page 287: Java Fundamentals SG JAH-CJ-200

287 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a OneDeclaring a One--Dimensional ArrayDimensional Array

• Syntax:

type [] array_identifier;

• Examples:

char [] status;

int [] ages;

Shirt [] shirts;

String [] names;

Notes: Arrays are handled by an implicit Array object (which is not available in the Java API, but is available in your code). Just as with any object, you must declare an object reference to the array, instantiate an Array object, and then initialize the Array object before you can use it. The syntax used to declare a one-dimensional array is: type [] array_identifier; where:

The type represents the primitive data type or object type for the values stored in the array.

The [] informs the compiler that you are declaring an array.

The array_identifier is the name that you are assigning to refer to the array. Use the following code to declare an array of char values called status and an array of int values called ages. char [] status; int [] ages; Use the following code to declare an array of Shirt references called shirts and an array of String references called names. Shirt [] shirts;

Page 288: Java Fundamentals SG JAH-CJ-200

288 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

String [] names; When you declare an array, the compiler and the Java virtual machine (JVM) have no idea how large the arrays will be because you have declared reference variables that do not currently point to any objects.

Page 289: Java Fundamentals SG JAH-CJ-200

289 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Instantiating a OneInstantiating a One--Dimensional ArrayDimensional Array

• Syntax:

array_identifier = new type [length];

• Examples:

status = new char [20];

ages = new int [5];

names = new String [7];

shirts = new Shirt [3];

Notes: Before you can initialize an array, you must instantiate an Array object large enough to hold all of the values in the array. Instantiate an array by defining the number of elements in the array. The syntax used to instantiate an Array object is: array_identifier = new type [length]; where:

The array_identifier is the name you are assigning to reference the array.

The type represents the primitive data type or object type for the values stored in the array.

The length represents the size (in number of elements) of the array. Use the following code to instantiate an array of char called status and an array of int called ages. status = new char [20]; ages = new int [5]; Use the following code to instantiate an Array object containing String references called names and an array of Shirt references called shirts. names = new String [7]; shirts = new Shirt [3];

Page 290: Java Fundamentals SG JAH-CJ-200

290 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

When you instantiate an Array object, every primitive element is initialized to the zero value for the type you specified. In the case of the char array called status, each value is initialized to \u0000 (the null character of the Unicode character set). For the int array called ages, the initial value is the integer value 0. For the names and shirt arrays, the object references are initialized to null.

Page 291: Java Fundamentals SG JAH-CJ-200

291 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Instantiating a OneInstantiating a One--Dimensional ArrayDimensional Array

Notes:

Page 292: Java Fundamentals SG JAH-CJ-200

292 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing a OneInitializing a One--Dimensional ArrayDimensional Array

• Syntax:

array_identifier[index] = value;

• Examples:

ages[0] = 19;

ages[1] = 42;

ages[2] = 92;

ages[3] = 33;

ages[4] = 46;

shirts[0] = new Shirt();

shirts[1] = new Shirt(„G‟);

shirts[2] = new Shirt(„G‟, 1000);

Notes: You can fill the contents of an array after you have created the array. The syntax for setting the values in an array is: array_identifier[index] = value; where:

The array_identifier is the name you are assigning to the array.

The index represents the location in the array where the value will be placed.

The value is the value you are assigning to index in the array.

Page 293: Java Fundamentals SG JAH-CJ-200

293 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing a OneInitializing a One--Dimensional ArrayDimensional Array

• Examples:

int[] height = new int[11];

height[0] = 69;

height[1] = 61;

height[2] = 70;

height[3] = 74;

height[4] = 62;

height[5] = 69;

height[6] = 66;

height[7] = 73;

height[8] = 79;

height[9] = 62;

height[10] = 70;

Notes:

Page 294: Java Fundamentals SG JAH-CJ-200

294 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring, Instantiating, and Initializing OneDeclaring, Instantiating, and Initializing One--Dimensional ArraysDimensional Arrays

• Syntax:

type [] array_identifier =

{comma-separated list of values or expressions};

• Examples:int [] ages = {19, 42, 92, 33, 46};

Shirt [] shirts = {new Shirt(), new Shirt(121,”Work Shirt”,

„B‟, 12.95), new Shirt(122,”Flannel Shirt”, „G‟, 22.95)};

double[] heights = {4.5, 23.6, 84.124, 78.2, 61.5};

boolean[] tired = {true, false, false, true};

char vowels[] = {'a', 'e', 'i', 'o', 'u'}

Notes: If you know the values you want in your array at the time that you declare the array, you can declare, instantiate, and set the values for an Array object in the same line of code. The syntax for this combined declaration, instantiation, initialization of values is: type [] array_identifier = {comma-separated_list_of_values_or_expressions}; where:

The type represents the primitive data type or object type for the values stored in the array.

The [] informs the compiler that you are declaring an array.

The array_identifier is the name you are assigning to the array.

The {comma-separated_list_of_values_or_expressions} represents a list of values you want to store in the array or a list of expressions with results that will be stored in the array.

Page 295: Java Fundamentals SG JAH-CJ-200

295 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring, Instantiating, and Initializing OneDeclaring, Instantiating, and Initializing One--Dimensional ArraysDimensional Arrays

• Examples:long[] even = {2L, 4L,6L,10L};

long[] value = even;

Notes:

An initializer list can be used to instantiate an array object instead of using the new operator. The size of the array and its initial values are determined by the initializer list.

Page 296: Java Fundamentals SG JAH-CJ-200

296 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Accessing a Value Within an ArrayAccessing a Value Within an Array

• To access a value in an array, we use the name of the array

followed by the index in square brackets.

• Examples:

status[0] = ‟3‟;

names[1] = "Fred Smith";

ages[1] = 19;

prices[2] = 9.99F;

char s = status[0];

String name = names [1];

int age = ages[1];

double price = prices[2];

Notes: Each element of an array is accessed using its index. To access a value from the array, state the array name and the index number for the element (in braces []) on the right side of an assignment operator. The following code example demonstrates how to set the value at a particular index in an array: status[0] = ’3’; names[1] = "Fred Smith"; ages[1] = 19; prices[2] = 9.99F; The following code example demonstrates how to retrieve values from a particular index in an array: char s = status[0]; String name = names [1]; int age = ages[1]; double price = prices[2];

Page 297: Java Fundamentals SG JAH-CJ-200

297 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Accessing a Value Within an ArrayAccessing a Value Within an Array

• Examples:

height[2] = 72;

height[count] = feet * 12;

average = (height[0] + height[1]

+ height[2]) / 3;

System.out.println (“The middle value is “

+ height[MAX/2]);

pick = height[rand.nextInt(11)];

Notes:

Page 298: Java Fundamentals SG JAH-CJ-200

298 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Accessing a Value Within an ArrayAccessing a Value Within an Array

public class BasicArray {

final static int LIMIT = 15;

final static int MULTIPLE = 10;

public static void main (String[] args) {

int[] list = new int[LIMIT];

// Initialize the array values

for (int index = 0; index < LIMIT; index++)

list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

for (int index = 0; index < LIMIT; index++)

System.out.print (list[index] + " ");

System.out.println ();

}

}

public class BasicArray {

final static int LIMIT = 15;

final static int MULTIPLE = 10;

public static void main (String[] args) {

int[] list = new int[LIMIT];

// Initialize the array values

for (int index = 0; index < LIMIT; index++)

list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

for (int index = 0; index < LIMIT; index++)

System.out.print (list[index] + " ");

System.out.println ();

}

}

Notes:

Page 299: Java Fundamentals SG JAH-CJ-200

299 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Accessing a Value Within an ArrayAccessing a Value Within an Array

Notes:

Page 300: Java Fundamentals SG JAH-CJ-200

300 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Accessing a Value Within an ArrayAccessing a Value Within an Array

public class Calculator {

public static double calculateAverage(int[] numbers) {

int sum = 0;

for (int i=0; i<numbers.length; i++)

sum += numbers[i];

return sum/(double)numbers.length;

}

public static int findMaximum(int[] numbers) {

int max = numbers[0];

for (int i=0; i<numbers.length; i++)

if (numbers[i] > max)

max = numbers[i];

return max;

}

}

public class Calculator {

public static double calculateAverage(int[] numbers) {

int sum = 0;

for (int i=0; i<numbers.length; i++)

sum += numbers[i];

return sum/(double)numbers.length;

}

public static int findMaximum(int[] numbers) {

int max = numbers[0];

for (int i=0; i<numbers.length; i++)

if (numbers[i] > max)

max = numbers[i];

return max;

}

}

Notes:

Page 301: Java Fundamentals SG JAH-CJ-200

301 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Accessing a Value Within an ArrayAccessing a Value Within an Array

public class CalculatorTester {

public static void main(String args[]) {

int numbers[] = {23, 54, 88, 98, 23, 54, 7, 72, 35, 22};

System.out.println("The average is " +

Calculator.calculateAverage(numbers));

}

}

public class CalculatorTester {

public static void main(String args[]) {

int numbers[] = {23, 54, 88, 98, 23, 54, 7, 72, 35, 22};

System.out.println("The average is " +

Calculator.calculateAverage(numbers));

}

}

Notes:

Page 302: Java Fundamentals SG JAH-CJ-200

302 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Storing Primitive Variables and Arrays of Primitives in MemoryStoring Primitive Variables and Arrays of Primitives in Memory

Notes: Arrays are objects referred to by an object reference variable. The figure illustrates how a primitive array is stored in memory in comparison to how a primitive data type is stored in memory. The value of the size variable (a char primitive) is L. The value of sizes[] is 0x334009, and it points to an object of type ―array of char‖ with three values. The value of sizes[0] is the char S, the value of sizes[1] is char M, and the value of sizes[2] is char L.

Page 303: Java Fundamentals SG JAH-CJ-200

303 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Storing Reference Variables and Arrays of References in MemoryStoring Reference Variables and Arrays of References in Memory

Notes: The figure illustrates how an object reference array is stored in memory. The value of the myShirt object reference is x99f311 which is an address to an object of type Shirt with the values 0, 0.0, and U. The value of the shirts[] object reference is x179009 which is an address to an object of type ―array of Shirt object references‖ containing three object references:

The value of the shirts[0] index is 0x00099, which is an object reference pointing to an object of type Shirt with the values of 0, 0, and U.

The value of the shirts[1] index is 0x00327, which is an object reference pointing to an object of type Shirt with the values of 0, 0, and U.

The value of the shirts[2] index is 0x00990, which is an object reference pointing to an object of type Shirt with the values of 0, 0, and U.

Page 304: Java Fundamentals SG JAH-CJ-200

304 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Setting Array Values Using the length Attribute and a LoopSetting Array Values Using the length Attribute and a Loop

public class Primes {

public static void main (String[] args) {

int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};

System.out.println ("Array length: " + primeNums.length);

System.out.println ("The first few prime numbers are:");

for (int scan = 0; scan < primeNums.length; scan++)

System.out.print (primeNums[scan] + " ");

System.out.println ();

}

}

public class Primes {

public static void main (String[] args) {

int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};

System.out.println ("Array length: " + primeNums.length);

System.out.println ("The first few prime numbers are:");

for (int scan = 0; scan < primeNums.length; scan++)

System.out.print (primeNums[scan] + " ");

System.out.println ();

}

}

Notes: All Array objects have a length attribute variable that contains the length of the array. The length of an array also referred to as its bounds. The bounds of an array, such as ages[10], is from ages[0] to ages[9], because all arrays start with element zero (0). The number of elements in an array are stored as part of the array object. The length is used by the JVM machine software to ensure that every access to the array corresponds to an actual element of the array. If you attempt to access an element of the array that does not exist, such as specifying ages[21] in your code for an ages array with length [10], you receive an error.

Page 305: Java Fundamentals SG JAH-CJ-200

305 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the Using the argsargs Array in the main MethodArray in the main Method

• Command Line Arguments can be used to supply inputs to a

program during its execution.

• The general construct used for the command line arguments is

as follows:

java classFileName argument1 argument2 etc…

We can give any number of command line arguments. These

command line arguments are stored in the string array passed to

the main() method.

Notes:

Page 306: Java Fundamentals SG JAH-CJ-200

306 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Using the Using the argsargs Array in the main MethodArray in the main Method

Java ArgTest Hello Java

The output is:

args[0] is Hello

args[1] is Java

• All command line arguments are interpreted as strings in Java.

public class ArgsTest {

public static void main (String args[]) {

System.out.println(“args[0] is “ + args[0]);

System.out.println(“args[1] is “ + args[1]);

}

}

public class ArgsTest {

public static void main (String args[]) {

System.out.println(“args[0] is “ + args[0]);

System.out.println(“args[1] is “ + args[1]);

}

}

Notes: The args array accepts an unspecified number of String objects: public static void main (String args[]); When you pass strings to your program on the command line, the strings are put in the args array. To use these strings, you must extract them from the args array and, optionally, convert them to their proper type.

The formal parameter to the main method of a Java application is always an array of String objects.

The Java runtime environment invokes the main method when an application is submitted to the interpreter. The String [] parameter, which we typically call args, represents command-line arguments that are provided when the interpreted is invoked.

Page 307: Java Fundamentals SG JAH-CJ-200

307 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Converting String Arguments to Other TypesConverting String Arguments to Other Types

• Example:

int ID = Integer.parseInt(args[0]);

• The Integer class is one of Java's

"wrapper" classes that provides

methods useful for manipulating

primitive types. Its parseInt() method

will convert a String into an int,

if possible.

Notes: The main method treats everything you type as a literal string. If you want to use the string representation of a number in an expression, you must convert the string to its numerical equivalent. Every data type has an associated class containing static utility methods for converting strings to that data type (Integer class for int, Byte class for byte, Long class for long, and so on). For example, to convert the first argument passed to the main method to an int type: int ID = Integer.parseInt(args[0]);

Page 308: Java Fundamentals SG JAH-CJ-200

308 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Describing TwoDescribing Two--Dimensional ArraysDimensional Arrays

• As the name implies, a two-dimensional array has values in two

dimensions, which are often thought of as the rows and columns

of a table. We must use two indexes to refer to a value in a

two-dimensional array, one specifying the row and another the

column.

Notes: Java allows arrays of multiple dimensions (two or more), 2-dimensional arrays are often used to represent:

Tables

Grid

Images

Page 309: Java Fundamentals SG JAH-CJ-200

309 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Describing TwoDescribing Two--Dimensional ArraysDimensional Arrays

Notes: You also can store matrices of data by using multiple-dimensional arrays (arrays of arrays, of arrays, and so on). A two-dimensional array (an array of arrays) is similar to a spreadsheet with multiple columns (each column represents one array or list of items) and multiple rows.

Page 310: Java Fundamentals SG JAH-CJ-200

310 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a TwoDeclaring a Two--Dimensional ArrayDimensional Array

• Syntax:

type [][] array_identifier;

• Example:

int [][] yearlySales;

Notes: Two dimensional arrays require an additional set of square brackets. The process of creating and using two-dimensional arrays is otherwise the same as with one-dimensional arrays. The syntax for declaring a two dimensional array is: type [][] array_identifier; where:

The type represents the primitive data type or object type for the values stored in the array.

The [][] inform the compiler that you are declaring a two-dimensional array.

The array_identifier is the name you have assigned the array during declaration.

Page 311: Java Fundamentals SG JAH-CJ-200

311 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Instantiating a TwoInstantiating a Two--Dimensional ArrayDimensional Array

• Syntax:array_identifier = new type [number_of_arrays] [length];

• Example:// Instantiates a two-dimensional array: 5 arrays of 4 elements each

yearlySales = new int[5][4];

Notes: The syntax for instantiating a two dimensional array is: array_identifier = new type [number_of_arrays] [length]; where:

The array_identifier is the name you have assigned the array during declaration.

The number_of_arrays is the number of arrays within the array.

The length is the length of each array within the array.

Page 312: Java Fundamentals SG JAH-CJ-200

312 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing a TwoInitializing a Two--Dimensional ArrayDimensional Array

• Example:

yearlySales[0][0] = 1000;

yearlySales[0][1] = 1500;

yearlySales[0][2] = 1800;

yearlySales[1][0] = 1000;

yearlySales[2][0] = 1400;

yearlySales[3][3] = 2000;

Notes:

Page 313: Java Fundamentals SG JAH-CJ-200

313 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing a TwoInitializing a Two--Dimensional ArrayDimensional Array

• Example:

int myTable[][] = {{23, 45, 65, 34, 21, 67, 78},

{46, 14, 18, 46, 98, 63, 88},

{98, 81, 64, 90, 21, 14, 23},

{54, 43, 55, 76, 22, 43, 33}};

for (int row=0;row<4; row++) {

for (int col=0;col<7; col++)

System.out.print(myTable[row][col] + " ");

System.out.println();

}

Notes:

Page 314: Java Fundamentals SG JAH-CJ-200

314 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Initializing a TwoInitializing a Two--Dimensional ArrayDimensional Array

• Example:

public class TwoDArray {

public static void main (String[] args) {

int[][] table = new int[5][10];

// Load the table with values

for (int row=0; row < table.length; row++)

for (int col=0; col < table[row].length; col++)

table[row][col] = row * 10 + col;

// Print the table

for (int row=0; row < table.length; row++) {

for (int col=0; col < table[row].length; col++)

System.out.print (table[row][col] + "\t");

System.out.println();

}

}

}

public class TwoDArray {

public static void main (String[] args) {

int[][] table = new int[5][10];

// Load the table with values

for (int row=0; row < table.length; row++)

for (int col=0; col < table[row].length; col++)

table[row][col] = row * 10 + col;

// Print the table

for (int row=0; row < table.length; row++) {

for (int col=0; col < table[row].length; col++)

System.out.print (table[row][col] + "\t");

System.out.println();

}

}

}

Notes:

Page 315: Java Fundamentals SG JAH-CJ-200

315 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 17 Arrays Lab Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Create and Initialize an array

Page 316: Java Fundamentals SG JAH-CJ-200

316 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. One.Lab Exercises. One.

• Make an array of 5 integers

• Use a for loop to set the values of the array to the index plus 10

• Use a for loop to print out the values in the array

• Make an arrays of strings initialized to Frank, Bob, and Jim using

the variable initializer syntax

• Use a for loop to print out the string in the array

• Set the last element of the array to Mike

• Print out the last element in the array

Solution to Exercise One:

Page 317: Java Fundamentals SG JAH-CJ-200

317 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Two.Lab Exercises. Two.

• Write an Ages program that will fill an array of ten positions

with the ages of ten people you know. (Hard-core the ages into

your program, do not try to use user input). Calculate and print

the oldest age, the youngest age, and the average age.

Solution to Exercise Two:

Page 318: Java Fundamentals SG JAH-CJ-200

318 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. Three.Lab Exercises. Three.

• Copy Ages.java to InputAges.java and then modifiy

InputAges.java so that:

• The size of the array created is determined by the number of

arguments input from the command line

• The values in the array are the arguments input from the

command line

• The same calculations performed by the Ages program are now

performed on this array created from user input.

Solution to Exercise Three:

Page 319: Java Fundamentals SG JAH-CJ-200

319 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 18 Implementing Inheritance Objectives Inheritance

o Superclasses and Subclasses o Declaring a Subclass

Objectives Upon completion of this module, you should be able to: Define and test your use of inheritance

Page 320: Java Fundamentals SG JAH-CJ-200

320 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

• Inheritance is the backbone of object-oriented programming.

• It enables programmers to create a hierarchy among a group of

classes that have similar characteristics.

• We can have one class that defines all the attributes and

behavior common to a specific group of classes.

• All classes that are a part of this specific group can inherit the

common attributes and behavior from this common class.

Notes:

Page 321: Java Fundamentals SG JAH-CJ-200

321 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

• Is a mechanism for defining a new class in terms of an existing

class.

• Allows you to group related classes so that they can be managed

collectively.

• Promotes reuse.

• Allows you hide or override inherited methods.

• Relevant terms: generalization, specialization, override.

Notes:

Page 322: Java Fundamentals SG JAH-CJ-200

322 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

Notes:

Page 323: Java Fundamentals SG JAH-CJ-200

323 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

Notes: Inheritance enables programmers to put common members (variables and methods) in one class and have other classes inherit these common members from this new class. The class containing members common to several other classes is called the superclass or the parent class. The classes that inherit from, or extend, the superclass, are called subclasses or child classes. Inheritance results in a class hierarchy of Java classes similar to the taxonomies found in biology. In the Java programming language, each class can inherit the members of only one other class. Some programming languages, such as C++, allow a class to inherit from multiple superclasses. This concept is called multiple inheritance. The Java programming language does not allow multiple inheritance because it can be confusing for programmers to implement. Instead, the Java programming language uses the concept of an interface.

Page 324: Java Fundamentals SG JAH-CJ-200

324 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

• Inheritance is often represented as a tree. Moving down the

tree, classes become more specialized, more honed toward an

application. Moving up the tree, classes are more general; they

contain members suitable for many classes but are often not

complete.

Notes:

Page 325: Java Fundamentals SG JAH-CJ-200

325 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

Notes:

Page 326: Java Fundamentals SG JAH-CJ-200

326 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

• Java does not support multiple inheritance

– Every Java class except Object has exactly one immediate

superclass (Object does not have a superclass)

• You can force classes that are not related by inheritance to

implement a common set of methods using interfaces

Notes:

Page 327: Java Fundamentals SG JAH-CJ-200

327 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

InheritanceInheritance

• Each subclass inherits the fields of its superclass

– These fields in the superclass may have been inherited from

classes even further up in the class hierarchy

• Each subclass inherits the methods of its superclass

– An object will understand all messages which its class has

implemented or its superclass has either inherited or

implemented

Notes:

Page 328: Java Fundamentals SG JAH-CJ-200

328 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

• Syntax:

[class_modifier] class class_identifier extends

superclass_identifier

Notes: Use the extends keyword to indicate that a class inherits from another class. To declare that a class is a subclass of another class, use the following syntax in your class declaration: [class_modifier] class class_identifier extends superclass_identifier where:

The class_modifier keyword is optional (as indicated by the square brackets) and can be public, abstract, or final. If the class_modifier is not included in the class declaration, it defaults to a default that is sometimes called ―package level‖ and allows access only to other classes in the same package.

The class keyword tells the compiler that the code block is a class declaration.

The class_identifier is the name that you give to this subclass.

The extends keyword tells the compiler that this is a subclass of another class.

The superclass_identifier is the name of the superclass that this subclass extends.

Page 329: Java Fundamentals SG JAH-CJ-200

329 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

• Example: public class Animal {

public void speak() {

System.out.println("I am a generic animal");

}

}

public class Animal {

public void speak() {

System.out.println("I am a generic animal");

}

}

public class Dog extends Animal {

public void speak() {

System.out.println("Woof!!");

}

}

public class Dog extends Animal {

public void speak() {

System.out.println("Woof!!");

}

}

public class Cat extends Animal {

public void speak() {

System.out.println(“Meow!!");

}

}

public class Cat extends Animal {

public void speak() {

System.out.println(“Meow!!");

}

}

Notes: A subclass, in its declaration, uses the extends keyword, followed by the super class name to specify its super class

Page 330: Java Fundamentals SG JAH-CJ-200

330 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

public class TwoDShape {

double width;

double height;

public void showDim() {

System.out.println("Width and height are " + width

+ " and " + height);

}

}

public class TwoDShape {

double width;

double height;

public void showDim() {

System.out.println("Width and height are " + width

+ " and " + height);

}

}

public class Triangle extends TwoDShape {

String style;

public double area() {

return width * height / 2;

}

public void showStyle() {

System.out.println("Triangle is " + style);

}

}

public class Triangle extends TwoDShape {

String style;

public double area() {

return width * height / 2;

}

public void showStyle() {

System.out.println("Triangle is " + style);

}

}

Notes:

Page 331: Java Fundamentals SG JAH-CJ-200

331 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

public class ClassRoom {

private String roomNumber;

private int totalSeats = 60;

private static int totalRooms = 0;

public void setRoomNumber(String rn) {

roomNumber = rn;

}

String getRoomNumber() {

return roomNumber;

}

public void setTotalSeats(int seats) {

totalSeats = seats;

}

public int getTotalSeats() {

return totalSeats;

}

}

public class ClassRoom {

private String roomNumber;

private int totalSeats = 60;

private static int totalRooms = 0;

public void setRoomNumber(String rn) {

roomNumber = rn;

}

String getRoomNumber() {

return roomNumber;

}

public void setTotalSeats(int seats) {

totalSeats = seats;

}

public int getTotalSeats() {

return totalSeats;

}

}

Notes:

Page 332: Java Fundamentals SG JAH-CJ-200

332 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

public class ComputerLab extends ClassRoom {

int totalComputers = 30;

String labAssistant = "TBA";

public void printSeatInfo() {

System.out.println("There are " + getTotalSeats() + "

seats, and “ + totalComputers + " computers in this

computer lab.");

}

public String getLabAssistant() {

return labAssistant;

}

public void setLabAssistant(String assistant) {

this.labAssistant = assistant;

}

}

public class ComputerLab extends ClassRoom {

int totalComputers = 30;

String labAssistant = "TBA";

public void printSeatInfo() {

System.out.println("There are " + getTotalSeats() + "

seats, and “ + totalComputers + " computers in this

computer lab.");

}

public String getLabAssistant() {

return labAssistant;

}

public void setLabAssistant(String assistant) {

this.labAssistant = assistant;

}

}

Notes:

A subclass inherits only nonprivate members of the superclass—that is, the members that do not have an access modifier of private.

A class can inherit only from one other class and no more. This is called single inheritance.

Constructors of the base class are not inherited

Page 333: Java Fundamentals SG JAH-CJ-200

333 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

public class MoodyObject {

// return the mood

protected String getMood() {

return "moody";

}

// ask the object how it feels

public void queryMood() {

System.out.println("I feel " + getMood() + " today!");

}

}

public class MoodyObject {

// return the mood

protected String getMood() {

return "moody";

}

// ask the object how it feels

public void queryMood() {

System.out.println("I feel " + getMood() + " today!");

}

}

public class HappyObject extends MoodyObject {

// redefine class‟s mood

protected String getMood() {

return "happy";

}

// specialization

public void laugh() {

System.out.println("hehehe... hahaha... HAHAHAHAHAHA!!!!!");

}

}

public class HappyObject extends MoodyObject {

// redefine class‟s mood

protected String getMood() {

return "happy";

}

// specialization

public void laugh() {

System.out.println("hehehe... hahaha... HAHAHAHAHAHA!!!!!");

}

}

Notes:

Page 334: Java Fundamentals SG JAH-CJ-200

334 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

public class SadObject extends MoodyObject {

// redefine class‟s mood

protected String getMood() {

return "sad";

}

// specialization

public void cry() {

System.out.println("„wah‟ „boo hoo‟ „weep‟ „sob‟

„weep‟");

}

}

public class SadObject extends MoodyObject {

// redefine class‟s mood

protected String getMood() {

return "sad";

}

// specialization

public void cry() {

System.out.println("„wah‟ „boo hoo‟ „weep‟ „sob‟

„weep‟");

}

}

Notes:

Page 335: Java Fundamentals SG JAH-CJ-200

335 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Declaring a SubclassDeclaring a Subclass

public class MoodyDriver {

public final static void main(String[] args) {

MoodyObject moodyObject = new MoodyObject();

SadObject sadObject = new SadObject();

HappyObject happyObject = new HappyObject();

System.out.println("How does the moody object feel today?");

moodyObject.queryMood();

System.out.println("");

System.out.println("How does the sad object feel today?");

sadObject.queryMood(); // notice that overriding changes the mood

sadObject.cry();

System.out.println("");

System.out.println("How does the happy object feel today?");

happyObject.queryMood(); //notice that overriding changes the mood

happyObject.laugh();

System.out.println("");

}

}

public class MoodyDriver {

public final static void main(String[] args) {

MoodyObject moodyObject = new MoodyObject();

SadObject sadObject = new SadObject();

HappyObject happyObject = new HappyObject();

System.out.println("How does the moody object feel today?");

moodyObject.queryMood();

System.out.println("");

System.out.println("How does the sad object feel today?");

sadObject.queryMood(); // notice that overriding changes the mood

sadObject.cry();

System.out.println("");

System.out.println("How does the happy object feel today?");

happyObject.queryMood(); //notice that overriding changes the mood

happyObject.laugh();

System.out.println("");

}

}

Notes:

Page 336: Java Fundamentals SG JAH-CJ-200

336 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Module 19 Inheritance Lab Objectives Lab Excercises

Objectives Upon completion of this module, you should be able to: Work with inheritance Invoke methods in a super class

Page 337: Java Fundamentals SG JAH-CJ-200

337 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. OneLab Exercises. One

• Design and implement a set of classes that define the employees of a hospital: doctor, nurse, administrator, surgeon, receptionist, janitor, and so on. Include methods in each class that are named according to the services provided by that person and that print an appropriate message. Create a main driver class to instantiate and exercise several of the classes.

Solution to Exercise One:

.

Page 338: Java Fundamentals SG JAH-CJ-200

338 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. TwoLab Exercises. Two

1. Write a Java program that has a class called Color. Color has an attribute called colorName that is private. Color also has the following methods:

final void setColor(String color);

String getColor(); // returned string gives the color

2. The class White inherits from Color, and has its (private) attribute colorName set to White. The classes Violet, Indigo, Blue, Green, Yellow, Orange, and Red inherit from the White class. All these classes have a private variable each, called colorName, initialized to ’violet’, ’indigo’, ’blue’, ’yellow’, ’orange’, and ’red’ respectively. The class Prism has the following method:

void activatePrism(Color c);

Solution to Exercise Two:

Page 339: Java Fundamentals SG JAH-CJ-200

339 Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0

This manual was developed for educational purposes only.

Lab Exercises. TwoLab Exercises. Two

3. This method checks if the getColor() method returns ’white’. If

true, it creates instances of Violet, Indigo, Blue, Green, Yellow,

Orange, and Red classes, and prints their colorName attribute to the

standard output. If the above check results in a false, the method

returns. The class AntiPrism has a method as shown below:

void activateAntiPrism(Red r, Blue b, Green g);

4. This method checks if the colorName attribute of r, b, and g are ’red’,

’blue’, and ’green’ respectively. If true, it creates a new White

object, and prints the value of its attribute colorName on to the

standard output.

5. A class Scientist uses the Prism and AntiPrism classes.

Solution to Exercise Two: