J.E.D.

I

Introduction to Programming I

Version 1.0 May 2005

Introduction to Programming I

1

J.E.D.I

Author Florence Tiu Balagtas Team Joyce Avestro Florence Balagtas Rommel Feria Reginald Hutcherson Rebecca Ong John Paul Petines Sang Shin Raghavan Srinivas Matthew Thompson

Requirements For the Laboratory Exercises
Minimum Hardware Configuration • Microsoft Windows operating systems:

• • • • • • • • • • • • • • • • • •

Processor: 500 MHz Intel Pentium III workstation or equivalent Memory: 384 megabytes Disk space: 125 megabytes of free disk space Processor: 450 MHz UltraTM 10 workstation or equivalent Memory: 384 megabytes Disk space: 125 megabytes of free disk space Processor: 500 MHz Intel Pentium III workstation or equivalent Memory: 384 megabytes

SolarisTM operating system:

Linux operating system:

Disk space: 125 megabytes of free disk space Recommended Hardware Configuration • Microsoft Windows operating systems: Processor: 780 MHz Intel Pentium III workstation or equivalent Memory: 512 megabytes Disk space: 125 megabytes of free disk space Processor: 500 MHz UltraTM 60 workstation or equivalent Memory: 512 megabytes Disk space: 125 megabytes of free disk space Processor: 800 MHz Intel Pentium III workstation or equivalent Memory: 512 megabytes

SolarisTM operating system:

Linux operating system:

Disk space: 125 megabytes of free disk space Operating System NetBeans IDE runs on operating systems that support the JavaTM VM. Below is a list of platforms that NetBeans IDE has been tested on. • Microsoft Windows XP Professional SP1

• • • • • • • • •

Microsoft Windows 2000 Professional SP3 Solaris operating system (SPARC® Platform Edition), versions 8, 9, and 10 Solaris operating system (x86 Platform Edition), versions 8, 9, and 10 Red Hat Linux 9.0 Red Hat Enterprise Linux 3

Sun Java Desktop System NetBeans IDE is also known to run on the following platforms: • Various other Linux distributions Mac OS X 10.1.1 or later Open VMS 7.2-1 or later

Other UNIX ® platforms, such as HP-UX Software NetBeans IDE runs on the J2SE JDK 5.0 (JavaTM 2 JDK, Standard Edition), which consists of the Java Runtime Environment plus developers tools for compiling, debugging, and running applications written in the JavaTM language. NetBeans IDE 4.0 has also been tested on J2SE SDK version 1.4.2. For more information, please visit: http://www.netbeans.org/community/releases/40/relnotes.html

Introduction to Programming I

2

J.E.D.I

Revision History
For Version 1.1 August 2005 Section Version Number Revision History Appendix E: Hands-on Lab Exercises

Details Change from 1.0 to 1.1 Added Added (c/o Sang)

Chapter 10: Creating Your own classes Added subsection on How to set classpath at packages section Chapter 11: Inheritance, Interfaces Polymorphism section and Polymorphism • Added example that uses another class whose method can receive a reference variable Interface • Added sections • Why do we use Interfaces? • Interface vs. Abstract Class • Interface vs. Class • Relationship of an Interface to a Class • Inheritance among Interfaces

Introduction to Programming I

3

J.E.D.I

Table of Contents
1 Introduction to Computer Programming.............................................................. 11 1.1 Objectives............................................................................................... 11 1.2 Introduction............................................................................................. 11 1.3 Basic Components of a Computer................................................................ 12 1.3.1 Hardware.......................................................................................... 12 1.3.1.1 The Central Processing Unit.......................................................... 12 1.3.1.2 Memory .................................................................................... 12 1.3.1.3 Input and Output Devices............................................................. 13 1.3.2 Software........................................................................................... 13 1.4 Overview of Computer Programming Languages........................................... 14 1.4.1 What is a Programming Language?....................................................... 14 1.4.2 Categories of Programming Languages.................................................. 14 1.5 The Program Development Life Cycle........................................................... 15 1.5.1 Problem Definition............................................................................. 16 1.5.2 Problem Analysis............................................................................... 16 1.5.3 Algorithm design and representation.................................................... 17 1.5.3.1 Flowcharting Symbols and their meanings...................................... 18 1.5.4 Coding and Debugging....................................................................... 19 1.6 Number Systems and Conversions.............................................................. 20 1.6.1 Decimal............................................................................................ 20 1.6.2 Binary.............................................................................................. 20 1.6.3 Octal................................................................................................ 20 1.6.4 Hexadecimal..................................................................................... 20 1.6.5 Conversions...................................................................................... 21 1.6.5.1 Decimal to Binary / Binary to Decimal............................................ 21 1.6.5.2 Decimal to Octal (or Hexadecimal)/Octal (or Hexadecimal) to Decimal.... 22 1.6.5.3 Binary to Octal / Octal to Binary.................................................... 23 1.6.5.4 Binary to Hexadecimal / Hexadecimal to Binary............................... 24 1.7 Exercises................................................................................................. 25 1.7.1 Writing Algorithms............................................................................. 25 1.7.2 Number Conversions.......................................................................... 25 2 Introduction to Java........................................................................................ 26 2.1 Objectives............................................................................................... 26 2.2 Java Background...................................................................................... 26 2.2.1 A little Bit of History .......................................................................... 26 2.2.2 What is Java Technology?................................................................... 26 2.2.2.1 A programming language............................................................. 26 2.2.2.2 A development environment......................................................... 26 2.2.2.3 An application environment.......................................................... 26 2.2.2.4 A deployment environment........................................................... 27 2.2.3 Some Features of Java........................................................................ 27 2.2.3.1 The Java Virtual Machine.............................................................. 27 2.2.3.2 Garbage Collection...................................................................... 27 2.2.3.3 Code Security............................................................................. 28 2.2.4 Phases of a Java Program.................................................................... 29 3 Getting to know your Programming Environment................................................. 30 3.1 Objectives............................................................................................... 30 3.2 Introduction............................................................................................. 30

Introduction to Programming I

4

J.E.D.I

3.3 My First Java Program............................................................................... 30 3.4 Using a Text Editor and Console................................................................. 31 3.4.1 Errors .............................................................................................. 46 3.4.1.1 Syntax Errors............................................................................. 46 3.4.1.2 Run-time Errors.......................................................................... 47 3.5 Using Netbeans........................................................................................ 48 3.6 Exercises................................................................................................. 66 3.6.1 Hello World!...................................................................................... 66 3.6.2 The Tree........................................................................................... 66 4 Programming Fundamentals............................................................................. 67 4.1 Objectives............................................................................................... 67 4.2 Dissecting my first Java program................................................................ 67 4.3 Java Comments........................................................................................ 69 4.3.1 C++-Style Comments......................................................................... 69 4.3.2 C-Style Comments............................................................................. 69 4.3.3 Special Javadoc Comments................................................................. 69 4.4 Java Statements and blocks....................................................................... 70 4.5 Java Identifiers........................................................................................ 71 4.6 Java Keywords......................................................................................... 72 4.7 Java Literals............................................................................................ 73 4.7.1 Integer Literals ................................................................................. 73 4.7.2 Floating-Point Literals ........................................................................ 73 4.7.3 Boolean Literals ................................................................................ 73 4.7.4 Character Literals .............................................................................. 74 4.7.5 String Literals ................................................................................... 74 4.8 Primitive data types.................................................................................. 75 4.8.1 Logical - boolean............................................................................... 75 4.8.2 Textual – char................................................................................... 75 4.8.3 Integral – byte, short, int & long.......................................................... 76 4.8.4 Floating Point – float and double.......................................................... 77 4.9 Variables................................................................................................. 78 4.9.1 Declaring and Initializing Variables....................................................... 78 4.9.2 Outputting Variable Data.................................................................... 79 4.9.3 System.out.println() vs. System.out.print() ......................................... 79 4.9.4 Reference Variables vs. Primitive Variables............................................ 80 4.10 Operators.............................................................................................. 81 4.10.1 Arithmetic operators......................................................................... 81 4.10.2 Increment and Decrement operators................................................... 84 4.10.3 Relational operators......................................................................... 86 4.10.4 Logical operators.............................................................................. 89 4.10.4.1 && (logical AND) and & (boolean logical AND)............................... 90 4.10.4.2 || (logical OR) and | (boolean logical inclusive OR)......................... 92 4.10.4.3 ^ (boolean logical exclusive OR).................................................. 94 4.10.4.4 ! (logical NOT).......................................................................... 95 4.10.5 Conditional Operator (?:).................................................................. 96 4.10.6 Operator Precedence........................................................................ 98 4.11 Exercises............................................................................................... 99 4.11.1 Declaring and printing variables......................................................... 99 4.11.2 Getting the average of three numbers................................................. 99 4.11.3 Output greatest value....................................................................... 99 4.11.4 Operator precedence........................................................................ 99 5 Getting Input from the Keyboard..................................................................... 100 5.1 Objectives............................................................................................. 100

Introduction to Programming I

5

J.E.D.I

6

7

8

9

5.2 Using BufferedReader to get input............................................................. 100 5.3 Using JOptionPane to get input................................................................. 104 5.4 Exercises............................................................................................... 106 5.4.1 Last 3 words (BufferedReader version)................................................ 106 5.4.2 Last 3 words (JOptionPane version).................................................... 106 Control Structures......................................................................................... 107 6.1 Objectives............................................................................................. 107 6.2 Decision Control Structures...................................................................... 107 6.2.1 if statement.................................................................................... 107 6.2.2 if-else statement.............................................................................. 109 6.2.3 if-else-if statement........................................................................... 111 6.2.4 Common Errors when using the if-else statements:............................... 112 6.2.5 Example for if-else-else if.................................................................. 113 6.2.6 switch statement............................................................................. 114 6.2.7 Example for switch........................................................................... 116 6.3 Repetition Control Structures.................................................................... 117 6.3.1 while loop....................................................................................... 117 6.3.2 do-while loop................................................................................... 119 6.3.3 for loop........................................................................................... 120 6.4 Branching Statements............................................................................. 121 6.4.1 break statement.............................................................................. 121 6.4.1.1 Unlabeled break statement......................................................... 121 6.4.1.2 Labeled break statement............................................................ 122 6.4.2 continue statement.......................................................................... 123 6.4.2.1 Unlabeled continue statement..................................................... 123 6.4.2.2 Labeled continue statement........................................................ 123 6.4.3 return statement.............................................................................. 124 6.5 Exercises............................................................................................... 125 6.5.1 Grades........................................................................................... 125 6.5.2 Number in words.............................................................................. 125 6.5.3 Hundred Times................................................................................ 125 6.5.4 Powers........................................................................................... 125 Java Arrays.................................................................................................. 126 7.1 Objectives............................................................................................. 126 7.2 Introduction to arrays.............................................................................. 126 7.3 Declaring Arrays..................................................................................... 127 7.4 Accessing an array element...................................................................... 129 7.5 Array length........................................................................................... 130 7.6 Multidimensional Arrays........................................................................... 131 7.7 Exercises............................................................................................... 132 7.7.1 Days of the Week............................................................................. 132 7.7.2 Greatest number.............................................................................. 132 7.7.3 Addressbook Entries......................................................................... 132 Command-line Arguments.............................................................................. 133 8.1 Objectives............................................................................................. 133 8.2 Command-line arguments........................................................................ 133 8.3 Command-line arguments in Netbeans...................................................... 135 8.4 Exercises............................................................................................... 139 8.4.1 Print arguments............................................................................... 139 8.4.2 Arithmetic Operations....................................................................... 139 Working with the Java Class Library................................................................. 140 9.1 Objectives............................................................................................. 140 9.2 Introduction to Object-Oriented Programming............................................. 140

Introduction to Programming I

6

J.E.D.I

9.3 Classes and Objects................................................................................ 141 9.3.1 Difference Between Classes and Objects.............................................. 141 9.3.2 Encapsulation.................................................................................. 142 9.3.3 Class Variables and Methods.............................................................. 142 9.3.4 Class Instantiation........................................................................... 143 9.4 Methods................................................................................................ 144 9.4.1 What are Methods and Why Use Methods?........................................... 144 9.4.2 Calling Instance Methods and Passing Variables....................................145 9.4.3 Passing Variables in Methods............................................................. 146 9.4.3.1 Pass-by-value........................................................................... 146 9.4.3.2 Pass-by-reference...................................................................... 147 9.4.4 Calling Static Methods...................................................................... 148 9.4.5 Scope of a variable........................................................................... 149 9.5 Casting, Converting and Comparing Objects............................................... 152 9.5.1 Casting Primitive Types..................................................................... 152 9.5.2 Casting Objects............................................................................... 154 9.5.3 Converting Primitive Types to Objects and Vice Versa............................ 156 9.5.4 Comparing Objects........................................................................... 157 9.5.5 Determining the Class of an Object..................................................... 159 9.6 Exercises............................................................................................... 160 9.6.1 Defining terms................................................................................. 160 9.6.2 Java Scavenger Hunt........................................................................ 160 10 Creating your own Classes............................................................................ 161 10.1 Objectives............................................................................................ 161 10.2 Defining your own classes...................................................................... 162 10.3 Declaring Attributes.............................................................................. 163 10.3.1 Instance Variables.......................................................................... 163 10.3.2 Class Variables or Static Variables.................................................... 164 10.4 Declaring Methods................................................................................ 164 10.4.1 Accessor methods........................................................................... 165 10.4.2 Mutator Methods............................................................................ 166 10.4.3 Multiple Return statements.............................................................. 167 10.4.4 Static methods............................................................................... 167 10.4.5 Sample Source Code for StudentRecord class..................................... 168 10.5 The this reference................................................................................. 170 10.6 Overloading Methods............................................................................. 171 10.7 Declaring Constructors........................................................................... 173 10.7.1 Default Constructor........................................................................ 173 10.7.2 Overloading Constructors................................................................ 173 10.7.3 Using Constructors......................................................................... 174 10.7.4 The this() Constructor Call............................................................... 175 10.8 Packages............................................................................................. 176 10.8.1 Importing Packages........................................................................ 176 10.8.2 Creating your own packages............................................................ 176 10.8.3 Setting the CLASSPATH.................................................................. 177 10.9 Access Modifiers................................................................................... 179 10.9.1 default access (also called package accessibility)................................ 179 10.9.2 public access................................................................................. 179 10.9.3 protected access............................................................................ 180 10.9.4 private access................................................................................ 180 10.10 Exercises........................................................................................... 181 10.10.1 Address Book Entry....................................................................... 181 10.10.2 AddressBook................................................................................ 181

Introduction to Programming I

7

.......................... 200 12..................................3 Output greatest value......................................................................... Polymorphism and Interfaces...............6.................... 240 Using Netbeans................... 182 11...............................4 Operator precedence...................6.....................1 Objectives...................................................... 257 Chapter 3 Exercises.........................................................2 Interface vs................... 251 1........4 Exercises.I 11 Inheritance........................2................................................. 196 12 Basic Exception Handling.... 241 Appendix C : Answers to Exercises............................................. 213 Installing Netbeans in Windows............................... 197 12...........................................................1 Hello World!............... 201 Installing Java in Linux.......... 202 Installing Java in Windows................................................................................ Abstract Class................................................................ 262 Chapter 6 Exercises..... 251 Chapter 1 Exercises........................4 Final Methods and Final Classes.................................................5....2 What are Exceptions?................................................. 258 3.............................................................................2 Last 3 words (JOptionPane version)...............2 Number Conversions.................................................................... 260 4..........................5........................3 Handling Exceptions.......................... 183 11........1 Writing Algorithms.............................................................5 Interfaces.................................................... 195 11................................................2 Getting the average of three numbers......................... 227 Setting the Path...............................................1 Objectives.................4.........2 Catching Exceptions 2...............................E....................D................................................................................3 Overriding Methods................................... 192 11.......5 Relationship of an Interface to a Class.................................................... 259 4.......... 258 3..................................2 The Shape abstract class............................ 182 11............. 259 4...........J.....................................................2 The Tree.............2 The super keyword.............. 261 5..............5.................................................................... 261 5....... 259 4..................................................................................4 Creating Interfaces.........1 Catching Exceptions1................................ 190 11.........................5.............1 Extending StudentRecord............................................................................................ 196 11...........................................................................................................................................................................................................5................4 Abstract Classes......................................1 Declaring and printing variables........................................................................ 263 Introduction to Programming I 8 ..................2 Inheritance.............................................................................................................1 Last 3 words (BufferedReader version)... 251 1..........................................................1 Why do we use Interfaces?.6 Inheritance among Interfaces................. 222 Appendix B: Getting to know your Programming Environment (Windows XP version).................. 196 11...................................6 Exercises............................................ 197 12.3 Polymorphism................................... Class......................... 200 12.............2........... 195 11........................................... 254 Chapter 2 (No exercises).................................................................................... 192 11.................................................... 200 Appendix A : Java and Netbeans Installation................................................................. 193 11................................................................................................................. 182 11......... 188 11.......................................................... 197 12...............................2...................................................................... 226 My First Java Program.................................................5................ 226 Using a Text Editor and Console..............................................................................................................1 Defining Superclasses and Subclasses...................2............................... 193 11......................... 187 11....................................................................................................4....................................3 Interface vs............................................. 260 Chapter 5 Exercises.................................. 185 11........................ 186 11......... 192 11..... 258 Chapter 4 Exercises............ 210 Installing Netbeans in Linux.................. 197 12...................

...................... 289 12............................................. 304 7........ 316 Chapter 11 Hands-on.........................................................................................................................................................2 Catching Exceptions 2........................................ 301 5...........................2 Conditional Operator......... 303 6.............................4 Powers........................ 289 12.....................................................2 Greatest number..............................................1 Defining terms..................................................................................................................................................... 296 3........ 297 3.. 307 Chapter 10 Hands-on................................................................1 Catching Exceptions 1.........................1 For Loop....................................................................................... 267 6................ 308 10.................... 301 5......2 Java Scavenger Hunt........................................1 Grades .................... 275 Chapter 9 Exercises.................................................................................................................................I 6...................... 304 Chapter 8 Hands-on.....................................................................................................................................................................................................2 Getting Input From Keyboard via JOptionPane................... 299 4....................................................................1 Address Book Entry........D..........................1 Pass-by-Value....... Initializing........................................................................2 AddressBook.................................................................................2 Number in words................ 294 Appendix E : Hands-on Laboratory.................. 300 Chapter 5 Hands-on.................................................................... 276 9...2 Abstract Classes.3 Packaging...................3 Write......................................1 Declaring............... 305 9...............1 Print Arguments........................................ 295 Chapter 2 Hands-on...........................................................................................1 Create your own class....................... 270 Chapter 7 Exercises............................................1 Extending StudentRecord.....................3 Hundred Times................................................................... 308 10.....1 Things to check before you start the lab .........................................................................................1 Arrays...........................................2 Overloading............. 276 9.................... Printing Variables................................2 Pass-by-Reference...................................................................................................................................................................................................................................................................J..................................................... Compile............................3 Comparing Objects......................................... 284 11......................................................................................................... 279 Chapter 11 Exercises................................................................................2 Write.................................................... 292 Machine Problem 2: Minesweeper.............................................................................................. 276 Chapter 10 Exercises........................................................................................................................................ 298 Chapter 4 Hands-on.... Compile............................................ 295 Chapter 1 Hands-on...........................1 Getting Input From Keyboard via BufferedReader......................... 302 Chapter 6 Hands-on............................. 277 10......... 299 4................................... 293 Machine Problem 3: Number Conversion......E........................................ and Run Hello Java Program.. and Run Hello Java Program using NetBeans................................................................................ 284 11.................................... 287 Chapter 12 Exercises............................................................ 305 Chapter 9 Hands-on.................................................. 289 Appendix D : Machine Problems.................... 305 9......................................... 273 7........................................................................................ 313 10...................... 321 Introduction to Programming I 9 ................ 306 9.......... 274 Chapter 8 Exercises............................. 292 Machine Problem 1: Phone Book.. 265 6.................. 275 8....... 273 7.... 277 10.......................................................................1 Days of the Week..... 295 Note to the Teacher.................................................................................. 296 3............................................................................................................................................. 303 Chapter 7 Hands-on................ 263 6................... 295 Chapter 3 Hands-on...............................................

...........Overriding..................................................................3 Polymorphism.................................... 349 Answers to Hands-on Exercises...3 Packaging.......Overriding..... 362 Introduction to Programming I 10 .........................................................................E..........5 Interfaces 1................................................................................................................................1 Exception Handling.......I 11.......................................1 Create your own class. 354 11.........................................................................................2 Inheritance .......1 Inheritance – Constructor.................................................................... 326 11......... 321 11...............................................................................................J........................ 352 10............................ 344 Chapter 12 Hands-on............. 358 11......................................................................................3 Polymorphism............... 360 11...............................D...6 Interfaces 2.................4 Abstract Classes..................... 350 10..........................................................6 Interfaces 2. 337 11............. 349 12.....................2 Inheritance ........2 Overloading...........5 Interfaces 1........................................................ 357 11.................................................................................. 355 11.... 330 11..................................................................................................................................................................................................4 Abstract Classes........................................... 350 10.............1 Inheritance – Constructor..... 355 11..................... 340 11.................................

Finally. It is a data processing machine which accepts data via an input device and its processor manipulates the data according to a program. At the end of the lesson. The second major component is the software which is the intangible part of a computer. different number systems and conversions from one type to another will be discussed. Introduction to Programming I 11 . we will be discussing the basic components of a computer. both hardware and software.1 Objectives In this section.E.I 1 Introduction to Computer Programming 1.J. It consists of data and the computer programs. It is composed of electronic and mechanical parts.D. The computer has two major components.2 Introduction A computer is a machine that performs a variety of tasks according to specific instructions. The first one is the Hardware which is the tangible part of the computer. the student should be able to: • • • • Identify the different components of a computer Know about programming languages and their categories Understand the program development life cycle and apply it in problem solving Learn the different number systems and their conversions 1. We will also be giving a brief overview of programming languages and the program development life cycle.

2 Memory The memory is where data and instructions needed by the CPU to do its appointed tasks can be found. It is used to hold programs and data.1. It is sometimes called the RAM (Random Access Memory). It is not used for long-term storage. all information residing in the main memory is erased. The CPU accesses the memory with the use of these addresses. It contains millions of extremely tiny electrical parts. The computer's main memory is considered as volatile storage. Examples of processors are Pentium. It is used to hold programs and data for long term use. It is divided into several storage locations which have corresponding addresses. Main Memory Fast Expensive Low Yes Secondary Memory Slow Cheap High No Property Speed Price Capacity Volatile Table 1: Comparison between main memory and secondary memory Introduction to Programming I 12 .E. This means that once the computer is turned off.I 1. that the processor is actively working with.3.3. 1. Athlon and SPARC.1. The Secondary Memory The secondary memory is connected to main memory. 2. Secondary memory is considered as non-volatile storage.3.J. It does the fundamental computing within the system. 1.1 The Central Processing Unit The processor is the “brain” of the computer. This means that information residing in secondary memory is not erased after the computer is turned off. Examples of secondary memory are hard disks and cd-rom.1 Hardware 1.3 Basic Components of a Computer 1.D. Main Memory The main memory is very closely connected to the processor.

Machine language is in the form of ones and zeros. Windows. It is kept on some hardware device like a hard disk. Unix. printers and speakers.D. The data that the computer uses can be anything that a program needs.J. for this purpose.1.3 Input and Output Devices Input and output devices allows a computer system to interact with the outside world by moving data into and out of the system. Solaris. Introduction to Programming I 13 . 1. there exists compilers.E. Examples of input devices are keyboards.3. Some Types of Computer Programs: 1. Since it is highly impractical for people to create programs out of zeros and ones. there must be a way of translating or converting a language which we understand into machine language.I 1. Compilers • The computer understands only one language: machine language. MacOS 2. Systems Programs • • Programs that are needed to keep all the hardware and software systems running together smoothly Examples: • Operating Systems like Linux. Examples of output devices are monitors. Programs acts like instructions for the processor. Application Programs • • Programs that people use to get their work done Examples: • Word Processor • Game programs • Spreadsheets 3.2 Software A software is the program that a computer uses in order to function. mice and microphones. but it itself is intangible.3.

Examples are Java. but they are much easier to program in because they allow a programmer to substitute names for numbers. C. Originally. but regardless of what language you use. how these data will be stored/transmitted.2 Categories of Programming Languages 1. etc. these instructions are translated into machine language that can be understood by computers.1 What is a Programming Language? A programming language is a standardized communication technique for expressing instructions to a computer.4. Many programmers today might refer to these latter languages as low-level. each language has its own syntax and grammar. There are different types of programming languages that can be used to create programs. C++. Programming languages enable a programmer to precisely specify what data a computer will act upon. Assembly languages are available for each CPU family.E. and each assembly instruction is translated into one machine instruction by an assembler program.D.4 Overview of Computer Programming Languages 1. assembly language was considered low-level and COBOL. Fortran • 2. Introduction to Programming I 14 . and abstract from low-level computer processor operations such as memory accesses. Low-level Assembly Language • Assembly languages are similar to machine languages. Like human languages.4. High-level Programming Languages • A high-level programming language is a programming language that is more userfriendly. were considered high-level. A programming statement may be translated into one or several machine instructions by a compiler. and precisely what actions to take under various circumstances.I 1. C. to some extent platform-independent.J. Basic. 1. Note: The terms "high-level" and "low-level" are inherently relative.

let us define a single problem that we will solve step-by-step as we discuss the problem solving methodologies in detail. they follow an organized plan or methodology.E. Problem Definition Problem Analysis Algorithm design and representation (Pseudocode or flowchart) Coding and debugging In order to understand the basic steps in solving a problem on a computer. The problem we will solve will be defined in the next section.5 The Program Development Life Cycle Programmers do not sit down and start writing code right away when trying to make a computer program. 3. Instead. Here are the basic steps in trying to solve a problem on the computer: 1.D.J. that breaks the process into a series of tasks. Introduction to Programming I 15 . 2. 4.I 1.

Usually.2 Problem Analysis After the problem has been adequately defined. the problem must be well and clearly defined first in terms of its input and output requirements.I 1.E.D. this step involves breaking up the problem into smaller and simpler subproblems. the simplest and yet the most efficient and effective approach to solve the problem must be formulated.J. Let us now define our example problem: “Create a program that will determine the number of times a name occurs in a list. Before a program can be designed to solve a particular problem. name to look for Output of the program: the number of times the name occurs in a list Introduction to Programming I 16 . Computer programming requires us to define the problem first before we even try to create a solution. Example Problem: Determine the number of times a name occurs in a list Input to the program: list of names.1 Problem Definition A programmer is usually given a task in the form of a problem.5.” 1.5. A clearly defined problem is already half the solution.

it is normally required to express our solution in a step-by-step manner. let's call this the keyname 3. we can now set to finding a solution. Now given the problem defined in the previous sections. Compare the keyname to each of the names in the list 4. which is a cross between human language and a programming language. An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem.D.3 Algorithm design and representation Once our problem is clearly defined. Get the name to look for.E. It may be expressed in either Human language (English. Get the list of names 2. through a graphical representation like a flowchart or through a pseudocode. If all the names have been compared.5.1: Example of a flow chart Introduction to Programming I 17 . In computer programming. If the keyname is the same with a name in the list.J. output the result Expressing our solution through a flowchart: YES Figure 1. how do we express our general solution in such a way that it is simple yet understandable? Expressing our solution through Human language: 1. Tagalog). add 1 to the count 5.I 1.

3. Decision Symbol Terminal Symbol Represents the beginning. and the arrowheads are mandatory only for right-to-left and bottom-totop flow.J. Annotation Symbol Represents a decision that determines which of a number of alternative paths is to be followed. Represents an I/O function.I Expressing our solution through pseudocode: Let nameList = List of Names Let keyName = the name to be sought Let Count = 0 For each name in NameList do the following if name == keyName Count = Count + 1 Display Count Figure 1. comments. Represents the addition of descriptive information. they state the concept in English or mathematical notation. You can use any symbols in creating your flowcharts. or on the right. form.1 Flowcharting Symbols and their meanings A flowchart is a design tool used to graphically represent the logic in a solution. Input/Output (I/O) Symbol Represents the sequence of available information and executable operations. Here are some guidelines for commonly used symbols in creating flowcharts. Also functions as the default symbol when no other symbol is available. or explanatory notes as clarification. as shown.E.2: Example of a pseudocode 1. as long as you are consistent in using them. or a point of interruption or delay in a program. Symbol Name Meaning Represents the process of executing a defined operation or groups of operations that results in a Process Symbol change in value. which makes data available for processing (input) or displaying (output)of processed information. The vertical line and the broken line may be placed on the left.5.D. Rather. the end. Flowcharts typically do not display programming language commands. or location of information.The lines connect Flowline Symbol other symbols. Introduction to Programming I 18 .

the programmer is unable to form an executable that a user can run until the error is fixed. The programmer has to add some fixes to the program in case of errors (also called bugs) that occurs in the program.E. This is especially true for logic errors such as infinite loops. the program compiles fine into an executable file.4 Coding and Debugging After constructing the algorithm. the program (or even their whole computer) freezes up due to an infinite loop. Also serves as an off-page connector. the program isn't 100% working right away.J. For example.D. However. Introduction to Programming I 19 . Forgetting a semi-colon at the end of a statement or misspelling a certain command. This type of error is called runtime error. In such a case. It's something the compiler can detect as an error. and unfortunately. and therefore. Other types of run-time errors are when an incorrect value is computed. Compilers aren't perfect and so can't catch all errors at compile time. is a compile-time error. Using the algorithm as basis. it is now possible to create the source code. Most of the time.I Symbol Name Connector Symbol Meaning Represents any entry from. Predefined Process Symbol Represents a named process consisting of one or more operations or program steps that are specified elsewhere. when the end-user runs the program. another part of the flowchart. The first one is compile-time error.5. Compile-Time Errors occur if there is a syntax error in the code. Table 2: Flowchart Symbols 1. This process of is called debugging. the same piece of code keeps executing over and over again infinitely so that it loops. The compiler will detect the error and the program won't even compile. But when you follow the code's logic. the source code can now be written using the chosen programming language. At this point. for example. and the other is runtime error. There are two types of errors that a programmer will encounter along the way. etc. the actual syntax of the code looks okay. or exit to. after the programmer has written the program. compilers aren't really smart enough to catch all of these types of errors at compile-time. the wrong thing happens.

Numbers in decimal form are in base 10. We need to write the subscript 16 to indicate that the number is a hexadecimal number.E. This means that the only legal digits are 0 and 1. lowercase or uppercase does not matter).J. Here are examples of numbers written in decimal form: 12610 (normally written as just 126) 1110 (normally written as just 11) 1.2 Binary Numbers in binary form are in base 2.D. This means that the only legal digits are 0-7.I 1.4 Hexadecimal Numbers in hexadecimal form are in base 16. The representation depends on what is called the BASE. Here are examples of numbers written in octal form: 1768 138 1. We need to write the subscript 8 to indicate that the number is an octal number. Here are examples of numbers written in hexadecimal form: 7E16 B16 Hexadecimal Decimal Equivalent 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 A B C D E F 1 9 10 11 12 13 14 5 Table 3: Hexadecimal Numbers and their Equivalence to decimal numbers Decimal 12610 1110 Binary 11111102 10112 Octal 1768 138 Hexadecimal 7E16 B16 Table 4: Summary of Examples Introduction to Programming I 20 .6.6. We need to write the subscript 2 to indicate that the number is a binary number.3 Octal Numbers in octal form are in base 8. The following are the four most common representations. This means that the only digits that appear are 0-9.6. 1. Here are examples of numbers written in binary form: 11111102 10112 1.1 Decimal We normally represent numbers in their decimal form.6. This means that the only legal digits are 09 and the letters A-F (or a-f.6 Number Systems and Conversions Numbers can be represented in a variety of ways.

and the result is the binary form of the number. Get the quotient and divide that number again by 2 and repeat the whole process until the quotient reaches 0 or 1. NOTE: For the last digit which is already less than the divisor (which is 2) just copy the value to the remainder portion. continuously divide the number by 2 and get the remainder (which is either 0 or 1). We then add all the products to get the resulting decimal number. For Example: 11111102 = ? Position Write it this way 10 Binary Digits 6 5 4 3 2 1 0 1 1 1 1 1 1 0 0 x 20 = 0 1 x 21 = 2 1 x 22 = 4 1 x 23= 8 1 x 24= 16 1 x 25 = 32 1 x 26 = 64 TOTAL: 126 Introduction to Programming I 21 . We then get all the remainders starting from the last remainder. writing the remainders from the bottom up.D.5 Conversions 1.E. and get that number as a digit of the binary form of the number. we get the binary number 11111102 To convert a binary number to decimal.I 1.J.6.1 Decimal to Binary / Binary to Decimal To convert a decimal number to binary. we multiply the binary digit to "2 raised to the position of the binary number". For Example: 12610 = ? 2 126 63 31 15 7 3 1 / / / / / / / 2 2 2 2 2 2 2 = = = = = = = Quotient 63 31 15 7 3 1 Remainder 0 1 1 1 1 1 1 So.6.5.

you replace it with 8(for octal) or 16 (for hexadecimal). To do that. we will just replace the base number 2 with 8 for Octal and 16 for hexadecimal. writing the remainders from the bottom up. we get the hexadecimal number 7E16 *** Converting octal or hexadecimal numbers is also the same as converting binary numbers to decimal.6.2 Decimal to Octal (or Hexadecimal)/Octal (or Hexadecimal) to Decimal Converting decimal numbers to Octal or hexadecimal is basically the same as converting decimal to binary.E. However. writing the remainders from the bottom up. we get the octal number 1768 For Example (Hexadecimal): 12610 = ? 16 Quotient 126 / 16 = 7 / 16 = 7 Remainder 14 (equal to hex digit E) 7 Write it this way So.J. For Example (Octal): 12610 = ? 8 Quotient 126 / 8 = 15 / 8 = 1/8= 15 1 Remainder 6 7 1 Write it this way So.5.D. instead of having 2 as the divisor.I 1. For Example (Octal): 1768 = ? 10 Position Octal Digits 2 1 1 7 0 6 6 x 80 = 6 7 x 81 = 56 1 x 82 = 64 TOTAL: 126 Introduction to Programming I 22 .

D.J. We then convert each partition into its corresponding octal digit.3 Binary to Octal / Octal to Binary To convert from binary numbers to octal. we partition the binary number into groups of 3 digits (from right to left). and pad it with zeros if the number of digits is not divisible by 3.5. Octal Digit 0 1 2 3 4 5 6 7 Binary Representation 000 001 010 011 100 101 110 111 Table 5: Octal Digits and their corresponding binary represenation For Example: 11111102 = ? 8 0 0 1 1 1 1 7 1 1 1 6 0 Equivalent octal number Converting octal numbers to binary is just the opposite of what is given above. Simply convert each octal digit into its binary representation (given the table) and concatenate them.E.I For Example (Hexadecimal): 7E16 = ? 10 Position Hex Digits 1 7 0 E 14 x 160 = 14 7 x 161 = 112 TOTAL: 126 1.6. The following is a table showing the binary representation of each octal digit. Introduction to Programming I 23 . The result is the binary representation.

The result is the binary representation. Hexadecimal Digit 0 1 2 3 4 5 6 7 8 9 A B C D E F Binary Representation 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Table 6: Hexadecimal Digits and their corresponding binary represenation For Example: 11111102 = ? 16 0 1 7 1 1 1 1 E 1 0 Equivalent Hexadecimal number Converting hexadecimal numbers to binary is just the opposite of what is given above.6.J. we partition the binary number into groups of 4 digits (from right to left). We then convert each partition into its corresponding hexadecimal digit.E.4 Binary to Hexadecimal / Hexadecimal to Binary To convert from binary numbers to hexadecimal. Simply convert each hexadecimal digit into its binary representation (given the table) and concatenate them.D.5. and pad it with zeros if the number of digits is not divisible by 4. The following is a table showing the binary representation of each hexadecimal digit. Introduction to Programming I 24 .I 1.

E. Logging into your laboratory's computer 3. 768 to binary.J. Getting the average of three numbers 1. 43F16 to binary.7.2 Number Conversions Convert the following numbers: 1. hexadecimal and octal 2. 10010011012 to decimal. 198010 to binary. You may write your algorithms using pseudocodes or you can use flowcharts. 1.1 Writing Algorithms Given the following set of tasks.I 1.7 Exercises 1. Baking Bread 2. hexadecimal and octal 3. hexadecimal and decimal 4.7. decimal and octal Introduction to Programming I 25 . create an algorithm to accomplish the following tasks.D.

and so on.2 A development environment As a development environment. its name was changed to Java because there was already a language called Oak. One of the first projects developed using Java was a personal hand-held remote control named Star 7. we will be discussing a little bit of Java history and what is Java Technology.1 A programming language As a programming language.3 An application environment Java technology applications are typically general-purpose programs that run on any machine where the Java runtime environment (JRE) is installed. garbage collection and code security Describe the different phases of a Java program 2. al. of Sun Microsystems. the student should be able to: • • Describe the features of Java technology such as the Java virtual machine. Introduction to Programming I 26 . Initially called Oak.2. Java technology provides you with a large suite of tools: a compiler. At about the same time.1 A little Bit of History Java was created in 1991 by James Gosling et al. in honor of the tree outside Gosling's window.E.2.2.D. the World Wide Web and the Internet were gaining popularity. The original motivation for Java was the need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators. a class file packaging tool. 2.2 Java Background 2.2 What is Java Technology? 2. Java can create all kinds of applications that you could create using any conventional programming language. 2.2. a documentation generator. 2. realized that Java could be used for Internet programming.2.J.2. We will also discuss the phases that a Java program undergoes.I 2 Introduction to Java 2. Gosling et. an interpreter. At the end of the lesson.2.2.1 Objectives In this section.

which includes basic language classes.D. 2. Most commercial browsers supply a Java technology interpreter and runtime environment.2. The JVM provides the hardware platform specifications to which you compile all Java technology code. This specification enables the Java software to be platform-independent because the compilation is done for a generic machine known as the JVM.3 Some Features of Java 2.3. In Java. after using that allocated memory. In C.2.2. Introduction to Programming I 27 . 2.2.4 A deployment environment There are two main deployment environments: First. A bytecode is a special machine language that can be understood by the Java Virtual Machine (JVM). no matter what type of computer the program was compiled on.3. C++ and other languages the programmer is responsible for this.1 The Java Virtual Machine The Java Virtual Machine is an imaginary machine that is implemented by emulating software on a real machine. This happens automatically during the lifetime of the Java program. However. GUI component classes. This can be difficult at times since there can be instances wherein the programmers forget to deallocate memory and therefor result to what we call memory leaks.2 Garbage Collection Many programming languages allows a programmer to allocate memory during runtime.I 2.2. there should be a way to deallocate that memory block in order for other programs to use it again. the programmer is freed from the burden of having to deallocate that memory themselves by having what we call the garbage collection thread. The garbage collection thread is responsible for freeing any memory that can be freed. The bytecode is independent of any particular computer hardware.J.E. and so on. The other main deployment environment is on your web browser. the JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages. so any computer with a Java interpreter can execute the compiled Java program.

E. the memory layout of the executable is then determined. After loading all the classes. This limits any Trojan horse applications since local classes are always loaded first. The Class Loader is responsible for loading all classes needed for the Java program.3 Code Security Code security is attained in Java through the implementation of its Java Runtime Environment (JRE). It adds security by separating the namespaces for the classes of the local file system from those that are imported from network sources. code verification (through the bytecode verifier) and finally code execution. the bytecode verifier then tests the format of the code fragments and checks the code fragments for illegal code that can violate access rights to objects.D. The JRE runs code compiled for a JVM and performs class loading (through the class loader).I 2. After all of these have been done.J. This adds protection against unauthorized access to restricted areas of the code since the memory layout is determined during runtime.3. the code is then finally executed. Introduction to Programming I 28 .2. After loading the class and layouting of memory.

java.class file is then interpreted by the Java interpreter that converts the bytecodes into the machine language of the particular computer you are using. Figure 2. After creating and saving your Java program. The . compile the program by using the Java Compiler. vi.I 2.E.4 Phases of a Java Program The following figure describes the process of compiling and executing a Java program. class. emacs. etc.java extension File with .J. The output of this process is a file of Java bytecodes with the file extension . Examples of text editors you can use are notepad. Task Write the program Compile the program Run the program Tool to use Any text editor Java Compiler Java Interpreter Output File with . This file is stored in a disk file with the extension .D.class extension (Java bytecodes) Program Output Table 7: Summary of Phases of a Java Program Introduction to Programming I 29 .1: Phases of a Java Program The first step in creating a Java program is by writing your programs in a text editor.2.

the first one is by using a console and a text editor. a compiler and/or interpreter and a debugger. At the end of the lesson. For the Windows XP version of this section.E. please refer to Appendix A. } } Before we try to explain what the program means. For instructions on how to install Java and Netbeans.out. There are two ways of doing this.println("Hello world!").J. you have installed Java and Netbeans in your system. This tutorial uses RedHat Linux as the operating system. 3.I 3 Getting to know your Programming Environment 3. The second one is by using Netbeans which is an Integrated Development Environment or IDE. compile and run Java programs. let us first take a look at the first Java program you will be writing. Introduction to Programming I 30 . please refer to Appendix B.2 Introduction An IDE is a programming environment integrated into a software application that provides a GUI builder. a text or code editor.3 My First Java Program public class Hello { /** * My first java program */ public static void main(String[] args) { //prints the string "Hello world" on screen System. the student should be able to: • • • Create a Java program using text editor and console in the Linux environment Differentiate between syntax-errors and runtime errors Create a Java program using Netbeans 3.1 Objectives In this section. Make sure that before you do this tutorial. we will be discussing on how to write. let's first try to write this program in a file and try to run it.D. Before going into details.

You will also need to open the Terminal window to compile and execute your Java programs.I 3.4 Using a Text Editor and Console For this example. click on Menu-> Accessories-> Text Editor.1: Opening the Text Editor Introduction to Programming I 31 . Step 1: Start the Text Editor To start the Text Editor in Linux.2: Text Editor Application in Linux Figure 3.J.D. we will be using a text editor to edit the Java source code.E. Figure 3.

Figure 3. click on Menu-> System Tools-> Terminal.D.I Step 2: Open Terminal To open Terminal in Linux.4: Terminal in Linux Figure 3.3: Opening the Terminal Introduction to Programming I 32 .E.J.

E.D.5: Writing the Source Code with the Text Editor Introduction to Programming I 33 .J.I Step 3: Write your the source code of your Java program in the Text Editor Figure 3.

J. Figure 3. click on the File menu found on the menubar and then click on Save.java".E.D. and we will be saving it inside a folder named MYJAVAPROGRAMS.I Step 4: Save your Java Program We will save our program on a file named "Hello. To open the Save dialog box.6: Saving the Source Code Introduction to Programming I 34 .

E.J.D. a dialog box will appear as shown in Figure below.I After doing the procedure described above. Figure 3.7: Save As Dialog Introduction to Programming I 35 .

E.I Now. Type on the "Folder Name" Textbox MYJAVAPROGRAMS. Click on the button encircled in the figure below to create the folder.D. and click on the CREATE button. A dialog box named "New Folder" will then appear.J. We shall name this folder MYJAVAPROGRAMS. Figure 3.8: Creating New Folder Introduction to Programming I 36 . we'll create a new folder inside the root folder where we will save your programs.

J. Figure 3.E.D.I Now that we've created the folder where we will save all the files.9: Opening the Created Folder Introduction to Programming I 37 . double click on that folder to open it.

The folder should be empty for now since it's a newly created folder and we haven't saved anything in it yet.10: View Inside The Created Folder Introduction to Programming I 38 .E.D.I You will see a similar figure as shown below after you clicked on MYJAVAPROGRAMS.J. Figure 3.

in the Selection textbox. and then click on the OK button.11: Saving the Source Code Inside the Created Folder Introduction to Programming I 39 .I Now. which is "Hello. Figure 3.J.java".D. type in the filename of your program.E.

you can just edit it.D. Figure 3. notice how the title of the frame changes from "Untitled 1 (modified) – gedit" to "/root/MYJAVAPROGRAMS/Hello.E.java . Take note that if you want to make changes in your file. and then save it again by clicking on File -> Save.J.gedit".12: New Window After Saving Introduction to Programming I 40 .I Now that you've saved your file.

you can see here that there is a folder named "MYJAVAPROGRAMS" which we have created a while ago. when you open the terminal window. Now let's go inside that directory.E. type ls and then press ENTER. the next step is to compile your program.I Step 5: Compiling your program Now. What you will see is a list of files and folders inside your home folder. To see what is inside that home folder. it opens up and takes you directly to what is called your home folder. Go to the Terminal window we just opened a while ago.java program.13: Lists of Files in the Home Folder Now.D. Figure 3. Typically.J. and where we saved our Hello. Introduction to Programming I 41 .

you type in: cd MYJAVAPROGRAMS Figure 3. you type in the command: cd [directory name].E. The "cd" command stands for.14: Changing the Directory Introduction to Programming I 42 . since the name of our directory is MYJAVAPROGRAMS. change directory.J.I To go inside a directory.D. In this case.

let us now start compiling your Java program.15: List of Files Inside the New Directory Introduction to Programming I 43 . In order to do that.I Once inside the folder where your Java programs are.E. you should make sure that the file is inside the folder where you are in. execute the "ls" command again to see if your file is inside that folder. Figure 3.D.J. Take note that.

javac adds a file to the disk called [filename]. Introduction to Programming I 44 .J.class.16: Compiling Java File During compilation. Figure 3.I To compile a Java program. So in this case. we type in the command: javac [filename].class.E. or in this case. type in: javac Hello.java. Hello. which is the actual bytecode.D.

"Hello world!". To run your Java program.J.17: Running Class File Introduction to Programming I 45 .E. type in: java Hello You can see on the screen that you have just run your first Java program that prints the message. we are now ready to run your program.I Step 6: Running the Program Now. type in the command: java [filename without the extension].D. Figure 3. so in the case of our example. assuming that there are no problems during compilation (we'll explore more of the problems encountered during compilation in the next section).

and omission of correct punctuation. the problem may not be at the exact point. the use of incorrect special characters. our Hello.18: Source Code With Errors Introduction to Programming I 46 . Other common mistakes are in capitalization. Figure 3. 3.4. As discussed before. Let's take for example.1 Errors What we've shown so far is a Java program wherein we didn't encounter any problems in compiling and running. there are two types of errors.java program wherein we intentionally omit the semicolon at one statement and we try to type the incorrect spelling of a command. The second one is the runtime error. we usually encounter errors along the way.J.D. You may have misspelled a command in Java or forgot to write a semi-colon at the end of a statement. However. Java attempts to isolate the error by displaying the line of code and pointing to the first incorrect character in that line.E. spelling. The first one is a compile-time error or also called as syntax error.1.4.I 3. However. As what we have discussed in the first part of this course.1 Syntax Errors Syntax errors are usually typing errors. this is not always the case.

Doing so may reduce the total number of errors dramatically. The second error message suggests that there is a missing semicolon after your statement. The first error message suggests that there is an error in line 6 of your program. It pointed to the next word after the statict. Even programs that compile successfully may display wrong answers if the programmer has not thought through the logical processes and structures of the program.I See the error messages generated after compiling the program. and try to compile the program again.4. try to correct the first mistake in a long list.J. which should be spelled as static. Figure 3.E.1. if you encounter a lot of error messages.D. 3.19: Compiling the Source Code with Errors As a rule of thumb. Introduction to Programming I 47 .2 Run-time Errors Run-time errors are errors that will not display until you run or execute your program.

In this part of the lesson.20: Running Netbeans with the Command-Line Introduction to Programming I 48 . a compiler and/or interpreter and a debugger. we will be using Netbeans. To run Netbeans using command-line.D.5 Using Netbeans Now that we've tried doing our programs the complicated way.J. One is through command-line using terminal. Step 1: Run Netbeans There are two ways to run Netbeans. let's now see how to do all the processes we've described in the previous sections by using just one application. which is an Integrated Development Environment or IDE.E.I 3. An IDE is a programming environment integrated into a software application that provides a GUI builder. a text or code editor. Open terminal (see steps on how to run terminal in the previous discussion). or by jst clicking on the shortcut button found on the main menu. and type: netbeans Figure 3.

Figure 3.I The second way to run Netbeans.E.D.21: Running Netbeans using the Menu Introduction to Programming I 49 . is by clicking on Menu-> Programming-> More Programming Tools-> Netbeans.J.

Figure 3.22: Window After Openning Netbeans Introduction to Programming I 50 .J.E.D.I After you've open NetBeans IDE. you will see a graphical user interface (GUI) similar to what is shown below.

Figure 3.23: Starting New Project Introduction to Programming I 51 .I Step 2: Make a project Now.D. let's first make a project.E. Click on File-> New Project.J.

I After doing this.E.D.J. a New Project dialog will appear. Figure 3.24: Choosing Project Type Introduction to Programming I 52 .

J.E.D.25: Choosing Java Application as Project Type Introduction to Programming I 53 .I Now click on Java Application and click on the NEXT button. Figure 3.

E. Edit the Project Name part and type in "HelloApplication". Figure 3.I Now.D.J.26: Setting the Project Name Introduction to Programming I 54 . a New Application dialog will appear.

E.27: Setting the Project Location Introduction to Programming I 55 .I Now try to change the Application Location. Figure 3. by clicking on the BROWSE button.J.D.

J.D. Figure 3.E.28: Opening the Root Folder Introduction to Programming I 56 .I A Select Project Location dialog will then appear. Double-click on the root folder.

E.D.I The contents of the root folder is then displayed.J.29: Choosing the Folder MYJAVAPROGRAMS as Project Location Introduction to Programming I 57 . Now double-click on the Figure 3. MYJAVAPROGRAMS folder and click on the OPEN button.

I See now that the Project root/MYJAVAPROGRAMS.30: Window after Setting the Project Location to MYJAVAPROGRAMS Introduction to Programming I 58 .D. Location and Project Folder is changed to / Figure 3.E.J.

and then click on the FINISH button. on the Create Main Class textfield. Figure 3.D.E.I Finally. type in Hello as the main class' name.31: Setting the Main Class of the Project to Hello Introduction to Programming I 59 .J.

E.D. Figure 3. NetBeans automatically creates the basic code for your Java program.32: View of the Created Project Introduction to Programming I 60 . where you set the Project location. On the left side of the window. let us first describe the main window after creating the project.I Step 3: Type in your program Before typing in your program. As shown below. This can all be found in your MYJAVAPROGRAMS folder. you can see a list of folders and files that NetBeans generated after creating the project.J. You can just add your own statements to the generated code.

after the statement. try to modify the code generated by Netbeans. Ignore the other parts of the program for now.J.E. as we will explain the details of the code later.println("Hello world!").D.33: Inserting the Code Introduction to Programming I 61 . Insert the code: System. Figure 3. //TODO code application logic here.out.I Now.

I Step 4: Compile your program Now. just click on Build -> Build Main Project.J.D. Figure 3. to compile your program.35: Compiling with Netbeans Using the Shortcut Button Introduction to Programming I 62 . Figure 3. you could also use the shortcut button to compile your code.34: Compiling with Netbeans Using the Build Menu Or.E.

I If there are no errors in your program. Figure 3. you will see a build successful message on the output window.E.36: View after a Successful Compilation Introduction to Programming I 63 .D.J.

Figure 3.E. click on Run-> Run Main Project.I Step 5: Run your program To run your program.J.37: Running with Netbeans using the Run Menu Or you could also use the shortcut button to run your program.D. Figure 3.38: Running with Netbeans using the Shortcut Button Introduction to Programming I 64 .

Figure 3.D.E.J.I The output of your program is displayed in the output window.39: View after a Successful Run Introduction to Programming I 65 .

The program should output on the screen: Welcome to Java Programming [YourName]!!! 3. Introduction to Programming I 66 . The program should output the following lines on the screen: I think that I shall never see.2 The Tree Using Netbeans.J. A tree whose hungry mouth is pressed Against the Earth’s sweet flowing breast.E.6 Exercises 3. create a class named: TheTree. create a class named: [YourName].1 Hello World! Using Netbeans. a poem as lovely as a tree.6.D.I 3.6.

which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). public class Hello indicates the name of the class which is Hello.I 4 Programming Fundamentals 4. however.identifiers and operators Develop a simple valid Java program using the concepts learned in this chapter 4. At the end of the lesson. We will also be discussing some coding guidelines or code conventions along the way to help in effectively writing readable programs.J. we'll try to the dissect your first Java program: public class Hello { /** * My first java program */ public static void main(String[] args) { //prints the string "Hello world" on screen System. we can also place this next to the first line of our code. We will be covering packages and access specifiers later.D.2 Dissecting my first Java program Now.java program introduced in the previous section. We do this by using the class keyword. primitive data types.1 Objectives In this section. the student should be able to: • • • Identify the basic parts of a Java program Differentiate among Java literals.println("Hello world!"). variable types .E. all code should be placed inside a class declaration. We will start by trying to explain the basic parts of the Hello. So. we will be discussing the basic parts of a Java program. we placed the curly brace at the next line after the class declaration. the class uses an access specifier public. In Java. The next line which contains a curly brace { indicates the start of a block. In addition. } } The first line of the code. In this code. we could actually write our code as: public class Hello { public class Hello { or Introduction to Programming I 67 .out.

It is good programming practice to add comments to your code. if the name of your public class is Hello.java extension.J. but used for documentation purposes.println("Hello world!"). It is not part of the program itself. The main method is the starting point of a Java program. //prints the string "Hello world" on screen Now. public static void main(String[] args) { indicates the name of one method in Hello which is the main method. prints the text enclosed by quotation on the screen. Your Java programs should always end with the . So for example. The next line. we learned two ways of creating comments. Make sure to follow the exact signature. You should write comments in your code explaining what a certain class does. 3. The next line. 2.D. A comment is something used to document a part of a code. and the other one is by writing // at the start of the comment. All programs except Applets written in Java start with the main method. The last two lines which contains the two curly braces is used to close the main method and class respectively. System. Coding Guidelines: 1.java. The command System.println(). The next line is also a Java comment.I The next three lines indicates a Java comment. you should save it in a file called Hello. Introduction to Programming I 68 . Anything within these delimiters are ignored by the Java compiler. public static void main(String[] args) { or can also be written as.out. Filenames should match the name of your public class. /** * My first java program */ A comment is indicated by the delimiters “/*” and “*/”.E.out. or what a certain method do. and are treated as comments. prints the text “Hello World!” on screen. The first one is by placing the comment inside /* and */.

Those text are not part of the program and does not affect the flow of the program. For example. It uses tags like: @author Florence Balagtas @version 1. /* this is an exmaple of a C style or multiline comments */ 4. /** This is an example of special java doc comments used for \n generating an html documentation. Like C-style comments. Unlike C++ style comments. For example. C-style multiline comments and special javadoc comments.I 4. For example.3. All the text after // are treated as comments. Java supports three types of comments: C++-style single line comments.3 Java Comments Comments are notes written to a code for documentation purposes.2 C-Style Comments C-style comments or also called multiline comments starts with a /* and ends with a */. It can also contain certain tags to add more information to your comments. You can create javadoc comments by starting the line with /** and ending it with */. All text in between the two delimeters are treated as comments.2 */ Introduction to Programming I 69 .E.3. it can span multiple lines. it can also span lines.D. // This is a C++ style or single line comments 4.J. 4.1 C++-Style Comments C++ Style comments starts with //.3.3 Special Javadoc Comments Special Javadoc comments are used for generating an HTML documentation for your Java programs.

J.println("world").4 Java Statements and blocks A statement is one or more lines of code terminated by a semicolon. An example of a single statement is. you can place the opening curly brace in line with the statement. An example of a block is.out.E.D. System. System.out.I 4. public static void main( String[] args ){ System. public static void main( String[] args ){ System. like for example.for example. System. Any amount of white space is allowed. } Coding Guidelines: 1.out. like.println(“Hello world”). You should indent the next statements after the start of a block.out.println("Hello").println("world"). A block is one or more statements bounded by an opening and closing curly braces that groups the statements as one unit. public static void main( String[] args ){ or you can place the curly brace on the next line.println("Hello").out. public static void main( String[] args ) { 2. } Introduction to Programming I 70 . Block statements can be nested indefinitely. In creating blocks.

use capital letters to indicate the start of the word except the first word.I 4. This means that the identifier: Hello is not the same as hello.J.D. Letters may be lower or upper case. System. 3. Java identifiers are case-sensitive. out.5 Java Identifiers Identifiers are tokens that represent names of variables. For names of methods and variables. Identifiers must begin with either a letter. capitalize the first letter of the class name. void. main. Examples of identifiers are: Hello. For example. or a dollar sign “$”. charArray. fileNumber. the first letter of the word should start with a small letter. Introduction to Programming I 71 . etc. We will discuss more about Java keywords later. Subsequent characters may use numbers 0 to 9. Avoid using underscores at the start of the identifier such as _read or _write.E. Coding Guidelines: 1. etc. In case of multi-word identifiers. methods. public.For example: ThisIsAnExampleOfClassName thisIsAnExampleOfMethodName 2. Identifiers cannot use Java keywords like class. classes. ClassName. For names of classes. an underscore “_”.

D.6 Java Keywords Keywords are predefined identifiers reserved by Java for a specific purpose. Here is a list of the Java Keywords. Introduction to Programming I 72 .1: Java Key Words We will try to discuss all the meanings of these keywords and how they are used in our Java programs as we go along the way.J.E. methods …etc. Figure 4.I 4. classes. You cannot use keywords as names for your variables.

8345e2 is in scientific notation.D. and octal (base 8). while in hexadecimal. Character Literals and String Literals. It's decimal representation is 12. Introduction to Programming I 73 . For decimal numbers. consider the number 12. and in octal. Integer literals default to the data type int. you may wish to force integer literal to the data type long by appending the “l” or “L” character. Boolean Literals. For example. while 5.3 Boolean Literals Boolean literals have only two values.7. we have to follow some special notations.7. Floating-Point Literals. For hexadecimal numbers.2 Floating-Point Literals Floating point literals represent decimals with fractional parts. 4. 4. To use a smaller precision (32-bit) float.1415. they are preceeded by “0”.7.J. just append the “f” or “F” character. The different types of literals in Java are: Integer Literals. it is 0xC. For example. An int is a signed 32-bit value. 583.E. For octals. Floating point literals default to the data type double which is a 64-bit value. We will cover more on data types later. it should be preceeded by “0x” or “0X”.1 Integer Literals Integer literals come in different formats: decimal (base 10). An example is 3. In using integer literals in our program. it is equivalent to 014.7 Java Literals Literals are tokens that do not change or are constant. Floating point literals can be expressed in standard or scientific notations. A long is a signed 64-bit value.45 is in standard notation. hexadecimal (base 16). We just write a decimal number as it is. 4.I 4. In some cases. true or false. we have no special notations.

5 String Literals String literals represent multiple characters and are enclosed by double quotes. ‘\b’ for backspace.J. ‘\n’ for the newline character. ‘\r’ for the carriage return. For example. “Hello World”. the letter a.7. To use a character literal. is represented as ‘a’. 4.D. a backslash is used followed by the character code. Introduction to Programming I 74 .I 4.E. An example of a string literal is. For example. To use special characters such as a newline character. A Unicode character is a 16-bit character set that replaces the 8-bit ASCII character set. enclose the character in single quote delimiters.7.4 Character Literals Character Literals represent single Unicode characters. Unicode allows the inclusion of symbols and special characters from other languages.

It has it’s literal enclosed in double quotes(“”).8. char (for textual). boolean (for logical). It must have its literal enclosed in single quotes(’ ’).J. For example. It is not a primitive data type. 4. double and float (floating point). long (integral).2 Textual – char A character data type (char). boolean result = true. '\'' '\"' //for single quotes //for double quotes Although. The example shown above. represents a single Unicode character. For example. int. String message=“Hello world!” Introduction to Programming I 75 . An example is. declares a variable named result as boolean type and assigns it a value of true.1 Logical .8 Primitive data types The Java programming language defines eight primitive data types. String is not a primitive data type (it is a Class). For example. byte.boolean A boolean data type represents two states: true and false. use the escape character \. ‘a’ ‘\t’ //The letter a //A tab To represent special characters like ' (single quotes) or " (double quotes).8. it is a class.E. 4. The following are. A String represents a data type that contains multiple characters. we will just introduce String in this section. short.D.I 4.

3 Integral – byte.8.J. short.E. a lowercase L is not recommended because it is hard to distinguish from the digit 1.I 4. Introduction to Programming I 76 . You can define its long value by appending the letter l or L. 2 //The 077 //The 0xBACC uses three forms – decimal. Integral data type have the following ranges: Integer Length 8 bits 16 bits 32 bits 64 bits Name or Type byte short int long -27 -215 -231 -263 Range to to to to 27-1 215-1 231-1 263-1 Table 8: Integral types and their ranges Coding Guidelines: In defining a long value.D. octal or hexadecimal. Examples decimal value 2 leading 0 indicates an octal value //The leading 0x indicates a hexadecimal value Integral types has int as default data type. int & long Integral data types in Java are.

02E23 //A large floating-point value 2.J.14 //A simple floating-point value (a double) 6. Floating-point data types have the following ranges: Float Length 32 bits 64 bits Name or Type float double -231 -263 Range to to 231-1 263-1 Table 9: Floating point types and their ranges Introduction to Programming I 77 .E. Floating-point literal includes either a decimal point or one of the following.8. 3.4E+306D //A large double value with redundant D In the example shown above.D.718F //A simple float size value 123.02E+23. That example is equivalent to 6. E or e //(add exponential value) F or f //(float) D or d //(double) Examples are.I 4. the 23 after the E in the second example is implicitly positive.4 Floating Point – float and double Floating point types has double as default data type.

Here is a sample program that declares and initializes some variables. is preferred over the declaration. Declare one variable per line of code. double grade = 0. Use descriptive names for your variables. It always good to initialize your variables as you declare them.9.9 Variables A variable is an item of data used to store state of objects. option = 'C'. public class VariableSamples { public static void main( String[] args ){ //declare a data type with variable name // result and boolean data type boolean result. name it as.1 Declaring and Initializing Variables To declare a variable is as follows. A variable has a data type and a name. } } Coding Guidelines: 1. double quiz=10. Note: Values enclosed in <> are required values.D. double exam=0. grade=0. double data type and initialized //to 0. The data type indicates the type of value that the variable can hold. while those values enclosed in [] are optional. Introduction to Programming I 78 .0. For example. The variable name must follow rules for identifiers. if you want to have a variable that contains a grade for a student. quiz=10. Like for example. double exam=0.I 4.E.J. grade and not just some random letters you choose. <data type> <name> [=initial value]. 4. //assign 'C' to option //declare a data type with variable name //grade. 3.0 double grade = 0. 2. the variable declarations. //declare a data type with variable name // option and char data type char option.

} } The program will output the following text on screen.out. System.println("world!"). Consider the statements.println( “The value of x=“ + x ).out. System.out. System.D.print ()? The first one appends a newline at the end of the data to output. Hello world! Introduction to Programming I 79 . char x. System.out.println( value ). public class OutputVariable { public static void main( String[] args ){ int value = 10. These statements will output the following on the screen.9.println() and System.3 System.out.I 4. x = ‘A’. 10 The value of x=A 4.print("Hello ").9.print("world!"). System.print() What is the difference between the commands System.out. System. System. System.2 Outputting Variable Data In order to output the value of a certain variable. These statements will output the following on the screen. we can use the following commands.println("Hello "). while the latter doesn't.out.println() vs.out.out.out.println() System.out.print() Here's a sample program.E.out. Hello world! Now consider the following statements.J.

It points to another memory location of where the actual data is.4 Reference Variables vs. For the reference variable name. Introduction to Programming I 80 . When you declare a variable of a certain class. you are actually declaring a reference variable to the object with that certain class. They store data in the actual memory location of where the variable is.J.E. Primitive variables are variables with primitive data types. the variable name and the data they hold. wherein you have the address of the memory cells. Reference variables are variables that stores the address in the memory location. int num = 10.9. for the primitive variable num. These are reference variables and primitive variables.D. For example. the variable just holds the address of where the actual data is. String name = "Hello" Suppose. the illustration shown below is the actual memory of your computer. the data is on the actual location of where the variable is.I 4. Memory Address 1001 : 1563 : : 2000 name Variable Name num Data 10 : Address(2000) : : "Hello" As you can see. suppose we have two variables with data types int and String. Primitive Variables We will now differentiate the two types of variables that Java programs have.

relational operators.J.10 Operators In Java. logical operators and conditional operators.E.D.op2 Description Adds op1 and op2 Multiplies op1 by op2 Divides op1 by op2 Computes the remainder of dividing op1 by op2 Subtracts op2 from op1 Table 10: Arithmetic operations and their functions Introduction to Programming I 81 .1 Arithmetic operators Here are the basic arithmetic operators that can be used in creating your Java programs.I 4. There are arithmetic operators. Operator + * / % Use op1 + op2 op1 * op2 op1 / op2 op1 % op2 op1 . These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement.10. 4. there are different types of operators.

out.out.println("Variable values.out. System. //multiplying numbers System.y = " + (x . System.println(" x + y = " + (x + y)).").out..out.").println("Mixing types.out.y)). //subtracting numbers System. int j = 42. / j)). double x = 27. System.. double y = 7.D.out. System.j)).. } } Introduction to Programming I 82 .").out.out.out.j = " + (i .println("Dividing. System.println("Subtracting.println(" i * x = " + (i * x)). //adding numbers System.println(" x = " + x).println(" x / y = " + (x numbers * j))..out.out. System. System. System. //mixing types System.. System.println(" y = " + y).println(" i / j = " + (i System.22.out.").").println(" i * j = " + (i System..E.println(" i = " + i).out..out.println(" x * y = " + (x //dividing numbers System..out.out. System. System...J.println("Adding.println(" i % j = " + (i % j)).println(" i + j = " + (i + j)).I Here's a sample program in the usage of these operators: public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37.").out.println(" j + y = " + (j + y)).out.475. System. System. System. //computing the remainder resulting from dividing System. System.out.println(" j = " + j).println(" x .println(" i .out.. / y)).println("Multiplying.println(" x % y = " + (x % y)).out. * y))..out.").println("Computing the remainder...

. i / j = 0 x / y = 3. i * j = 1554 x * y = 198..22 Adding.y = 20. i % j = 37 x % y = 5.8054 Computing the remainder.475 y = 7. i = 37 j = 42 x = 27..j = -5 x ..D.. i . j + y = 49..37 Dividing. The integer is implicitly converted to a floating-point number before the operation takes place.695 Subtracting.I Here is the output of the program.E.815 Mixing types. the result is a floating point.58 Note: When an integer and a floating-point number are used as operands to a single arithmetic operation.J...22 i * x = 1016..255 Multiplying. Introduction to Programming I 83 .. i + j = 79 x + y = 34.... Variable values..

evaluates to the value of op before it was decremented Decrements op by 1. Operator ++ ++ Use op++ ++op Description Increments op by 1. evaluates to the value of op after it was incremented Decrements op by 1. int j = 3.D. evaluates to the value of op before it was incremented Increments op by 1. the expression. When used before an operand. Java also includes a unary increment operator (++) and unary decrement operator (--). count = count + 1.I 4. is equivalent to.J. int k = 0. int i = 10. Increment and decrement operators increase and decrease a value stored in a number variable by 1. //will result to k = 4+10 = 14 Introduction to Programming I 84 . it causes the variable to be incremented or decremented by 1.E. For example.10. k = ++j + i. count++. evaluates to the value of op after it was decremented //increment the value of count by 1 -- op-- -- --op Table 11: Increment and Decrement operators The increment and decrement operators can be placed before or after an operand. and then the new value is used in the expression in which it appears.2 Increment and Decrement operators Aside from the basic arithmetic operators. For example.

J.E.I When the increment and decrement operators are placed after the operand. int i = 10. For example. int j = 3. the old value of the variable will be used in the expression where it appears. //will result to k = 3+10 = 13 Coding Guideline: Always keep expressions containing increment and decrement operators simple and easy to understand. Introduction to Programming I 85 . k = j++ + i.D. int k = 0.

The output of evaluation are the boolean values true or false. Operator > >= < <= == != Use op1 > op2 op1 >= op2 op1 < op2 op1 <= op2 op1 == op2 op1 != op2 Description op1 is greater than op2 op1 is greater than or equal to op2 op1 is less than op2 op1 is less than or equal to op2 op1 and op2 are equal op1 and op2 are not equal Table 12: Relational Operators Introduction to Programming I 86 .D.3 Relational operators Relational operators compare two values and determines the relationship between those values.10.J.I 4.E.

out.println(" k != j = " + (k != j)).println(" i == j = " + (i == j)). //false //less than or equal to System.out.J.println(" i >= j = System.out. //greater than System.out.println(" k <= j = " + (k <= j))... //true //not equal to System.out.. //true " + (k >= j)). System. //true //greater than or equal to System. //false System.out.out.. int j = 42.println(" k == j = " + (k == j)). " + (i >= j)). //true System.out.. j = " + (i > j)).out.out.I Here's a sample program that uses relational operators.println(" k >= j = //less than System..println(" i != j = " + (i != j)).").println(" j < i = " + (j < i)). System..println("Greater System.out.println(" k < j = " + (k < j)). //true System.out..out.out.").").println(" i <= j = " + (i <= j)). //true j = " + (k > j)). //false or equal to..out.println("Not equal to.println("Less than or equal to.out. System. //false System. public class RelationalDemo { public static void main(String[] args) { //a few numbers int i = 37. //false } } Introduction to Programming I 87 .println(" j > System.out."). System.. //false System.out. //false " + (j >= i))..println("Variable values.println(" j <= i = " + (j <= i)). System.println("Greater than System.out. //false i = " + (j > i)). int k = 42.out.out.. System.println("Less than.println("Equal to.").println(" k = " + k).println(" i = " + i).")..out.println(" k > than.out.E.println(" i > System.out."). //true System.println(" j >= i = System. //true //equal to System.out.D. System.out.println(" j = " + j).println(" i < j = " + (i < j)). System..

.... i < j = true j < i = false k < j = false Less than or equal to. i >= j = false j >= i = true k >= j = true Less than..I Here's the output from this program: Variable values. i = 37 j = 42 k = 42 Greater than. i != j = true k != j = false Introduction to Programming I 88 . i == j = false k == j = true Not equal to.J..D...... i > j = false j > i = true k > j = false Greater than or equal to.E. i <= j = true j <= i = false k <= j = true Equal to....

^ (boolean logical exclusive OR). variables or constants. Introduction to Programming I 89 . and op is either &&.D. ||.I 4.10.4 Logical operators Logical operators have one or two boolean operands that yield a boolean result. x2 can be boolean expressions. | or ^ operator.E. &.J. The basic expression for a logical operation is. and ! (logical NOT). || (logical OR). summarize the result of each operation for all possible combinations of x1 and x2. | (boolean logical inclusive OR). & (boolean logical AND). x1 op x2 where x1. The truth tables that will be shown next. There are six logical operators: && (logical AND).

the & operator always evaluates both exp1 and exp2 before returning an answer.out. What does this mean? Given an expression. } } Introduction to Programming I 90 .println(i). x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE FALSE FALSE FALSE Table 13: Truth table for & and && The basic difference between && and & operators is that && supports short-circuit evaluations (or partial evaluations).D. boolean test= false.E.out. In contrast. exp1 && exp2 && will evaluate the expression exp1. the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2. System. Here's a sample source code that uses logical and boolean AND.I 4. System. and immediately return a false value is exp1 is false.4.println(test).println(i). //demonstrate && test = (i > 10) && (j++ > 9). int j = 10.println(j).out. public class TestAND { public static void main( String[] args ){ int i = 0. System.println(test).out.J.out.out.1 && (logical AND) and & (boolean logical AND) Here is the truth table for && and &.println(j). If exp1 is false. System.10. System. while & doesn't. //demonstrate & test = (i > 10) & (j++ > 9). System.

D.J. 0 10 false 0 11 false Note. that the j++ on the line containing the && operator is not evaluated since the first expression (i>10) is already equal to false. Introduction to Programming I 91 .I The output of the program is.E.

public class TestOR { public static void main( String[] args ){ int i = 0. In contrast. exp1 || exp2 || will evaluate the expression exp1.4.out.D. while | doesn't.out.println(i). //demonstrate || test = (i < 10) || (j++ > 9).println(i). } } Introduction to Programming I 92 . System. System.10. What does this mean? Given an expression.out. System.E. //demonstrate | test = (i < 10) | (j++ > 9).out.I 4.J.out.out.println(test). the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2. System. and immediately return a true value is exp1 is true. System.println(j). Here's a sample source code that uses logical and boolean OR.2 || (logical OR) and | (boolean logical inclusive OR) Here is the truth table for || and |. the | operator always evaluates both exp1 and exp2 before returning an answer. boolean test= false.println(j). System. x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE TRUE TRUE FALSE Table 14: Truth table for | and || The basic difference between || and | operators is that || supports short-circuit evaluations (or partial evaluations). If exp1 is true. int j = 10.println(test).

E. 0 10 true 0 11 true Note.J.I The output of the program is. Introduction to Programming I 93 .D. that the j++ on the line containing the || operator is not evaluated since the first expression (i<10) is already equal to true.

out. Here's a sample source code that uses the logical exclusive OR operator. System.out.println(val1 ^ val2). false true false true Introduction to Programming I 94 .println(val1 ^ val2). System.E.println(val1 ^ val2). val2 = false.3 ^ (boolean logical exclusive OR) Here is the truth table for ^. val1 = false.D.println(val1 ^ val2).I 4. val2 = false. val1 = false.10.out.J. Note that both operands must always be evaluated in order to calculate the result of an exclusive OR. if and only if one operand is true and the other is false. val1 = true. boolean val2 = true. x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Table 15: Truth table for ^ Result FALSE TRUE TRUE FALSE The result of an exclusive OR operation is TRUE.out. public class TestXOR { public static void main( String[] args ){ boolean val1 = true. } } The output of the program is. System. System. val2 = true.4.

Here is the truth table for !.4 ! (logical NOT) The logical NOT takes in one argument.println(!val1). variable or constant.10. } } The output of the program is.I 4.D.E.J. boolean val2 = false. wherein that argument can be an expression. x1 TRUE FALSE Result FALSE TRUE Table 16: Truth table for ! Here's a sample source code that uses the logical NOT operator. System. public class TestNOT { public static void main( String[] args ){ boolean val1 = true.4.out. System. false true Introduction to Programming I 95 .println(!val2).out.

10. Passed Introduction to Programming I 96 . exp2 is the value returned.out. If it is false.5 Conditional Operator (?:) The conditional operator ?: is a ternary operator. If exp1 is true. exp1?exp2:exp3 wherein exp1 is a boolean expression whose result must either be true or false. public class ConditionalOperator { public static void main( String[] args ){ String status = "".I 4.D. given the code. This means that it takes in three arguments that together form a conditional expression.E.println( status ). The structure of an expression using a conditional operator is. int grade = 80.J. //print status System. } } The output of this program will be. //get status of the student status = (grade >= 60)?"Passed":"Fail". then exp3 is returned. For example.

out.J.D. answer = 'a'.I Here is the flowchart of how ?: works.2: Flowchart using the ?: operator Here is another program that uses the ?: operator. } } score = (answer == 'a') ? 10 : 0. The output of the program is. System. Score = 10 Introduction to Programming I 97 .E.println("Score = " + score ). class ConditionalOperator { public static void main( String[] args ){ int char score = 0. Figure 4.

I 4.6 Operator Precedence Operator precedence defines the compiler’s order of evaluation of operators so as to come up with an unambiguous result. Introduction to Programming I 98 . Coding Guidelines To avoid confusion in evaluating mathematical operations. ((6%2)*5)+(4/2)+88-10. 6%2*5+4/2+88-10 we can re-write the expression and place some parenthesis base on operator precedence.J.10.3: Operator Precedence Given a complicated expression.E. Figure 4.D. keep your expressions simple and use parenthesis.

4 Operator precedence Given the following expressions. your program should output. For example. declare the following variables with the corresponding data types and initialization values.I 4.11. given the numbers 10. number 1 = number 2 = number 3 = Average is 10 20 45 = 25 4. Variable name number letter result str Data Type integer character boolean String Initial value 10 a true hello The following should be the expected screen output.11. 3 * 10 *2 / 15 – 2 + 4 ^ 2 ^ 2 3.D. write a program that outputs the number with the greatest value among the three. Number = 10 letter = a result = true str = hello 4.3 Output greatest value Given three numbers. number 1 = 10 number 2 = 23 number 3 = 5 The highest number is = 23 4. Use the conditional ?: operator that we have studied so far (HINT: You will need to use two sets of ?: to solve this).11. 20 and 45.E.1 Declaring and printing variables Given the table below. 1. Let the values of the three numbers be.J. 10. a / b ^ c ^ d – e + f – g * h + i 2.11 Exercises 4. Output to the screen the variable names together with the values.2 Getting the average of three numbers Create a program that outputs the average of three numbers.11. r ^ s * t / u – v + w ^ x – y++ Introduction to Programming I 99 . re-write them by writing some parenthesis based on the sequence on how they will be evaluated. The expected screen output is. 23 and 5.

*. } catch( IOException e ){ System.J. 3.out.io package in order to get input from the keyboard. } Introduction to Programming I 100 . the student should be able to: • • • Create an interactive Java program that gets input from the keyboard Use the BufferedReader class to get input from the keyboard using a console Use the JOptionPane class to get input from the keyboard using a graphical user interface 5. we will use the BufferedReader class found in the java. At the end of the lesson.E. let's make our programs more interactive by getting some input from the user. the first one is through the use of the BufferedReader class and the other one involves a graphical user interface by using JOptionPane. Add this at the top of your code: import java. and invoke the readLine() method to get input from the keyboard. In this section.in) ).2 Using BufferedReader to get input In this section.readLine().I 5 Getting Input from the Keyboard 5.1 Objectives Now that we've studied some basic concepts in Java and we've written some simple programs.io. Declare a temporary String variable to get the input. 2. Add this statement: BufferedReader dataIn = new BufferedReader( new InputStreamReader( System. Here are the steps to get input from the keyboard: 1.D. You have to type it inside a try-catch block. we'll be discussing two methods of getting input. try{ String temp = dataIn.println(“Error in getting input”).

out.IOException.io.BufferedReader. The statements can also be rewritten as. InputStreamReader and IOException which is inside the java.io. String name = "".IOException.I Here is the complete source code: import java.J. public class GetInputFromKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ). }catch( IOException e ){ System. the java.out. which will load all the classes found in the package. try{ name = dataIn.println("Error!"). The Java Application Programming Interface (API) contains hundreds of predefined classes that you can use in your programs. System. Just like in our example. import java.InputStreamReader.io package contains classes that allow programs to input and output data. import java.E. These classes are organized into what we call packages. and then we can use those classes inside our program.io.io. import java. import java. } Now let's try to explain each line of code: The statements. } } System.D.readLine().out.io. import java.io. Packages contain classes that have related purpose.io package.BufferedReader. import java. indicate that we want to use the classes BufferedReader.io.print("Please Enter Your Name:").println("Hello " + name +"!").*. Introduction to Programming I 101 .InputStreamReader.

try{ name = dataIn.I The next two statements.println("Error!"). We will cover more about this later in the course. System. BufferedReader dataIn = new BufferedReader(new InputStreamReader( System. the following block defines a try-catch block. Now.out.in) ). Now. Introduction to Programming I 102 .D.out. It is always good to initialize your variables as you declare them. public class GetInputFromKeyboard { public static void main( String[] args ){ were already discussed in the previous lesson. will be catched. We will cover more about exception handling in the latter part of this course. but for now.J. The variable name is initialized to an empty String "". we are declaring a variable named dataIn with the class type BufferedReader. This means we declare a class named GetInputFromKeyboard and we declare the main method. In the statement. The next line just outputs a String on the screen asking for the user's name.print("Please Enter Your Name:"). } This assures that the possible exceptions that could occur in the statement name = dataIn.readLine(). This is where we will store the input of the user.readLine().E. }catch( IOException e ){ System. we are declaring a String variable with the identifier name. String name = "". Don't worry about what the syntax means for now. just take note that you need to add this code in order to use the readLine() method of BufferedReader to get input from the user.

Introduction to Programming I 103 . gets input from the user and will return a String value. name = dataIn. dataIn.E.readLine(). System.out.J. This value will then be saved to our name variable.println("Hello " + name + "!"). which we will use in our final statement to greet the user.D.readLine(). the method call.I Now going back to the statement.

I 5.showInputDialog("Please enter your name").E.showMessageDialog(null. msg). name = JoptionPane. } Figure 5. JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. public class GetInputFromKeyboard { public static void main( String[] args ){ String name = "". String msg = "Hello " + name + "!".swing package.JOptionPane. JOptionPane. } This will output.D.3 Using JOptionPane to get input Another way to get input from the user is by using the JOptionPane class which is found in the javax.1: Getting Input Using JOptionPane Figure 5.J.3: Showing Message Using JOptionPane Introduction to Programming I 104 . import javax. Given the following code.swing.2: Input florence on the JOptionPane Figure 5.

The next line displays a dialog which contains a message and an OK button.showInputDialog("Please enter your name"). msg).swing package. name = JOptionPane. a textfield and an OK button as shown in the figure.showMessageDialog(null. import javax.I The first statement.D. which will display a dialog with a message. Introduction to Programming I 105 . String msg = "Hello " + name + "!". creates a JOptionPane input dialog.J. The statement. indicates that we want to import the class JOptionPane from the javax.*. JOptionPane. Now we create the welcome message.E. We can also write this as. which we will store in the msg variable.swing. import javax.JOptionPane. This returns a String which we will save in the name variable.swing.

4.1 Last 3 words (BufferedReader version) Using BufferedReader. ask for three words from the user and output those three words on the screen. For example.I 5.4.5: Second Input Figure 5.D.4 Exercises 5. For example.J. Enter word1:Goodbye Enter word2:and Enter word3:Hello Goodbye and Hello 5.2 Last 3 words (JOptionPane version) Using JOptionPane. Figure 5.6: Third Input Figure 5.E.7: Show Message Introduction to Programming I 106 .4: First Input Figure 5. ask for three words from the user and output those three words on the screen.

return) which allows redirection of program flow 6. for) which allow executing specific sections of code a number of times Use branching statements (break. At the end of the lesson. if( boolean_expression ) statement. The if-statement has the form. which allows us to change the ordering of how the statements in our programs are executed. statement2.I 6 Control Structures 6. or if( boolean_expression ){ statement1.J. In this section.E. } where.2 Decision Control Structures Decision control structures are Java statements that allows us to select and execute specific blocks of code while skipping other sections.D. Introduction to Programming I 107 . .2. the student should be able to: • • • Use decision control structures (if. else. we will be discussing control structures. . we have given examples of sequential programs.1 Objectives In the previous sections. .1 if statement The if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. wherein statements are executed one after another in a fixed order. do-while. boolean_expression is either a boolean expression or boolean variable. switch) which allows selection of specific sections of code to be executed Use repetition control structures (while. 6. continue.

if( grade > 60 ){ System. //statement2.println("Congratulations!").out. Indent the statements inside the if-block.println("You passed!").E.For example.out.println("Congratulations!"). int grade = 68. } Coding Guidelines: 1. } Introduction to Programming I 108 . if( boolean_expression ){ //statement1. 2. System. That means that the execution of the condition should either result to a value of true or a false. or int grade = 68.out.J.D. The boolean_expression part of a statement should evaluate to a boolean value.1: Flowchart of If-Statement if( grade > 60 ) System. given the code snippet. Figure 6.I For example.

. .out.println("Congratulations!"). } else{ System.out. else System. if( grade > 60 ) System.println("Sorry you failed"). if( grade > 60 ){ System.J. . } Introduction to Programming I 109 . statement2. or can also be written as.println("Sorry you failed"). and a different statement if the condition is false.out. } else{ statement1.2 if-else statement The if-else statement is used when we want to execute a certain statement if a condition is true. or int grade = 68.E. .D. . if( boolean_expression ) statement. The if-else statement has the form. int grade = 68.out. System.I 6. .2.out.println("Congratulations!"). else statement. if( boolean_expression ){ statement1. } For example. statement2. given the code snippet.println("You passed!").

.E. This means that you can have other if-else blocks inside another if-else block.D.. } } else{ .2: Flowchart of If-Else Statement Coding Guidelines: 1. To avoid confusion.For example.. if( boolean_expression ){ if( boolean_expression ){ . 2. You can have nested if-else blocks. always place the statement or statements of an if or if-else block inside brackets {}. } Introduction to Programming I 110 .J. .I Figure 6.

else if( boolean_expression2 ) statement2. else statement3.I 6. Figure 6. Take note that you can have many else-if blocks after an if-statement.2. if boolean_expression1 is true. The else-block is optional and can be omitted.3: Flowchart of If-Else-If Statement Introduction to Programming I 111 . then the program executes statement1 and skips the other statements. In the example shown above. If boolean_expression2 is true. if( boolean_expression1 ) statement1. The if-else if statement has the form.E. This cascading of structures allows us to make more complex selections.D.J. then the program executes statement 2 and skips to the statements following statement3.3 if-else-if statement The statement in the else-clause of an if-else block can be another if-else structures.

2. //WRONG int number = 0. if( number == 0 ){ //some statements here } 3.out. if( number ){ //some statements here } The variable number does not hold a Boolean value. } else if( grade > 60 ){ System. For example. The condition inside the if-statement does not evaluate to a boolean value.E. } else{ System. Introduction to Programming I 112 .J. if( number = 0 ){ //some statements here } This should be written as.println("Very good!"). //WRONG int number = 0. Using = instead of == for comparison. if( grade > 90 ){ System.out. Writing elseif instead of else if.println("Sorry you failed").D.I For example. For example.println("Very good!").out. } 6.4 Common Errors when using the if-else statements: 1. int grade = 68. given the code snippet. //CORRECT int number = 0.2.

0.E.out.out. } else if( (grade < 80) && (grade >= 60)){ System. } else if( (grade < 90) && (grade >= 80)){ System.out.out.J. you failed. } else{ System.2.D.println("Study harder!" )."). } } } Introduction to Programming I 113 .println( "Excellent!" ).5 Example for if-else-else if public class Grade { public static void main( String[] args ) { double grade = 92.println("Good job!" ).I 6.println("Sorry. if( grade >= 90 ){ System.

NOTES: • Unlike with the if statement. // break.2. . all the statements associated with that case are executed. case case_selector2: statement1.I 6. // statement2. the statements associated with the succeeding cases are also executed. and jumps to the case whose selector matches the value of the expression. //block 2 . Java first evaluates the switch_expression. switch( switch_expression ){ case case_selector1: statement1. Introduction to Programming I 114 . we use a break statement as our last statement. default: statement1. // statement2.D. . are unique integer or character constants. // break. // break. The switch construct allows branching on multiple outcomes. .E. .6 switch statement Another way to indicate a branch is through the switch keyword. . . } where. the multiple statements are executed in the switch statement without needing the curly braces. switch_expression is an integer or character expression and. case_selector2 and so on.J. //block n . The program executes the statements in order from that point on until a break statement is encountered. The switch statement has the form. • When a case in a switch statement has been matched. Take note however. • To prevent the program from executing statements in the subsequent cases. If none of the cases are satisfied. . skipping then to the first statement after the end of the switch structure. . that the default part is optional. the default block is executed. Not only that. . // statement2. When a switch is encountered. case_selector1. //block 1 . A switch statement can have no default block.

You can decide which to use. An if statement can be used to make decisions based on ranges of values or conditions. 2. Deciding whether to use an if statement or a switch statement is a judgment call.4: Flowchart of Switch Statements Introduction to Programming I 115 .J.E. Figure 6. based on readability and other factors.D. Also.I Coding Guidelines: 1. the value provided to each case statement must be unique. whereas a switch statement can make decisions based only on a single integer or character value.

J.E.D.I

6.2.7 Example for switch
public class Grade { public static void main( String[] args ) { int grade = 92; switch(grade){ case 100: System.out.println( "Excellent!" ); break; case 90: System.out.println("Good job!" ); break; case 80: System.out.println("Study harder!" ); break; default: System.out.println("Sorry, you failed."); }

}

}

Introduction to Programming I

116

J.E.D.I

6.3 Repetition Control Structures
Repetition control structures are Java statements that allows us to execute specific blocks of code a number of times. There are three types of repetition control structures, the while, do-while and for loops.

6.3.1 while loop
The while loop is a statement or block of statements that is repeated as long as some condition is satisfied. The while statement has the form, while( boolean_expression ){ statement1; statement2; . . . } The statements inside the while loop are executed as long as the boolean_expression evaluates to true. For example, given the code snippet, int i = 4; while ( i > 0 ){ System.out.print(i); i--; } The sample code shown will print 4321 containing the statement i--; is removed, that does not terminate. Therefore, when control structures, make sure that you add terminate at some point. on the screen. Take note that if the line this will result to an infinite loop, or a loop using while loops or any kind of repetition some statements that will allow your loop to

Introduction to Programming I

117

J.E.D.I

The following are other examples of while loops, Example 1: int x = 0; while (x<10) { System.out.println(x); x++; } Example 2: //infinite loop while(true) System.out.println(“hello”); Example 3: //no loops // statement is not even executed while (false) System.out.println(“hello”);

Introduction to Programming I

118

J.E.D.I

6.3.2 do-while loop
The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed several times as long as the condition is satisfied. The main difference between a while and do-while loop is that, the statements inside a do-while loop are executed at least once. The do-while statement has the form, do{ statement1; statement2; . . . }while( boolean_expression ); The statements inside the do-while loop are first executed, and then the condition in the boolean_expression part is evaluated. If this evaluates to true, the statements inside the do-while loop are executed again. Here are a few examples that uses the do-while loop: Example 1: int x = 0; do { System.out.println(x); x++; }while (x<10); This example will output 0123456789 on the screen. Example 2: //infinite loop do{ System.out.println(“hello”); } while (true); This example will result to an infinite loop, that prints hello on screen. Example 3: //one loop // statement is executed once do System.out.println(“hello”); while (false); This example will output hello on the screen.

Introduction to Programming I

119

J.E.D.I

Coding Guidelines: 1. Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after the while expression. do{ ... }while(boolean_expression) //WRONG->forgot semicolon ; 2. Just like in while loops, make sure that your do-while loops will terminate at some point.

6.3.3 for loop
The for loop, like the previous loops, allows execution of the same code a number of times. The for loop has the form, for (InitializationExpression; LoopCondition; StepExpression){ statement1; statement2; . . . } where, InitializationExpression -initializes the loop variable. LoopCondition - compares the loop variable to some limit value. StepExpression - updates the loop variable.

A simple example of the for loop is, int i; for( i = 0; i < 10; i++ ){ System.out.print(i); } In this example, the statement i=0, first initializes our variable. After that, the condition expression i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is executed. Next, the expression i++ is executed, and then the condition expression is again evaluated. This goes on and on, until the condition expression evaluates to false. This example, is equivalent to the while loop shown below, int i = 0; while( i < 10 ){ System.out.print(i); i++; }

Introduction to Programming I

120

J.E.D.I

6.4 Branching Statements
Branching statements allows us to redirect the flow of program execution. Java offers three branching statements: break, continue and return.

6.4.1 break statement
The break statement has two forms: unlabeled (we saw its unlabeled form in the switch statement) and labeled. 6.4.1.1 Unlabeled break statement The unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop. For example, String names[] = {"Beah", "Bianca", "Lance", "Belle", "Nico", "Yza", "Gem", "Ethan"}; String boolean searchName = "Yza"; foundName = false;

for( int i=0; i< names.length; i++ ){ if( names[i].equals( searchName )){ foundName = true; break; } } if( foundName ){ System.out.println( searchName + " found!" ); } else{ System.out.println( searchName + " not found." ); } In this example, if the search string "Yza" is found, the for loop will stop and flow of control transfers to the statement following the for loop.

Introduction to Programming I

121

J.E.D.I

6.4.1.2 Labeled break statement The labeled form of a break statement terminates an outer statement, which is identified by the label specified in the break statement. The following program searches for a value in a two-dimensional array. Two nested for loops traverse the array. When the value is found, a labeled break terminates the statement labeled search, which is the outer for loop. int[][] numbers = {{1, 2, 3}, {7, 8, 9}}; int searchNum = 5; boolean foundNum = false; searchLabel: for( int i=0; i<numbers.length; i++ ){ for( int j=0; j<numbers[i].length; j++ ){ if( searchNum == numbers[i][j] ){ foundNum = true; break searchLabel; } } } if( foundNum ){ System.out.println( searchNum + " found!" ); } else{ System.out.println( searchNum + " not found!" ); } The break statement terminates the labeled statement; it does not transfer the flow of control to the label. The flow of control transfers to the statement immediately following the labeled (terminated) statement. {4, 5, 6},

Introduction to Programming I

122

The following example counts the number of "Beah"s in the array. Introduction to Programming I 123 . outerLoop: for( int i=0.2.println("Inside for(i) loop").J.out.D. //message2 In this example.2. int count = 0.println("There are " + count + " Beahs in the list"). i++ ){ if( !names[i].1 Unlabeled continue statement The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. basically skipping the remainder of this iteration of the loop. "Lance". for( int i=0. //skip next statement } } count++. "Beah"}. You can use the continue statement to skip the current iteration of a for.println("Inside for(j) loop"). System. i<5. //message1 if( j == 2 ) continue outerLoop.length.E.out. String names[] = {"Beah".4. i<names. j++ ){ System. "Bianca".4. while or do-while loop.out. 6. message 2 never gets printed since we have the statement continue outerloop which skips the iteration. i++ ){ for( int j=0. } } System.4.2 continue statement The continue statement has two forms: unlabeled and labeled.equals("Beah") ){ continue.I 6. 6. j<5.2 Labeled continue statement The labeled form of the continue statement skips the current iteration of an outer loop marked with the given label.

J. Introduction to Programming I 124 .4.I 6. use the form of return that doesn't return a value.E. The flow of control returns to the statement that follows the original method call. return "Hello". We will cover more about return statements later when we discuss about methods. return. For example. For example. To return a value.D. simply put the value (or an expression that calculates the value) after the return keyword. The return statement has two forms: one that returns a value and one that doesn't. The data type of the value returned by return must match the type of the method's declared return value. or return ++count.3 return statement The return statement is used to exit from the current method. When a method is declared void.

If the user inputs a number that is not in the range.3 Hundred Times Create a program that prints your name a hundred times. Introduction to Programming I 125 . Together with the average. otherwise output :-(. 1.5. 2. 6.5 Exercises 6. Use a switch statement to solve this problem 6. and System. 6. a do-while loop and a for-loop. "Invalid number".D.5. Use BufferedReader to get input from the user. Output the average of the three exams. also include a smiley face in the output if the average is greater than or equal to 60.1 Grades Get three exam grades from the user and compute the average of the grades.I 6.out to output the result.J.5. Do three versions of this program using a while loop. and output the equivalent of the number in words. Use an if-else statement to solve this problem 2. output.E. Do three versions of this program using a while loop. 1.2 Number in words Get a number as input from the user.5. Use JOptionPane to get input from the user and to output the result. a do-while loop and a for-loop. The number inputted should range from 1-10.4 Powers Compute the power of a number given the base and exponent.

number3 = 3. Think of an array as a stretched variable – a location that still has one identifier name. divided into a number of slots. At the end of the lesson. but can hold more than one value. there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. int number2. we will be discussing about Java Arrays. we often use a unique identifier or name and a datatype. we have here three variables of type int with different identifiers for each variable. number1 = 1.2 Introduction to arrays In the previous sections. it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. and then we are going to discuss on how to declare and use them.1 Objectives In this section. As you can see. int number1. For example. This type of variable is called an array.1: Example of an Integer Array An array stores multiple data items of the same datatype. number2 = 2. Introduction to Programming I 126 . we have discussed on how to declare different variables using the primitive data types. int number3. In Java and other programming languages. the student should be able to: • • • • Declare and create arrays Access array elements Determine the number of elements in an array Declare and create multidimensional arrays 7. we call it by its identifier name.J.E. in a contiguous block of memory. In order to use the variable. Figure 7. First.D. In declaring variables.I 7 Java Arrays 7. we are going to define what arrays are.

2: Instantiating Arrays Introduction to Programming I 127 . We will cover more about instantiating objects and constructors later. the declaration tells the Java Compiler that the identifier ages will be used as the name of an array containing integers. This process in Java is called instantiation (the Java word for creates). After declaring. you list the data type. For example. we need to use a constructor for this. that the size of an array cannot be changed once you've initialized it. In the example. int ages[]. can also be written as. Instead of using the new keyword to instantiate an array. //declaration int ages[]. For example. or.3 Declaring Arrays Arrays must be declared like all variables. //instantiate object ages = new int[100]. or you can place the brackets after the identifier.E.J. construct and assign values at once. you can also automatically declare. //declare and instantiate object int ages[] = new int [100]. int []ages.I 7.D. For example. When declaring an array. In order to instantiate an object. and to create or instantiate a new array containing 100 elements. we must create the array and specify its length with a constructor statement. Figure 7. Take note. followed by the identifier name. followed by a set of square brackets[].

This array contains 4 elements that are //initialized to values {true. 90. false }. 75}. “Sat”. //creates an array of Strings with identifier days and //initialized.E. 80. “Wed”. “Thu”. true. This array contains 7 elements String days[] = { “Mon”. //creates an array of boolean variables with ientifier //results. 75}.I Examples are. false} boolean results[] ={ true. double []grades = {100.J. “Tue”. Introduction to Programming I 128 .D. true. 90. 80. false. //creates an array of 4 double variables initialized //to the values {100. “Sun”}. false. “Fri”.

given the array we declared a while ago. Take note that the elements inside your array is from 0 to (sizeOfArray-1).E. int []arr = new int[100]. i<100. is preferred over. They begin with zero and progress sequentially by whole numbers to the end of the array.print( ages[i] ). 3. i++ ){ System. Introduction to Programming I 129 . An index number or subscript is assigned to each member of the array. for( int i=0. you use a number called an index or a subscript. 2. } } Coding Guidelines: } 1. Therefore. The following is a sample code on how to print all the elements in the array. For example.print(ages[99]). so our code is shorter. Index numbers are always integers. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception.I 7.4 Accessing an array element To access an array element. You cannot resize an array. you must populate the String arrays explicitly. arr = new int[100]. the stored value of each member of the array will be initialized to zero for number data. public class ArraySample{ public static void main( String[] args ){ int[] ages = new int[100]. reference data types such as Strings are not initialized to blanks or an empty string “”.D.out.J. This uses a for loop. we have //assigns 10 to the first element in the array ages[0] = 10. However. It is usually better to initialize or instantiate the array right away after you declare it. allowing the program and the programmer to access individual values when necessary. //prints the last element in the array System. Take note that once an array is declared and constructed. The elements of an n-element array have indexes from 0 to n-1. int []arr. For example. the declaration.out. or a part of the array.

The length field of an array returns the size of the array. //declare a constant .length For example.length. given the previous example.. you can use the length field of an array.I 7. final int ARRAY_SIZE = 1000. It can be used by writing. When creating for loops to process the elements of an array. Declare the sizes of arrays in a Java program using named constants to make them easy to change.print( ages[i] ). } } Coding Guidelines: } 1. Introduction to Programming I 130 . For example. we can re-write it as. 2. use the array object's length field in the condition statement of the for loop. public class ArraySample { public static void main( String[] args ){ int[] ages = new int[100]. arrayName. This will allow the loop to adjust automatically for different-sized arrays.J.5 Array length In order to get the number of elements in an array. int[] ages = new int[ARRAY_SIZE]. i<ages.D.out. for( int i=0. i++ ){ System.E..

we write. { "fido". Introduction to Programming I 131 .I 7. Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. "black"} }.J.E. { "Kristin". To access an element in a multidimensional array is just the same as accessing the elements in a one dimensional array. to access the first element in the first row of the array dogs.6 Multidimensional Arrays Multidimensional arrays are implemented as arrays of arrays. { "toby". For example. // integer array 512 x 128 elements int[][] twoD = new int[512][128].print( dogs[0][0] ). "gray"}. This will print the String "terry" on the screen. "white" }. System. // String array 4 rows x 2 columns String[][] dogs = {{ "terry".D.out. "brown" }. For example. // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24].

"456-3322".7. print all the contents of the array. # : 456-3322 Address : Manila Introduction to Programming I 132 .E. {"Becca".I 7. "983-3333".J.D.2 Greatest number Using BufferedReader or JOptionPane. String days[] = {“Monday”. 7. For Example. Print the following entries on screen in the following format: Name : Florence Tel. # : 983-3333 Address : Quezon City Name : Becca Tel.7. "Manila"}. {"Joyce".7.}. Output on the screen the number with the greatest value. Using a while-loop. Use an array to store the values of these 10 numbers.1 Days of the Week Create an array of Strings which are initialized to the 7 days of the week. (do the same for do-while and forloop) 7.7 Exercises 7.3 Addressbook Entries Given the following multidimensional array that contains addressbook entries: String entry = {{"Florence". ask for 10 numbers from the user. # : 735-1234 Address : Manila Name : Joyce Tel. "Manila"}}. “Tuesday”…. "735-1234". "Quezon City"}.

Introduction to Programming I 133 . that sorts five numbers. suppose you have a Java application.2 Command-line arguments A Java application can accept any number of arguments from the command-line. called Sort.I 8 Command-line Arguments 8. Command-line arguments allow the user to affect the operation of an application for one invocation.E. you run it like this: Figure 8.1: Running with Command-Line Arguments Take note that the arguments are separated by spaces.1 Objectives In this section. the student should be able to: • • • Know and explain what a command-line argument is Get input from the user using command-line arguments Learn how to pass arguments to your programs in Netbeans 8. we will study on how to process input from the command-line by using arguments pass onto a Java program.D. For example.J. At the end of the lesson. The user enters command-line arguments when invoking the application and specifies them after the name of the class to run.

D. You can derive the number of command-line arguments with the array's length attribute. "3". int numberOfArgs = args. when you invoke an application. the command-line arguments passed to the Sort application is an array that contains five strings which are: "5".I In the Java language. such as "34". If your program needs to support a numeric command-line argument.parseInt(args[0]). the runtime system passes the command-line arguments to the application's main method via an array of Strings. always check if the number of arguments before accessing the array elements so that there will be no exception generated. For example. Remember the declaration for the main method. public static void main( String[] args ) The arguments that are passed to your program are saved into an array of String with the args identifier. Here's a code snippet that converts a command-line argument to an integer. if (args.E.length. "4". it must convert a String argument that represents a number. In the previous example.length > 0){ firstArg = Integer. "2" and "1". to a number. } parseInt throws a NumberFormatException (ERROR) if the format of args[0] isn't valid (not a number). Introduction to Programming I 134 . Each String in the array contains one of the command-line arguments. Coding Guidelines: Before using command-line arguments.J. int firstArg = 0.

3 Command-line arguments in Netbeans To illustrate on how to pass some arguments to your programs in Netbeans. Now.println("First Argument="+ args[0]).out.I 8. Click on Projects (encircled below). Figure 8. Copy the code shown above and compile the code. System. } } Now.out.D.2: Opening Project File Introduction to Programming I 135 .println("Number of arguments=" + args.J. public class CommandLineExample { public static void main( String[] args ){ System. run netbeans and create a new project and name this CommandLineExample. let us create a Java program that will print the number of arguments and the first argument passed to it.E. follow these steps to pass arguments to your program using Netbeans.length).

and a popup menu will appear.4: Properties Dialog Introduction to Programming I 136 .J. Figure 8.I Right-click on the CommandLineExample icon. Click on Properties.D. Figure 8.3: Opening Properties The Project Properties dialog will then appear.E.

type the arguments you want to pass to your program.E.5: Click On Running Project On the Arguments textbox.D. Figure 8. Then. In this case we typed in the arguments 5 4 3 2 1. click on Run-> Running Project. click on the OK button.I Now. Figure 8.J.6: Set the Command-Line Arguments Introduction to Programming I 137 .

I Now try to RUN your program.D. the output to your program is the number of arguments which is 5.7: Running the Program in with the Shortcut Button As you can see here. Figure 8. and the first argument which is 5.E. Figure 8.8: Program Output Introduction to Programming I 138 .J.

4 Exercises 8. product and quotient of the two numbers.J. For example. difference.4. if the user entered. java ArithmeticOperation 20 4 your program should print sum = 24 difference = 16 product = 80 quotient = 5 Introduction to Programming I 139 . java Hello world that is all your program should print Hello world that is all 8.I 8.D.1 Print arguments Get input from the user using command-line arguments and print all the arguments to the screen.4.2 Arithmetic Operations Get two numbers from the user using command-line arguments and print sum.E. if the user entered. For example.

Comparison. people and so on. At the end of the lesson. These objects are characterized by their properties (or attributes) and behaviors. braking and accelerating. we will discuss later on how to create your own classes. Later on. such as cars.E. we will introduce some basic concepts of object-oriented programming. For example. type of transmission.D. the student should be able to: • • • • • • • Explain object-oriented programming and some of its concepts Differentiate between classes and objects Differentiate between instance variables/methods and class(static) variables/methods Explain what methods are and how to call and pass parameters to methods Identify the scope of a variable Cast primitive data types and objects Compare objects and determine the class of an objects 9. we can define different properties and behavior of a lion.1 Objectives In this section. For now. we can find many objects around us.I 9 Working with the Java Class Library 9. Please refer to the table below for the examples. Object Car Properties type of transmission manufacturer color Weight Color hungry or not hungry tamed or wild Table 17: Example of Real-life Objects Behavior turning braking accelerating roaring sleeping hunting Lion Introduction to Programming I 140 .2 Introduction to Object-Oriented Programming Object-Oriented programming or OOP revolves around the concept of objects as the basic elements of your programs. a car object has the properties. we will discuss the concept of classes and objects. and how to use these classes and their members. lion. When we compare this to the physical world. conversion and casting of objects will also be covered. we will focus on using classes that are already defined in the Java class library.J. Its behaviors are turning. manufacturer and color. Similarly.

Car Class Instance Variables Plate Number Color Manufacturer Current Speed Blue Object Car A ABC 111 Mitsubishi 50 km/h Accelerate Method Turn Method Brake Method Table 18: Example of Car class and its objects Object Car B XYZ 123 Red Toyota 100 km/h When instantiated. let us discuss an example. and it also consists of a set of methods (behavior) that describes how an object behaves.D. an object is a software bundle of variables and related methods. and current speed which are filled-up with corresponding values in objects Car A and Car B. Each object is composed of a set of data (properties/attributes) which are variables describing the essential characteristics of the object. manufacturer. the method implementations are shared among objects of the same class. Introduction to Programming I Instance Methods 141 . Software programmers can use a class over and over again to create many objects. 9. color. Fields specifiy the data types defined by the class. while methods specify the operations. Turn and Brake. However. The variables and methods in a Java object are formally known as instance variables and instance methods to distinguish them from class variables and class methods. The class is the fundamental structure in object-oriented programming. which will be discussed later. To differentiate between classes and objects. It can be thought of as a template.E. the objects in the physical world can easily be modeled as software objects using the properties as data and the behaviors as methods. It consists of two types of members which are called fields (properties or attributes) and methods.1 Difference Between Classes and Objects In the software world. each object gets a fresh set of state variables.J.3 Classes and Objects 9. Thus. In the table shown below. An object is an instance of the class. a prototype or a blueprint of an object. Car A and Car B are objects of the Car class.I With these descriptions. an object is a software component whose structure is similar to objects in the real world. Classes provide the benefit of reusability. What we have here is a Car Class which can be used to define several Car Objects.3. The Car has also some methods Accelerate. The class has fields plate number. These data and methods could even be used in programming games or interactive software to simulate the real-world objects! An example would be a car software object in a racing game or a lion software object in an educational interactive software zoo for kids.

They are also called static member variables. it is also possible to define class variables. To clearly describe class variables. 9. By placing a boundary around the properties and methods of our objects. This means that it has the same value for all the objects in the same class. all of the objects of the Car class will have the value 2 for their Count variable.3. which are variables that belong to the whole class.J.D. We will learn more about how Java implements encapsulation as we discuss more about classes. let's go back to our Car class example. we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways. If we change the value of Count to 2. Suppose that our Car class has one class variable called Count.3. Car Class Instance Variables Plate Number Color Manufacturer Current Speed Blue Mitsubishi 50 km/h Count = 2 Accelerate Method Turn Method Brake Method Table 19: Car class' methods and variables Object Car A ABC 111 Red Toyota Object Car B XYZ 123 100 km/h Introduction to Programming I Instance Methods Variable Class 142 . We can prevent access to our object's data by declaring them declaring them in a certain way such that we can control access to them.2 Encapsulation Encapsulation is the method of hiding certain elements of the implementation of a certain class.I 9.E.3 Class Variables and Methods In addition to the instance variables.

I 9. you actually invoke the class' constructor. Figure 9. When you create an object. str2 = new String(“Hello world!”).4 Class Instantiation To create an object or an instance of a class. String str2 = "Hello". String or also equivalent to. if you want to create an instance of the class String.3.E.1: Classs Instantiation The new operator allocates a memory for that object and returns a reference of that memory location to you. The constructor is a method where you place all the initializations. Introduction to Programming I 143 .D. we write the following code. it has the same name as the class. For example.J. we use the new operator.

and that is the main() method. it goes back to the method that called it. Taking a problem and breaking it into small.4 Methods 9. why do we need to create methods? Why don't we just place all the code inside one big method? The heart of effective problem solving is in problem decomposition. In Java. Introduction to Programming I 144 . We can do this in Java by creating methods to solve a specific part of the problem. • After the method has finished execution.J. we only have one method.D. we can define many methods which we can call from different methods. A method is a separate piece of code that can be called by a main program or any other method to perform some specific function.I 9.E. The following are characteristics of methods: • It can return one or no values • It may accept as many parameters it needs or no parameter at all. Now. manageable pieces is critical to writing large programs.1 What are Methods and Why Use Methods? In the examples we discussed before.4. Parameters are also called function arguments.

E. String char String str1 = "Hello". Two strings are considered equal ignoring case if they are of the same length. The first character of the sequence is at index 0. nameOfObject.4. Table 20: Sample Methods of class String Using the methods. Later on.equalsIgnoreCase( str1 ).J. public boolean equalsIgnoreCase Compares this String to another String. ignoring (String anotherString) case considerations. Method declaration public char charAt(int index) Definition Returns the character at the specified index. we will create our own methods.nameOfMethod( parameters ). and corresponding characters in the two strings are equal ignoring case. we write the following. Let's take two sample methods found in the class String. and so on.I 9. to illustrate how to call methods. let's use the String class as an example. You can use the Java API documentation to see all the available methods in the String class. as for array indexing. To call an instance method.charAt(0). //this will return a boolean value true boolean result = str1. Introduction to Programming I 145 .D.2 Calling Instance Methods and Passing Variables Now. //will return the character H //and store it to variable x str2 = "hello". the next at index 1.1. An index ranges from 0 to length() . let us use what is available. x = str2. but for now.

pass-byreference. //call method test //and pass i to method test test( i ).I 9. Pass i as parameter which is copied to j } //print the value of i.J. it will not affect the variable value if i in main since it is a different copy of the variable.4. The method cannot accidentally modify the original argument even if it modifies the parameters during calculations.1 Pass-by-value When a pass-by-value occurs. we called the method test and passed the value of i as parameter. Introduction to Programming I 146 . we already tried passing variables to methods.out.E.3. By default.println( i ). //print the value of i System. } In the given example. Since j is the variable changed in the test method. 9.out. However. i not changed System.println( i ).3 Passing Variables in Methods In our examples. all primitive data types when passed to a method are pass-by-value. The value of i is copied to the variable of the method j. } public static void test( int j ){ //change value of parameter j j = 33. For example. public class TestPassByValue { public static void main( String[] args ){ int i = 10. the method makes a copy of the value of the variable passed to the method. we haven't differentiated between the different types of variable passing in Java.D. the first one is pass-by-value and then.4. There are two types of passing data to methods.

out. 12}. the method can modify the actual object that the reference is pointing to. However.J. } //call test and pass reference to array test( ages ). the reference to an object is passed to the calling method. } } public static void test( int[] arr ){ //change values of array for( int i=0.out. the method makes a copy of the reference of the variable passed to the method. the location of the data they are pointing to is the same.length. This means that.3. i++ ){ System. For example. } } Introduction to Programming I 147 . 11. since.4. Pass ages as parameter which is copied to variable arr } //print array values again for( int i=0.length.E.I 9. i<ages. unlike in pass-by-value.println( ages[i] ). i<ages. class TestPassByReference { public static void main( String[] args ){ //create an array of integers int []ages = {10. i++ ){ arr[i] = i + 50. i++ ){ System. although different references are used in the methods.println( ages[i] ). i<arr.length. //print array values for( int i=0.2 Pass-by-reference When a pass-by-reference occurs.D.

D.println(“Hello world”). Examples of static methods.out. //prints data to screen System. to an integer int i = Integer.J.parseInt(“10”). //Returns a String representation of the integer argument as an //unsigned integer base 16 String hexEquivalent = Integer. 9. Classname. Static methods are distinguished from instance methods in a class definition by the keyword static. Static methods belongs to the class as a whole and not to a certain instance (or object) of a class. you cannot write a standard swap method to swap objects. Introduction to Programming I 148 .4 Calling Static Methods Static methods are methods that can be invoked without instantiating a class (means without invoking the new keyword). Take note that Java manipulates objects 'by reference.4. //converts the String 10. just type.staticMethodName(params).E.2: Pass-by-reference example Coding Guidelines: A common misconception about pass-by-reference in Java is when creating a swap method using Java references.'" As a result.' but it passes object references to methods 'by value.toHexString( 10 ). To call a static method. we've used so far in our examples are.I Figure 9.

E.. they are visible (i. The scope is determined by where the variable declaration is placed in the program. If you declare variables in the outer block. and the inner curly braces is called inner blocks.D and E. n = 0. m is D. k is C. Given the variables i. public class ScopeExample { public static void main( String[] args ){ int i = 0.j. int j = 0. The outer curly braces is called the outer blocks. int k = 0.m and n. //. The scope determines where in the program the variable is accessible. For example.}.D.5 Scope of a variable In addition to a variable's data type and name.C.J.. you cannot expect the outer block to see it.k. m = 0. starting from the point where it is declared. To simplify things. and the five scopes A. if you declare variables in the inner block. we have the following scopes for each variable: The The The The The scope scope scope scope scope of of of of of variable variable variable variable variable i is A. some code here B A { int int E } } The code we have here represents five scopes indicated by the lines and the letters representing the scope.B. D C Introduction to Programming I 149 . However. just think of the scope as anything between the curly braces {. usable) by the program lines inside the inner blocks. given the following code snippet. A variable's scope is inside the block where it is declared. The scope also determines the lifetime of a variable or how long the variable can exist in memory.e. a variable has scope.. n is E.4.. and in the inner blocks. j is B.I 9.

//print array values for( int i=0. ages[] . } B A C } E } public static void test( int[] arr ){ //change values of array for( int i=0. i<arr. given the two methods main and test in our previous examples. } } D In the main method.D. } //call test and pass reference to array test( ages ).length.out.scope E Introduction to Programming I 150 .scope B i in C – scope C In the test method. arr[] i in E .println( ages[i] ). class TestPassByReference { public static void main( String[] args ){ //create an array of integers int []ages = {10. i++ ){ arr[i] = i + 50. //print array values again for( int i=0.out. i++ ){ System.I Now. i++ ){ System.println( ages[i] ). the scope ofthe variables are. 11.J.length. the scope of the variables are. i<ages. 12}.length.scope A i in B .E.scope D . i<ages.

For the second System. System. it prints the value of the first test variable since it is the variable seen at that scope. Coding Guidelines: Avoid having variables of the same name declared inside one method to avoid confusion.J..out. your compiler will generate an error since you should have unique names for your variables in one block.print is invoke. } When the first System.out. Introduction to Programming I 151 . int test = 0. //.out.out. int test = 20. However. only one variable with a given identifier or name can be declared in a scope.E. { } int test = 10. you can have two variables of the same name. System. For example.D. That means that if you have the following declaration. if they are not declared in the same block.print( test ).print.print( test ). the value 20 is printed since it is the closest test variable seen at that scope.I When declaring variables.some code here { int test = 20.

System. and Java adopted this as part of its character support. Converting and Comparing Objects In this section. double numDouble = numInt.I 9.print( valInt ).5 Casting. 9. the cast (char)i produces the character value 'A'.E.1 Casting Primitive Types Casting between primitive types enables you to convert the value of one data from one type to another primitive type. The numeric code associated with a capital A is 65. and that is the boolean data type. A character can be used as an int because each character has a corresponding numeric code that represents its position in the character set. An example of typecasting is when you want to store an integer data to a variable of data type double. int valInt = valChar.D.5. If the variable i has the value 65. char valChar = 'A'. //explicit cast: output 65 Introduction to Programming I 152 . We will also learn how to convert primitive data types to objects and vice versa. we are going to learn how to compare objects. //implicit cast In this example. we are going to learn how to do typecasting. This commonly occurs between numeric types. For example. And finally. int numInt = 10. Typecasting or casting is the process of converting a data of a certain data type to another data type. the data is implicitly casted to data type double. For example.out. since the destination variable (double) holds a larger value than what we will place inside it. There is one primitive data type that we cannot do casting though. Another example is when we want to typecast an int to a char value or vice versa.J. according to the ASCII character set.

E. For example. double valDouble = 10. dataType. int int result = (int)(x/y). we must use an explicit cast. //convert valDouble to int type double x = 10.I When we convert a data that has a large type to a smaller type. int valInt = (int)valDouble. is an expression that results in the value of the source type.12. is the name of the data type you're converting to value. int y = 2.J.2. Explicit casts take the following form: (dataType)value where. //typecast result of operation to Introduction to Programming I 153 .D.

but you gain all the methods and variables that the subclass defines. There is a catch. We'll cover more about inheritance later. some objects might not need to be cast explicitly. You can pass an instance of any class for the Object argument because all Java classes are subclasses of Object.J. You won't lose any information in the cast. Introduction to Programming I 154 . one of type Object and another of type Window. because a subclass contains all the same information as its superclass. This is true anywhere in a program. To use superclass objects where subclass objects are expected. To cast an object to another class. If you had a variable defined as class Window. consider a method that takes two arguments. (classname)object where.2 Casting Objects Instances of classes also can be cast into instances of other classes. For example. however: Because subclasses contain more behavior than their superclasses. is a reference to the source object. is the name of the destination class object. you can use an instance of a subclass anywhere a superclass is expected. there's a loss in precision involved. For example. you must cast them explicitly. For the Window argument. you use the same operation as for primitive types: To cast. Analogous to converting a primitive value to a larger type. Errors occur if you try to call methods that the destination object doesn't have.I 9.5. not just inside method calls. such as Dialog. In particular. if you have an operation that calls methods in objects of the class Integer. Figure 9.D. and Frame. FileDialog. you can pass in its subclasses. with one restriction: The source and destination classes must be related by inheritance.3: Sample Class Hierarchy This is true in the reverse. Those superclass objects might not have all the behavior needed to act in place of a subclass object. you could assign objects of that class or any of its subclasses to that variable without casting.E. one class must be a subclass of the other. and you can use a superclass when a subclass is expected. classname. using an object of class Number won't include many methods specified in Integer.

J. VicePresident veep = new VicePresident().I • Note: that casting creates a reference to the old object of the type classname. // no cast needed for upward use veep = (VicePresident)emp. // must cast explicitlyCasting Introduction to Programming I 155 . the old object continues to exist as it did before. emp = veep.E. which here defines that the VicePresident has executive washroom privileges.D. VicePresident is a subclass of Employee with more information. Figure 9. Employee emp = new Employee().4: Class Hierarchy for superclass Employee The following example casts an instance of the class VicePresident to an instance of the class Employee.

lang package includes classes that correspond to each primitive data type: Float. the java. Byte.D. or vice versa. Double instead of double. //The following statement converts an Integer object to // its primitive data type int. As an alternative.I 9. and the like). Boolean. and you can't automatically cast between the two or use them interchangeably. which is used in method definitions to indicate that the method does not return a value. Most of these classes have the same names as the data types. // A common translation you need in programs // is converting a String to a numeric type. Examples: //The following statement creates an instance of the Integer // class with the integer value 7801 (primitive -> Object) Integer dataCount = new Integer(7801).E. two classes have names that differ from the corresponding data type: Character is used for char variables and Integer for int variables.intValue(). except that the class names begin with a capital letter (Short instead of short. such as an int // Object->primitive String pennsylvania = "65000". (Called Wrapper Classes) Java treats the data types and their class versions very differently.J. Introduction to Programming I 156 . It's a placeholder for the void keyword. Primitive types and objects are very different things in Java. so there's no reason it would be used when translating between primitive values and objects. you can create an object that holds the same value. and a program won't compile successfully if you use one when the other is expected. Also.parseInt(pennsylvania). • CAUTION: The Void class represents nothing in Java.3 Converting Primitive Types to Objects and Vice Versa One thing you can't do under any circumstance is cast from an object to a primitive data type. int penn = Integer. The result is an int with //value 7801 int newCount = dataCount. and so on.5. Using the classes that correspond to each primitive type.

J.E.D.I

9.5.4 Comparing Objects
In our previous discussions, we learned about operators for comparing values—equal, not equal, less than, and so on. Most of these operators work only on primitive types, not on objects. If you try to use other values as operands, the Java compiler produces errors. The exceptions to this rule are the operators for equality: == (equal) and != (not equal). When applied to objects, these operators don't do what you might first expect. Instead of checking whether one object has the same value as the other object, they determine whether both sides of the operator refer to the same object. To compare instances of a class and have meaningful results, you must implement special methods in your class and call those methods. A good example of this is the String class. It is possible to have two different String objects that contain the same values. If you were to employ the == operator to compare these objects, however, they would be considered unequal. Although their contents match, they are not the same object. To see whether two String objects have matching values, a method of the class called equals() is used. The method tests each character in the string and returns true if the two strings have the same values. The following code illustrates this, class EqualsTest { public static void main(String[] arguments) { String str1, str2; str1 = "Free the bound periodicals."; str2 = str1; System.out.println("String1: " + str1); System.out.println("String2: " + str2); System.out.println("Same object? " + (str1 == str2)); str2 = new String(str1); System.out.println("String1: " + str1); System.out.println("String2: " + str2); System.out.println("Same object? " + (str1 == str2)); System.out.println("Same value? " + str1.equals(str2));

}

}

This program's output is as follows, OUTPUT: String1: Free the bound String2: Free the bound Same object? true String1: Free the bound String2: Free the bound Same object? false Same value? True periodicals. periodicals. periodicals. periodicals.

Introduction to Programming I

157

J.E.D.I

Now let's discuss the code. String str1, str2; str1 = "Free the bound periodicals.";

Figure 9.5: Both references point to the same object

The first part of this program declares two variables (str1 and str2), assigns the literal "Free the bound periodicals." to str1, and then assigns that value to str2. As you learned earlier, str1 and str2 now point to the same object, and the equality test proves that. str2 = new String(str1); In the second part of this program, you create a new String object with the same value as str1 and assign str2 to that new String object. Now you have two different string objects in str1 and str2, both with the same value. Testing them to see whether they're the same object by using the == operator returns the expected answer: false—they are not the same object in memory. Testing them using the equals() method also returns the expected answer: true—they have the same values.

Figure 9.6: References now point to different objects

NOTE: Why can't you just use another literal when you change str2, rather than using new? String literals are optimized in Java; if you create a string using a literal and then use another literal with the same characters, Java knows enough to give you the first String object back. Both strings are the same objects; you have to go out of your way to create two separate objects.

Introduction to Programming I

158

J.E.D.I

9.5.5 Determining the Class of an Object
Want to find out what an object's class is? Here's the way to do it for an object assigned to the variable key: 1. The getClass() method returns a Class object (where Class is itself a class) that has a method called getName(). In turn, getName() returns a string representing the name of the class. For Example, String name = key.getClass().getName(); 2. The instanceOf operator The instanceOf has two operands: a reference to an object on the left and a class name on the right. The expression returns true or false based on whether the object is an instance of the named class or any of that class's subclasses. For Example, boolean ex1 = "Texas" instanceof String; // true Object pt = new Point(10, 10); boolean ex2 = pt instanceof String; // false

Introduction to Programming I

159

J.E.D.I

9.6 Exercises
9.6.1 Defining terms
In 1. 2. 3. 4. 5. 6. 7. your own words, define the following terms: Class Object Instantiate Instance Variable Instance Method Class Variables or static member variables Constructor

9.6.2 Java Scavenger Hunt
Pipoy is a newbie in the Java programming language. He just heard that there are already ready-to-use APIs in Java that one could use in their programs, and he's eager to try them out. The problem is, Pipoy does not have a copy of the Java Documentation, and he also doesn't have an internet access, so there's no way for him to view the Java APIs. Your task is to help Pipoy look for the APIs (Application Programming Interface). You should state the class where the method belongs, the method declaration and a sample usage of the said method. For example, if Pipoy wants to know the method that converts a String to integer, your answer should be: Class: Integer Method Declaration: public static int parseInt( String value ) Sample Usage: String strValue = "100"; int value = Integer.parseInt( strValue ); Make sure that the snippet of code you write in your sample usage compiles and outputs the correct answer, so as not to confuse Pipoy. (Hint: All methods are in the java.lang package). In cases where you can find more methods that can accomplish the task, give only one. Now let's start the search! 1. Look for a method that checks if a certain String ends with a certain suffix. For example, if the given string is "Hello", the method should return true the suffix given is "lo", and false if the given suffix is "alp". 2. Look for the method that determines the character representation for a specific digit in the specified radix. For example, if the input digit is 15, and the radix is 16, the method would return the character F, since F is the hexadecimal representation for the number 15 (base 10). 3. Look for the method that terminates the currently running Java Virtual Machine 4. Look for the method that gets the floor of a double value. For example, if I input a 3.13, the method should return the value 3. 5. Look for the method that determines if a certain character is a digit. For example, if I input '3', it returns the value true.

Introduction to Programming I

160

J.E.D.I

10 Creating your own Classes
10.1 Objectives
Now that we've studied on how to use existing classes from the Java class library, we will now be studying on how to write our own classes. For this section, in order to easily understand how to create classes, we will make a sample class wherein we will add more data and functionality as we go along the way. We will create a class that contains information of a Student and operations needed for a certain student record. Things to take note of for the syntax defined in this section and for the other sections: * <description> [] - means that there may be 0 or more occurrences of the line whereit was applied to. - indicates that you have to substitute an actual value for this part instead of typing it as it is. - indicates that this part is optional

At the end of the lesson, the student should be able to: • • • • • • Create their own classes Declare attributes and methods for their classes Use the this reference to access instance data Create and call overloaded methods Import and create packages Use access modifiers to control access to class members

Introduction to Programming I

161

J.E.D.I

10.2 Defining your own classes
Before writing your class, think first on where you will be using your class and how your class will be used. Think of an appropriate name for the class, and list all the information or properties that you want your class to contain. Also list down the methods that you will be using for your class. To define a class, we write, <modifier> class <name> { <attributeDeclaration>* <constructorDeclaration>* <methodDeclaration>* }

where <modifier> is an access modifier, which may be combined with other types of modifier. Coding Guidelines: Remember that for a top-level class, the only valid access modifiers are public and package (i.e., if no access modifier prefixes the class keyword). In this section, we will be creating a class that will contain a student record. Since we've already identified the purpose of our class, we can now name it. An appropriate name for our class would be StudentRecord. Now, to define our class we write, public class StudentRecord { //we'll add more code here later } where, public class StudentRecord Coding Guidelines: 1. Think of an appropriate name for your class. Don't just call your class XYZ or any random names you can think of. 2. Class names should start with a CAPITAL letter. 3. The filename of your class should have the SAME NAME as your class name. - means that our class is accessible to other classes outside the package - this is the keyword used to create a class in Java - a unique identifier that describes our class

Introduction to Programming I

162

J.E.D.I

10.3 Declaring Attributes
To declare a certain attribute for our class, we write, <modifier> <type> <name> [= <default_value>]; Now, let us write down the list of attributes that a student record can contain. For each information, also list what data types would be appropriate to use. For example, you don't want to have a data type int for a student's name, or a String for a student's grade. The following are some sample information we want to add to the student record. name address age math grade english grade science grade average grade String String int double double double double

You can add more information if you want to, it's all really up to you. But for this example, we will be using these information.

10.3.1 Instance Variables
Now that we have a list of all the attributes we want to add to our class, let us now add them to our code. Since we want these attributes to be unique for each object (or for each student), we should declare them as instance variables. For example, public class StudentRecord { private String name; private String address; private int age; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; //we'll add more code here later }

where, private here means that the variables are only accessible within the class. Other objects cannot access these variables directly. We will cover more about accessibility later. Coding Guidelines: 1. Declare all your instance variables on the top of the class declaration. 2. Declare one variable for each line. 3. Instance variables, like any other variables should start with a SMALL letter. 4. Use an appropriate data type for each variable you declare. 5. Declare instance variables as private so that only class methods can access them directly.

Introduction to Programming I

163

public class StudentRecord { private String name. } //we'll add more code here later we use the keyword static to indicate that a variable is a static variable.E. private String address. private int age. <modifier> <returnType> <name>(<parameter>*) { <statement>* } where.3.4 Declaring Methods Before we discuss what methods we want our class to have. public class StudentRecord { //instance variables we have declared private static int studentCount. So far. <modifier> can carry a number of different modifiers <returnType> can be any data type (including void) <name> can be any valid identifier <parameter> ::= <parameter_type> <parameter_name>[.I 10. private double englishGrade. private static int studentCount. To declare methods we write. private double average. private double scienceGrade. let us first take a look at the general syntax for declaring methods. } //we'll add more code here later 10. we can also declare class variables or variables that belong to the class as a whole.2 Class Variables or Static Variables Aside from instance variables. Let us call this as studentCount. The value of these variables are the same for all the objects of the same class. our whole code now looks like this. Now suppose. private double mathGrade. To declare a static variable. we want to know the total number of student records we have for the whole class.D.] Introduction to Programming I 164 .J. we can declare one static variable that will hold this value.

Take note that the return type of the method should have the same data type as the data in the return statement. Accessor methods are used to read values from class variables (instance/static). there are times wherein we want other objects to access private data. we don't want any objects to just access our data anytime.is the return type of the method. return name. we want an accessor method that can read the name.J. math grade and science grade of the student.E.D. It also returns a value.String return age. public class StudentRecord { private String name. we create accessor methods. In order to do this. public String getName () The statement. : : public String getName(){ return name.4.this means that our method does not have any parameters where.lang. However. we declare the fields or attributes of our classes as private.1 Accessor methods In order to implement encapsulation. Now let's take a look at one implementation of an accessor method. in our program signifies that it will return the value of the instance variable name to the calling method. english grade.the name of the method . You usually encounter the following error if the two does not have the same data type. For our example. StudentRecord. address.java:14: incompatible types found : int required: java.means that the method can be called from objects outside the class . ^ 1 error Introduction to Programming I 165 . that is. An accessor method usually starts with a get<NameOfInstanceVariable>. } } . This means that the method should return a value of type String .I 10.

} The getAverage method computes the average of the 3 grades and returns the result.D. public class StudentRecord { private String name. what if we want other objects to alter our data? What we do is we provide methods that can write or change values of our class variables (instance/static). assigns the value of temp to name and thus changes the data inside the instance variable name. } } where. public class StudentRecord { private String name. : : public double getAverage(){ double result = 0. name = temp.J. means that the method can be called from objects outside the class imeans that the method does not return any value the name of the method parameter that will be used inside our method Introduction to Programming I 166 . We call these methods. 10. Take note that mutator methods don't return values. mutator methods. : : public void setName( String temp ){ name = temp. public void setName (String temp) The statement. A mutator method is usuallyu written as set<NameOfInstanceVariable>.E.2 Mutator Methods Now. it contains some program argument or arguments that will be used inside the method. However. result = ( mathGrade+englishGrade+scienceGrade )/3.4. Now let's take a look at one implementation of a mutator method. } return result.I Another example of an accessor method is the getAverage method.

Method names should be verbs 3. Coding Guidelines: 1.J. 2. For example. 10.E. Method names should start with a SMALL letter. Please see example. getStudentCount will always return the value zero since we haven't done anything yet in our program in order to set its value. if( num == 1 return } else if( num return } ){ "one".is the return type of the method. we can create a static method to access its value. public String getNumberInWords( int num ){ String defaultNum = "zero".this means that our method does not have any parameters For now. public class StudentRecord { private static int studentCount.[methodName].3 Multiple Return statements You can have multiple return statements for a method as long as they are not on the same block. } } where. [ClassName]. //return a constant } //return a variable return defaultNum.means that the method is static and should be called by typing.the name of the method .means that the method can be called from objects outside the class . public static int getStudentCount () . Introduction to Programming I 167 .4.4.I 10. This means that the method should return a value of type int . You can also use constants to return values instead of variables. we call the method StudentRecord. For example. Always provide documentation before the declaration of the method.D. We will try to change the value of studentCount later on when we discuss constructors. in this case. You can use javadocs style for this.4 Static methods For the static variable studentCount.getStudentCount() . consider the method. public static int getStudentCount(){ return studentCount. //return a constant == 2){ "two".

J. result = ( mathGrade+englishGrade+scienceGrade )/3.4. } /** * Changes the name of the student */ public void setName( String temp ){ name = temp. /** * Computes the average of the english.D. math and science * grades */ public double getAverage(){ double result = 0. average. public class { private private private private private private private StudentRecord String String int double double double double name.E. } Introduction to Programming I 168 .. mathGrade.I 10. scienceGrade. } // other code here . /** * Returns the name of the student */ public String getName(){ return name.. private static int studentCount. } return result.. address. age. englishGrade. } /** * returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount.5 Sample Source Code for StudentRecord class Here is the code for our StudentRecord class.

out.println( annaRecord. crisRecord.getStudentCount } record StudentRecord(). } The output of this program is.setName("Beah"). here's a sample code of a class that uses our StudentRecord class. beahRecord. StudentRecord(). public class StudentRecordExample { public static void main( String[] args ){ //create three objects for Student StudentRecord annaRecord = new StudentRecord beahRecord = new StudentRecord crisRecord = new //set the name of the students annaRecord.println("Count="+StudentRecord. //print anna's name System.E.I Now.setName("Anna"). StudentRecord().out.getName() ).J.D. //print number of students System. ()). Anna Student Count = 0 Introduction to Programming I 169 .setName("Cris").

Since the parameter age is the closest declaration to the method. public void setAge( int age ){ this. public void setAge( int age ){ age = age.D.J. NOTE: You can only use the this reference for instance variables and NOT static or class variables.<nameOfTheInstanceVariable> So for example. } This method will then assign the value of the parameter age to the instance variable of the object StudentRecord. the value of the parameter age will be used.E. So in the statement. To use the this reference. we use the this reference. we are just assigning the value of the parameter age to itself! This is not what we want to happen in our code. let's take for example the setAge method.I 10. age = age. we can now rewrite our code to. we type. Suppose we have the following declaration for setAge.5 The this reference The this reference is used to access the instance variables shadowed by the parameters. which has the same name as the instance variable age. //WRONG!!! } The parameter name in this declaration is age. Introduction to Programming I 170 . this. To understand this better. In order to correct this mistake.age = age.

For example.println("Address:" + address). System. double sGrade) System.6 Overloading Methods In our classes. However. System. For example. we want the print method to print things differently depending on the parameters we pass to it. System. we want the print method to print out the name. address and age of the student. we want the method to print the student's name and grades. public void print( String temp ){ System.println("Math Grade:" + mGrade). System.println("Name:" + name). Method overloading allows a method with the same name but different parameters. System.println("English Grade:" + eGrade).I 10. When we pass 3 double values. method overloading can be used when the same operation has different implementations. in our StudentRecord class we want to have a method that prints information about the student.println("Age:" + age).D. } public void print(double eGrade.out. double mGrade. to have different implementations and return values of different types.out. when we pass a String. We have the following overloaded methods inside our StudentRecord class.println("Science Grade:" + sGrade).out.out.E.out. we want to sometimes create methods that has the same names but function differently depending on the parameters that are passed to them. Rather than invent new names all the time. and it is called Method Overloading. } Introduction to Programming I 171 .out.J. This capability is possible in Java.println("Name:" + name).out.

annaRecord. Name:Anna Address:Philippines Age:15 we will have the output for the second call to print.setAddress("Philippines"). annaRecord. annaRecord.J. annaRecord.print( annaRecord.I When we try to call this in the following main method. } we will have the output for the first call to print. annaRecord.setAge(15).print( annaRecord.getName() ). – the same name – different parameters – return types can be different or the same Introduction to Programming I 172 .5).D.getScienceGrade()).getEnglishGrade(). annaRecord. public static void main( String[] args ) { StudentRecord annaRecord = new StudentRecord(). annaRecord.setMathGrade(80). Name:Anna Math Grade:80.setScienceGrade(100). annaRecord.0 English Grade:95.E.5 Science Grade:100. annaRecord.setEnglishGrade(95.0 Always remember that overloaded methods have the following properties.getMathGrade().setName("Anna"). //overloaded methods annaRecord.

E. for example. Constructors have the same name as the class 2. then an implicit default constructor is created. double sGrade){ mathGrade = mGrade. constructors can also be overloaded.address = address. we have here four overloaded constructors. The default constructor is the constructor without any parameters. A constructor is just like an ordinary method.I 10. Constructors does not have any return value 4. the default constructor would look like this. this. It is a method where all the initializations are placed. Constructors are important in instantiating an object. englishGrade = eGrade.1 Default Constructor Every class has a default constructor. You cannot call a constructor directly. public StudentRecord() { //some code here } 10. } public StudentRecord(double mGrade.7. it can only be called by using the new operator during class instantiation. String address){ this..J. For example.name = name. 3. If the class does not specify any constructors. double eGrade. however only the following information can be placed in the header of the constructor.7.. in our StudentRecord class. we write. public StudentRecord(){ //some initialization code here } public StudentRecord(String temp){ this. constructor's name and parameters if it has any. } public StudentRecord(String name.2 Overloading Constructors As we have mentioned. scienceGrade = sGrade. } Introduction to Programming I 173 . scope or accessibility identifier (like public.D. <modifier> <className> (<parameter>*) { <statement>* } 10.7 Declaring Constructors We have discussed before the concept of constructors. To declare a constructor.name = temp.). The following are the properties of a constructor: 1.

what we want to do here is. studentCount++.name = temp.name = name. public StudentRecord(){ //some initialization code here studentCount++. before we move on.D. So. we have the following code. //add a student } public StudentRecord(String name.I 10.E.7. "Philippines"). //add a student } Introduction to Programming I 174 . double eGrade. The purpose of the studentCount is to count the number of objects that are instantiated with the class StudentRecord. let us go back to the static variable studentCount we have declared a while ago.J. A good location to modify and increment the value of studentCount is in the constructors.3 Using Constructors To use these constructors. public static void main( String[] args ) { //create three objects for Student record StudentRecord annaRecord=new StudentRecord("Anna"). we increment the value of studentCount. englishGrade = eGrade.address = address. scienceGrade = sGrade.90. everytime an object of class StudentRecord is instantiated. StudentRecord StudentRecord (80. studentCount++. studentCount++. For example. crisRecord=new StudentRecord Now. String address){ this. double sGrade){ mathGrade = mGrade. this. //add a student } public StudentRecord(String temp){ this. //add a student } public StudentRecord(double mGrade. because it is always called everytime an object is instantiated.100). //some code here } beahRecord=new StudentRecord("Beah".

meaning. 8: } 9: 10: public static void main( String[] args ) 11: { 12: 13: StudentRecord annaRecord = new StudentRecord(). it will call the default constructor line 1. given the following code. IT MUST OCCUR AS THE FIRST STATEMENT in a constructor 2. When statement in line 2 is executed. 14: } Given the code above. For example. 1: public StudentRecord(){ 2: this("some string"). Introduction to Programming I 175 . you can call another constructor from inside another constructor.7. When using the this constructor call.4 The this() Constructor Call Constructor calls can be chained. when the statement at line 13 is called. 3: 4: } 5: 6: public StudentRecord(String temp){ 7: this.D.J. The this call can then be followed by any other relevant statements. It can ONLY BE USED IN A CONSTRUCTOR DEFINITION.E. it will then call the constructor that has a String parameter (in line 6).name = temp. There are a few things to remember when using the this constructor call: 1. We use the this() call for this.I 10.

The first thing you have to do is create a folder named schoolClasses.*. we write.Color. The first statement imports the specific class Color while the other imports all of the classes in the java. 10. private String address. For example. import java. We will call our package. you have to type the following. public class StudentRecord { private String name. package schoolClasses.2 Creating your own packages To create our own package. import java. : Packages can also be nested. together with other related classes. you need to import the package of those classes.8 Packages Packages are Java’s means of grouping related classes and interfaces together in a single unit (interfaces will be discussed later). the Java interpreter expects the directory structure containing the executable classes to match the package hierarchy. package <packageName>. Introduction to Programming I 176 . In this case.Color color. The syntax for importing packages is as follows.I 10. schoolClasses.* package. all your Java programs import the java.J.1 Importing Packages To be able to use classes outside of the package you are currently working in. This powerful feature provides for a convenient mechanism for managing a large group of classes and interfaces while avoiding potential naming conflicts. that is why you can use classes like String and Integers inside the program eventhough you haven't imported any packages.awt.awt. private int age. if you want to use the class Color inside package awt.E.lang. By default. import <nameOfPackage>. This is done by using the package name to declare an object of a class.8.awt. java. For example.8.D. After copying. Copy all the classes that you want to belong to this package inside this folder. 10. Suppose we want to create a package where we will place our StudentRecord class. Another way to import classes from other packages is through explicit package referencing. add the following code at the top of the class file.awt package.

loadClassInternal(Unknown Source) We encounter a NoClassDefFoundError which means that Java did not know where to look for your class. C:\schoolClasses>javac StudentRecord.net.java C:\schoolClasses>java StudentRecord Exception in thread "main" java.lang. The reason for this is that your class StudentRecord now belongs to a package named studentClasses.findClass(Unknown Source) at java. which in this case is in location C:\. If we want to run our class. Before we discuss how to set the classpath.URLClassLoader.StudentRecord For Unix base systems. C:\schoolClasses> set classpath=C:\ where C:\ is the directory in which we have placed the packages. let us take a look at an example on what will happen if we don't set the classpath. Suppose we compile and then run the StudentRecord class we wrote in the last section.run(Unknown Source) at java.access$100(Unknown Source) at java.lang. we jave to tell Java about its full class name which is schoolClasses.loadClass(Unknown Source) at sun.ClassLoader.net.E.J.defineClass(Unknown Source) at java.Launcher$AppClassLoader.NoClassDefFoundError: StudentRecord (wrong name: schoolClasses/StudentRecord) at java. we write.I 10. suppose we have our classes in the directory /usr/local/myClasses.8. we must set the classpath.defineClass1(Native Method) at java. suppose we place the package schoolClasses under the C:\ directory.net. We also have to tell JVM where to look for our packages.security.lang.loadClass(Unknown Source) at java.ClassLoader.StudentRecord.SecureClassLoader.doPrivileged(Native Method) at java. export classpath=/usr/local/myClasses Introduction to Programming I 177 . We need to set the classpath to point to that directory so that when we try to run it. the JVM will be able to see where our classes are stored.loadClass(Unknown Source) at java.lang.D.misc.net.3 Setting the CLASSPATH Now.AccessController. C:\schoolClasses> java schoolClasses.security.ClassLoader.URLClassLoader. To set the classpath in Windows.ClassLoader. After setting the classpath.URLClassLoader. we type this at the command prompt.defineClass(Unknown Source) at java.URLClassLoader$1.ClassLoader. we can now run our program anywhere by typing.lang.defineClass(Unknown Source) at java. To do this.lang.

E:\MyPrograms\Java and for Unix based systems. For example.I Take note that you can set the classpath anywhere.E. You can also set more than one classpath. set classpath=C:\myClasses.D.J.(for windows) and : (for Unix based systems).D:\. export classpath=/usr/local/java:/usr/myClasses Introduction to Programming I 178 . we just have to separate them by .

For example. For example. 10. we want to implement some kind of restriction to access these data. Any object that interacts with the class can have access to the public members of the class. both inside and outside the class.2 public access This specifies that class members are accessible to anyone.9. as long as the object belongs to the same package where the class StudentRecord belongs to.1 default access (also called package accessibility) This specifies that only classes in the same package can have access to the class' variables and methods. you may want to hide this from other objects using your class. //default access to method String getName(){ return name. no keyword is used. The first three access modifiers are explicitly written in the code to indicate the access type. public class StudentRecord { //default access to instance variable public int name. it is applied in the absence of an access modifier.9 Access Modifiers When creating our classes and defining the properties and methods in our class. } } In this example. In Java. //default access to method public String getName(){ return name. public class StudentRecord { //default access to instance variable int name.9. if you want a certain attribute to be changed only by the methods inside the class.I 10. the instance variable name and the method getName() can be accessed from other objects. private. 10. protected and default.E.D. Introduction to Programming I 179 . There are four different types of member access modifiers in Java: public. for the fourth one which is default.J. For example. the instance variable name and the method getName() can be accessed from other objects. } } In this example. There are no actual keyword for the default modifier. we have what we call access modifiers in order to implement this.

9. and the class will just provide accessor and mutator methods to these variables. the instance variable name and the method getName() can be accessed only from methods inside the class and from subclasses of StudentRecord. 10. } } In this example.9.3 protected access This specifies that the class members are accessible only to methods in that class and the subclasses of the class. //default access to method protected String getName(){ return name. } } In this example. For example. Introduction to Programming I 180 .4 private access This specifies that the class members are only accessible by the class they are defined in. We will discuss about subclasses on the next chapter. the instance variable name and the method getName() can be accessed only from methods inside the class.I 10. //default access to method private String getName(){ return name. Coding Guidelines: The instance variables of a class should normally be declared private. For example.D.E. public class StudentRecord { //default access to instance variable private int name. public class StudentRecord { //default access to instance variable protected int name.J.

10 Exercises 10.1 Address Book Entry Your task is to create a class that contains an address book entry.10. 2. Provide the necessary accessor and mutator methods for all the attributes.J. 4. create the following: 1. Add entry Delete entry View all entries Update an entry Introduction to Programming I 181 . You should provide the following methods for the address book.10.E. 2. The following table describes the information that an adressbook entry has. Constructors 10. 1.D. Attributes/Properties Name Address Telephone Number Email Address Description Name of the person in the addressbook Address of the person Telephone number of the person Person's Email address Table 21: Attributes and Attributes Descriptions For the methods. 3.I 10.2 AddressBook Create a class address book that can contain 100 entries of AddressBookEntry objects (use the class you created in the first exercise).

J.E.D.I

11 Inheritance, Polymorphism and Interfaces
11.1 Objectives
In this section, we will be discussing on how a class can inherit the properties of an existing class. A class that does this is called a subclass and its parent class is called the superclass. We will also be discussing a special property of Java wherein it can automatically apply the proper methods to each object regardless of what subclass the object came from. This property is known as polymorphism. Finally, we are going to discusss about interfaces that helps reduce programming effort. At the end of the lesson, the student should be able to: • • • Define super classes and subclasses Override methods of superclasses Create final methods and final classes

11.2 Inheritance
In Java, all classes, including the classes that make up the Java API, are subclassed from the Object superclass. A sample class hierarchy is shown below. Any class above a specific class in the class hierarchy is known as a superclass. While any class below a specific class in the class hierarchy is known as a subclass of that class.

Inheritance is a major advantage in object-oriented programming since once a behavior (method) is defined in a superclass, that behavior is automatically inherited by all subclasses. Thus, you can encode a method only once and they can be used by all subclasses. A subclass only need to implement the differences between itself and the parent.

Figure 11.1: Class Hierarchy

Introduction to Programming I

182

J.E.D.I

11.2.1 Defining Superclasses and Subclasses
To derive a class, we use the extends keyword. In order to illustrate this, let's create a sample parent class. Suppose we have a parent class called Person. public class Person { protected String protected String

name; address;

/** * Default constructor */ public Person(){ System.out.println(“Inside Person:Constructor”); name = ""; address = ""; } /** * Constructor with 2 parameters */ public Person( String name, String address ){ this.name = name; this.address = address; } /** * Accessor methods */ public String getName(){ return name; } public String getAddress(){ return address; } public void setName( String name ){ this.name = name; } public void setAddress( String add ){ this.address = add; } } Notice that, the attributes name and address are declared as protected. The reason we did this is that, we want these attributes to be accessible by the subclasses of the superclass. If we declare this as private, the subclasses won't be able to use them. Take note that all the properties of a superclass that are declared as public, protected and default can be accessed by its subclasses.

Introduction to Programming I

183

J.E.D.I

Now, we want to create another class named Student. Since a student is also a person, we decide to just extend the class Person, so that we can inherit all the properties and methods of the existing class Person. To do this, we write, public class Student extends Person { public Student(){ System.out.println(“Inside Student:Constructor”); //some code here } } // some code here

When a Student object is instantiated, the default constructor of its superclass is invoked implicitly to do the necessary initializations. After that, the statements inside the subclass are executed. To illustrate this, consider the following code, public static void main( String[] args ){ Student anna = new Student(); } In the code, we create an object of class Student. The output of the program is, Inside Person:Constructor Inside Student:Constructor The program flow is shown below.

Figure 11.2: Program Flow

Introduction to Programming I

184

J.E.D.I

11.2.2 The super keyword
A subclass can also explicitly call a constructor of its immediate superclass. This is done by using the super constructor call. A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the superclass, based on the arguments passed. For example, given our previous example classes Person and Student, we show an example of a super constructor call. Given the following code for Student, public Student(){ super( "SomeName", "SomeAddress" ); System.out.println("Inside Student:Constructor"); } This code calls the second constructor of its immediate superclass (which is Person) and executes it. Another sample code shown below, public Student(){ super(); System.out.println("Inside Student:Constructor"); } This code calls the default constructor of its immediate superclass (which is Person) and executes it. There are a few things to remember when using the super constructor call: 1. The super() call MUST OCCUR THE FIRST STATEMENT IN A CONSTRUCTOR. 2. The super() call can only be used in a constructor definition. 3. This implies that the this() construct and the super() calls CANNOT BOTH OCCUR IN THE SAME CONSTRUCTOR. Another use of super is to refer to members of the superclass (just like the this reference ). For example, public Student() { super.name = “somename”; super.address = “some address”; }

Introduction to Programming I

185

J.E.D.I

11.2.3 Overriding Methods
If for some reason a derived class needs to have a different implementation of a certain method from that of the superclass, overriding methods could prove to be very useful. A subclass can override a method defined in its superclass by providing a new implementation for that method. Suppose we have the following implementation for the getName method in the Person superclass, public class Person { : : public String getName(){ System.out.println("Parent: getName"); return name; } : } To override, the getName method in the subclass Student, we write, public class Student extends Person { : : public String getName(){ System.out.println("Student: getName"); return name; } : } So, when we invoke the getName method of an object of class Student, the overridden method would be called, and the output would be, Student: getName

Introduction to Programming I

186

J.E.D.I

11.2.4 Final Methods and Final Classes
In Java, it is also possible to declare classes that can no longer be subclassed. These classes are called final classes. To declare a class to be final, we just add the final keyword in the class declaration. For example, if we want the class Person to be declared final, we write, public final class Person { //some code here } Many of the classes in the Java API are declared final to ensure that their behavior cannot be overridden. Examples of these classes are Integer, Double and String. It is also possible in Java to create methods that cannot be overridden. These methods are what we call final methods. To declare a method to be final, we just add the final keyword in the method declaration. For example, if we want the getName method in class Person to be declared final, we write, public final String getName(){ return name; } Static methods are automatically final. This means that you cannot override them.

Introduction to Programming I

187

J.E.D.I

11.3 Polymorphism
Now, given the parent class Person and the subclass Student of our previous example, we add another subclass of Person which is Employee. Below is the class hierarchy for that, Person

Student

Employee

Figure 11.3: Hierarchy for Person class and it's classes

In Java, we can create a reference that is of type superclass to an object of its subclass. For example, public static main( String[] args ) { Person ref; Student Employee studentObject = new Student(); employeeObject = new Employee();

ref = studentObject; //Person ref points to a // Student object } //some code here

Now suppose we have a getName method in our superclass Person, and we override this method in both the subclasses Student and Employee, public class Person { public String getName(){ System.out.println(“Person Name:” + name); return name; } } public class Student extends Person { public String getName(){ System.out.println(“Student Name:” + name); return name; } } public class Employee extends Person { public String getName(){ System.out.println(“Employee Name:” + name); return name; } }

Introduction to Programming I

188

while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to. Student Employee studentObject = new Student(). } Introduction to Programming I 189 . Employee employeeObject = new Employee().out.println( temp ). printInformation( studentObject ).E. . } This ability of our reference to change behavior according to what object it is holding is called polymorphism. . ref = employeeObject.D. Another example that exhibits the property of polymorphism is when we try to pass a reference to methods. if we assign ref to an Employee object. the getName method of the Student object will be called. ref = studentObject. Suppose we have a static method printInformation that takes in a Person object as reference.out. public static printInformation( Person p ){ . } printInformation( employeeObject ). employeeObject = new Employee(). //getName of Student //class is called System. the getName method of Employee will be called. //getName of Employee //class is called System. Polymorphism allows multiple objects of different subclasses to be treated as objects of a single superclass. . when we try to call the getName method of the reference Person ref.I Going back to our main method. //Person reference points to an // Employee object String temp = ref.println( temp ). public static main( String[] args ) { Person ref. public static main( String[] args ) { Student studentObject = new Student().getName(). //Person reference points to a // Student object String temp = ref.J. Now. we can actually pass a reference of type Employee and type Student to this method as long as it is a subclass of the class Person.getName().

This class has certain methods like breath. we want to create a superclass named LivingThing. just write the method declaration without the body and use the abstract keyword. there are many characteristics that living things have in common. Take the humans for instance. we humans walk on two legs. It often appears at the top of an object-oriented programming class hierarchy. and some methods wherein we just want to be overridden by its subclasses. we can create a superclass that has some methods with implementations and others which do not. However. sleep and walk.E. For example. the walk method. An abstract class is a class that cannot be instantiated. This kind of class is called an abstract class. Those methods in the abstract classes that do not have implementation are called abstract methods. eat.J. while other living things like dogs walk on four legs. that is why we want to create a general superclass for this. Take for example. there are some methods in this superclass wherein we cannot generalize the behavior. However. Introduction to Programming I 190 .4: Abstract class In order to do this. defining the broad types of actions possible with objects of all subclasses of the class.I 11. For example. Figure 11. Not all living things walk the same way.D. To create an abstract method. public abstract void someMethod().4 Abstract Classes Now suppose we want to create a superclass wherein it has certain methods in it that contains some implementation.

println("Human walks..out.").I Now. and use its subclasses to provide implementation details of the abstract class. or else.println("Living Thing breathing. } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk(). } } If the class Human does not override the walk method. let's create an example abstract class.").D. Human.. } When a class extends the LivingThing abstract class.java:1: Human is not abstract and does not override abstract method walk() in LivingThing public class Human extends LivingThing ^ 1 error Coding Guidelines: Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy.println("Living Thing eating. it is required to override the abstract method walk().out.out.. we would encounter the following error message.E. and therefore cannot be instantiated. For example. public class Human extends LivingThing { public void walk(){ System.")..J.. public abstract class LivingThing { public void breath(){ System. } public void eat(){ System.. Introduction to Programming I 191 . that subclass will also become an abstract class.

11. Introduction to Programming I 192 . Object b). public interface Relation { public boolean isGreater( Object a.5 Interfaces An interface is a special kind of block containing method signatures (and possibly constants) only. Our interface Relation can be declared as.D. Classes. let's say interface Relation which has some comparison method declarations. suppose we have another class MyInteger which contains methods that compares a MyInteger object to objects of the same class. } Another reason for using an object's programming interface is to reveal an object's programming interface without revealing its class.5. In order to enforce a way to make sure that these two classes implement some methods with similar signatures. As we can see later on the section Interface vs. but present in other object-oriented languages like C++.J. Interfaces define a standard and public way of specifying the behavior of classes. Object b).I 11. As we can see here. we need to use interfaces to model multiple inheritance which allows a class to have more than one superclass. public boolean isEqual( Object a. Object b). 11. Finally. an interface can only define constants and an interface have no direct inherited relationship with any particular class.2 Interface vs. but they are not related whatsoever. public boolean isLess( Object a. Let's take as an example a class Line which contains methods that computes the length of the line and compares a Line object to objects of the same class. we can actually capture similarities among unrelated classes without artificially forcing a class relationship. Interfaces define the signatures of a set of methods without the body. both of the classes have some similar methods which compares them from other objects of the same type. they are defined independently. Multiple inheritance is not present in Java. regardless of their location in the class hierarchy. They allow classes. Abstract Class The following are the main differences between an interface and an abstract class: interface methods have no body. We can create an interface class. we can use an interface for this.5.E. to implement common behaviors. we can actually use an interface as data type. Thru interfaces. Now. since program may call an interface method and the proper version of that method will be executed depending on the type of object passed to the interface method call. Note that interfaces exhibit polymorphism as well.1 Why do we use Interfaces? We need to use interfaces if we want unrelated classes to implement similar methods.

However. public boolean isLess( Object a. For example. public interface [InterfaceName] { //some methods without the body } As an example. Class One common characteristic of an interface and class is that they are both types. we write. private double y1. Object b). However. this.y1 = y1. An example of this is: PersonInterface pi = new PersonInterface().J.3 Interface vs. 11.4 Creating Interfaces To create an interface. this. private double x2. you cannot create an instance from an interface. /** * This class defines a line segment */ public class Line implements Relation { private double x1. given a class Person and an interface PersonInterface. this.y2 = y2. double y2){ this. let's create an interface that defines relationships between two objects according to the “natural order” of the objects. public boolean isEqual( Object a. This means that an interface can be used in places where a class can be used. private double y2. the following declarations are valid: PersonInterface Person pi = new Person(). Object b). } public double getLength(){ Introduction to Programming I 193 .x1 = x1. double x2. we use the implements keyword. Object b). double y1. public Line(double x1.5.I 11.E. //COMPILE //ERROR!!! Another common characteristic is that both interface and class can define methods.D.x2 = x2. to use the interface. an interface does not have an implementation code while the class have one. public interface Relation { public boolean isGreater( Object a.5. } Now. For example. pc = new Person().

getLength(). return (aLen == bLen). Object b){ double aLen = ((Line)a). public boolean isGreater( Object a.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)). or else.lang.getLength().Object) in Relation public class Line implements Relation ^ 1 error Coding Guidelines: Use interfaces to create the same standard method definitions in may different classes.getLength(). double bLen = ((Line)b). Introduction to Programming I 194 .java.java:4: Line is not abstract and does not override abstract method isGreater(java.getLength(). double bLen = ((Line)b). Object b){ double aLen = ((Line)a). you would encounter this error. always make sure that you implement all the methods of that interface. } public boolean isLess( Object a.J.E. Once a set of standard method definition is created. double bLen = ((Line)b). return (aLen > bLen).D.getLength().lang. } } When your class tries to implement an interface. Object b){ double aLen = ((Line)a).getLength().Object. return (aLen < bLen). Line. you can write a single method to manipulate all of the classes that implement the interface. return length. } public boolean isEqual( Object a.I } double length = Math.

5. An example of a class that implements many interfaces is. Unrelated classes can implement the same interface. LivingThing. If StudentInterface extends PersonInterface. Another thing to note about the relationship of interfaces to classes is that. 11.I 11. .6 Inheritance among Interfaces Interfaces are not part of the class hierarchy. suppose we have two interfaces StudentInterface and PersonInterface. but it can IMPLEMENT MANY interfaces.5 Relationship of an Interface to a Class As we have seen in the previous section. . interfaces can have inheritance relationship among themselves. public class ComputerScienceStudent extends Student implements PersonInterface. } public interface StudentInterface extends PersonInterface { .5.J. it will inherit all of the method declarations in PersonInterface. a class can only EXTEND ONE super class. . . a class can implement an interface as long as it provides the implementation code for all the methods defined in the interface. WhateverInterface { } //some code here Another example of a class that extends one super class and implements an interface is. LivingThing { } //some code here Take note that an interface is not part of the class inheritance hierarchy. public interface PersonInterface { . public class Person implements PersonInterface.D.E. } Introduction to Programming I 195 . However. For example.

Add some attributes and methods that you think are needed for a Computer Science student record. Write two of its subclasses Circle and Square. if you really need to.6. 11. we want to create a more specialized student record that contains additional information about a Computer Science student. Try to override some existing methods in the superclass StudentRecord.6.I 11.E. Your task is to extend the StudentRecord class that was implemented in the previous lessons.1 Extending StudentRecord In this exercise.6 Exercises 11.2 The Shape abstract class Try to create an abstract class called Shape with abstract methods getArea() and getName(). You can add additional methods to its subclasses if you want to.J. Introduction to Programming I 196 .D.

This technique is called exception handling. 12.I 12 Basic Exception Handling 12. .parseInt method. or maybe a NumberFormatException.1 Objectives In this section. The general form of a try-catch-finally block is. At the end of the lesson. What we do in our programs is that we place the statements that can possibly generate an exception inside this block.D. which occurs if we try to access a non-existent array element. try{ //write the statements that can generate an exception //in this block } catch( <exceptionType1> <varName1> ){ } . we use a try-catch-finally block.3 Handling Exceptions To handle exceptions in Java. Some examples of exceptions that you might have encountered in our previous exercises are: ArrayIndexOutOfBounds exceptions. This event is usually some error of some sort. the student should be able to: • • Define exceptions Handle exceptions using a simple try-catch-finally block 12. catch( <exceptionTypen> <varNamen> ){ //write the action your program will do if an //exception of a certain type occurs } finally{ //add more cleanup code here } //write the action your program will do if an exception //of a certain type occurs Introduction to Programming I 197 .J. we are going to study a technique used in Java to handle unusual conditions that interrupt the normal operation of the program.E. This causes our program to terminate abnormally. which occurs when we try to pass as a parameter a non-number in the Integer. .2 What are Exceptions? An exception is an event that interrupts the normal processing flow of a program.

main(ExceptionExample. and in the above order. but only one finally block.E.java:5) Introduction to Programming I 198 .lang. • A try block must be followed by at least one catch block OR one finally block. we'll get the following exception. The following are the key aspects about the syntax of the try-catch-finally construct: • The block notation is mandatory. there is no checking inside your code for the number of arguments and we just access the second argument args[1] right away. which is the exception its block is willing to handle. The header of the catch block takes exactly one argument. Figure 12. • Each catch block defines an exception handle.ArrayIndexOutOfBoundsException: 1 at ExceptionExample. Suppose.D. The exception must be of the Throwable class or one of its subclasses. • The catch blocks and finally blocks must always appear in conjunction with the try block. or both.J.I Exceptions thrown during execution of the try block can be caught and handled in a catch block. Exception in thread "main" java. The code in the finally block is always executed.1: Flow of events in a try-catch-finally block Let's take for example a code that prints the second argument when we try to run the code using command-line arguments. there can be one or more catch blocks. • For each try block.

println( args[1] ). Exception caught! Introduction to Programming I 199 . we won't use the finally block.println("Exception caught!"). }catch( ArrayIndexOutOfBoundsException exp ){ System. } } try{ } So when we try to run the program again without arguments.D. The finally block is just optional.E.out. the output would be.I To prevent this from happening.J. we can place the code inside a try-catch block. For this example. public class ExceptionExample { public static void main( String[] args ){ System.out.

ArrayIndexOutOfBoundsException: 3 at TestExceptions.4.E. Go back to those programs and implement exception handling. } } } Compile and run the TestExceptions program. 12.4.main(1. i++ ){ System. The output of the program after catching the exception should look like this: javac TestExceptions one two three args[0]=one args[1]=two args[2]=three Exception caught: java. The output should look like this: javac TestExceptions one two three args[0]=one args[1]=two args[2]=three Exception in thread "main" java.out.J. Introduction to Programming I 200 .println("args["+i+"]="+ args[i]).I 12.lang..2 Catching Exceptions 2 Chances are very good that some programs you've written before have encountered exceptions.4 Exercises 12.D. Since you didn't catch the exceptions.1 Catching Exceptions1 Given the following code: public class TestExceptions{ public static void main( String[] args ){ for( int i=0.lang. true. they simply halted the execution of your code.ArrayIndexOutOfBoundsException: 3 Quiting.java:4) Modify the TestExceptions program to handle the exception..

For Windows: Just copy the installers in any temporary directory.5.com/j2se/1.I Appendix A : Java and Netbeans Installation In this section.D. Introduction to Programming I 201 . copy the installers in your hard disk first.E. For Linux: Create a folder under the /usr directory and name it java.0 installers by your instructor. we will discuss on how to install Java and Netbeans in your system (Redhat Linux 9. you can download a copy of the installers from the Sun Microsystems website (http://java. If you are not provided with the Java 1.0/Windows XP). Before starting with the installation.0/download.org/downloads/ for Netbeans). You will now have a /usr/java directory. and copy all the installers inside this folder.J.jsp for Java and http://www.5 and Netbeans 4.sun.netbeans.

E.2: Start Terminal Introduction to Programming I 202 .I Installing Java in Linux Step 1: Run Terminal To start Terminal. click on Menu-> System Tools-> Terminal Figure 12.D.J.

D.I Step 2: Go to the folder where you copied the Java installer. type: cd /usr/java Figure 12.J.3: Change directory Introduction to Programming I 203 . To go to the folder.E.

Figure 12.I To make sure that all installers you need are already in the folder. To do this.4: List all files Make your installer file executable by using the chmod command. type: chmod u+x jdk-1_5_0_01-linux-i586.E.bin Figure 12.5: Make an installer an executable file Introduction to Programming I 204 .D. type: ls The ls (list) command will list all the files inside your directory.J.

J.E.D.I Step 3: Run the installer To run the installer. just type: .6: Run installer Introduction to Programming I 205 .bin Figure 12./jdk-1_5_0_01-linux-i586.

D.E. and press ENTER.I After pressing ENTER.8: License agreement Introduction to Programming I 206 . Figure 12. Just type: yes.9: License agreement Figure 12.7: License agreement Figure 12. until you see the question: Do you agree to the above license terms? [yes or no]. Just press enter. you will see the license agreement displayed on the console.J.

J.E.D.I Just wait for the installer to finish unpacking all its contents and installing java.10: Finish installation Introduction to Programming I 207 . Figure 12.

To do this.E. go to the directory:/usr/local/bin. we need to create symbolic links for all the commands in JDK inside the /usr/local/bin directory.J.I Step 4: Creating symbolic links In order to run java commands anywhere. Type: cd /usr/local/bin Figure 12.D.11: Change directory Introduction to Programming I 208 .

E.D.J.0_01/bin/* . type: ln -s /usr/java/jdk1. Figure 12.5.12: Create Symbolic links Introduction to Programming I 209 .I To make the symbolic links to the commands.

D.13: Folder containing installers Introduction to Programming I 210 . go to the folder where your Java installer is located Figure 12.E.J.I Installing Java in Windows Step 1: Using Windows Explorer.

J.E.D.14: License agreement Introduction to Programming I 211 . A J2SE installer dialog will then appear.I Step 2: Run the installer To run the installer. Click on the radio button labeled "I accept the terms in the license agreement" and press NEXT. just double-click on the installer icon. Figure 12.

15: Custom setup Click on FINISH to complete installation.D.I Click on NEXT to continue installation.16: Finish installation Introduction to Programming I 212 . Figure 12.E. Figure 12.J.

17: Run Console Introduction to Programming I 213 .J.D. click on Menu-> System Tools-> Terminal Figure 12.I Installing Netbeans in Linux Step 1: Run Terminal To start Terminal.E.

18: Change directory Introduction to Programming I 214 .E. type: cd /usr/java Figure 12.J.I Step 2: Go to the folder where you copied the Netbeans installer.D. To go to the folder.

Figure 12.bin Figure 12.I To make sure that all installers you need are already in the folder. To do this.J.E.D. type: chmod u+x netbeans-4_0-bin-linux.20: Make installer an executable Introduction to Programming I 215 .19: List all files Make your installer file executable by using the chmod command. type: ls The ls (list) command will list all the files inside your directory.

E. Click on NEXT.21: Run installer Figure Introduction to Programming I 12.I Step 3: Run Installer To run the netbeans installer.22: Netbeans installation wizard 216 . Figure 12. type: .0 Installer dialog will then appear./netbeans-4_0-bin-linux.D.bin A netbeans 4.J.

For the directory name.E. And then click on NEXT.J. Figure 12. then click on NEXT.23: Netbeans license agreement Figure 12.D. change it to: /usr/java/netbeans-4.I Click on the radio button that says "I accept the terms in the license agreement".0.24: Choose directory on where to install netbeans Introduction to Programming I 217 .

26: Installation summary Introduction to Programming I 218 .E. Just click again on NEXT.I For the JDK directory. The next dialog just shows information about Netbeans thatyou will install.D. Figure 12. choose /usr/java/jdk1.5.J.25: Choose jdk version to use Figure 12.0_01. and then click on NEXT.

D.28: Installation successful Introduction to Programming I 219 .J.E. Figure 12. just wait for netbeans to finish its installation.I Now. Figure 12.27: Netbeans installation Click on FINISH to complete the installation.

J. Type: cd /usr/local/bin Make a symbolic link to the netbeans executable by typing: ln -s /usr/java/netbeans-4. go first to the directory:/usr/local/bin.0/bin/netbeans .D. we need to create symbolic link for it. To do this.30: Create symbolic links Introduction to Programming I 220 .E.I Step 4: Creating symbolic links In order to run netbeans anywhere.29: Change directory Figure 12. Figure 12.

you can run netbeans in any directory by typing: netbeans & Figure 12.D.I Now.31: Netbeans running Introduction to Programming I 221 .E.J.

just double-click on the installer icon.32: Netbeans installer files Step 2: Run the installer To run the installer. Figure 12.D. go to the folder where your Netbeans installer is located Figure 12. Click on NEXT to enter installation process.E. the Netbeans installation wizard will appear.J.33: Netbeans installation Introduction to Programming I 222 . After clicking on the netbeans4_0-bin-windows icon.I Installing Netbeans in Windows Step 1: Using Windows Explorer.

J. Choose to ACCEPT and click NEXT to continue. You can move on by clicking NEXT or you can click on BROWSE to choose a different directory.34: License agreement Figure 12. Then you will be given the choice on which directory to place the Netbeans.I The agreement page will the appear.D. Figure 12.35: Choose directory where to install Netbeans Introduction to Programming I 223 .E.

I Next is choosing the Standard Edition JDKs from your machine.37: Installation summary Introduction to Programming I 224 . Figure 12. If you have finished installing Java.J.5.E. It will then inform you the location and size of Netbeans which will be installed to your machine.D. the jdk1. Click on NEXT to finish installation.0_01 chould appear from your choices.36: Choose JDK to use Figure 12. Click on NEXT to continue.

Figure 12.J.D.38: Successful installation Introduction to Programming I 225 .E. Click on FINISH to complete installation.I You have installed Netbeans on your computer.

My First Java Program public class Hello { /** * My first java program */ public static void main(String[] args) { //prints the string "Hello world" on screen System. Before going into details.E. the first one is by using a console and a text editor. The second one is by using Netbeans which is an Integrated Development Environment or IDE. let us first take a look at the first Java program you will be writing. Introduction to Programming I 226 . let's first try to write this program in a file and try to run it.println("Hello world!"). There are two ways of doing this.D.out. a compiler and/or interpreter and a debugger. compile and run Java programs.J. we will be discussing on how to write. a text or code editor. } } Before we try to explain what the program means. An IDE is a programming environment integrated into a software application that provides a GUI builder.I Appendix B: Getting to know your Programming Environment (Windows XP version) In this section.

we will be using the text editor "Notepad"(for Windows) to edit the Java source code.J. Step 1: Start Notepad To start Notepad in Windows.I Using a Text Editor and Console For this example. click on start-> All Programs-> Accessories-> Notepad. You can use other text editors if you want to.D. Figure 12.40: Notepad Application Figure 12.E.39: Click on start-> All Programs-> Accessories -> Notepad Introduction to Programming I 227 . You will also need to open the MS-DOS prompt window to compile and execute your Java programs.

41: start-> All programs-> Accessories -> Command Prompt Figure 12.I Step 2: Open the Command Prompt window To open the MSDOS command prompt in Windows. click on start-> All programs-> Accessories-> Command Prompt. Figure 12.42: MSDOS Command Prompt Introduction to Programming I 228 .J.D.E.

E. and we will be saving it inside a folder named MYJAVAPROGRAMS.java". Introduction to Programming I 229 .J.I Step 3: Write your the source code of your Java program in Notepad Step 4: Save your Java Program We will save our program on a file named "Hello. click on the File menu found on the menubar and then click on Save. To open the Save dialog box.D.

Introduction to Programming I 230 .43: This Dialog appears after clicking on File -> Save Click on the MY DOCUMENTS button to open the My Documents folder where we will be saving all your Java programs. Figure 12.I After doing the procedure described above.D.E.J. a dialog box will appear as shown in Figure below.

45: Clicking on the encircled button will create a New Folder. This will open your "My Documents" folder Figure 12.D. Figure 12.44: Click on the button encircled. we'll create a new folder inside the My Documents folder where we will save your programs.E.I Now. Click on the button encircled in the figure below to create the folder. We shall name this folder MYJAVAPROGRAMS.J. Introduction to Programming I 231 .

In this case.E. type in MYJAVAPROGRAMS. Introduction to Programming I 232 .I After the folder is created.J. and then press ENTER. you can type in the desired name for this folder.D.

double click on that folder to open it.E. You will see a similar figure as shown below. Introduction to Programming I 233 .D.J. The folder should be empty for now since it's a newly created folder and we haven't saved anything in it yet.I Now that we've created the folder where we will save all the files.

in the Filename textbox. Click on the "All Files" option. Now.I Now click on the drop down list box "Save as type". type in the filename of your program. and then click on the SAVE button.D. which is "Hello. Introduction to Programming I 234 .J.java".E. so that we can choose what kind of file we want to save.

you can just edit it. Take note that if you want to make changes in your file. notice how the title of the frame changes from UntitledNotepad to Hello. and then save it again by clicking on File -> Save. Introduction to Programming I 235 .java-Notepad.E.J.D.I Now that you've saved your file.

the next step is to compile your program. Figure 12.J. Introduction to Programming I 236 .D. To see what is inside that home folder. Now.I Step 5: Compiling your program Now.46: List of files and folders shown after executing the command DIR. when you open the command prompt window. type DIR or dir and then press ENTER. you can see here that there is a folder named "My Documents" where we created your MYJAVAPROGRAMS folder. it opens up and takes you directly to what is called your home folder.E. What you will see is a list of files and folders inside your home folder. Typically. Go to the MSDOS command prompt window we just opened a while ago. Now let's go inside that directory.

try typing in the "dir" command again. and tell me what you see. you type in the command: cd [directory name].I To go inside a directory. since the name of our directory is My Documents. Figure 12. change directory. Introduction to Programming I 237 . Figure 12.E.D. In this case.J.47: Inside the My Documents folder Now that you are inside the "My Documents" folder. you type in: cd My Documents.48: The contents of My Documents Now perform the same steps described before to go inside the MYJAVAPROGRAMS folder. The "cd" command stands for.

So in this case. Introduction to Programming I 238 . Figure 12. javac adds a file to the disk called [filename].class. type in: javac Hello. Hello.49: Inside the MYJAVAPROGRAMS folder Figure 12. or in this case.J.java. To compile a Java program. In order to do that.D. you should make sure that the file is inside the folder where you are in.E. we type in the command: javac [filename].I Once inside the folder where your Java programs are.class. which is the actual bytecode. Take note that. let us now start compiling your Java program. execute the dir command again to see if your file is inside that folder.50: Compile program by usingthe javac command During compilation.

J. "Hello world!". we are now ready to run your program. To run your Java program. Figure 12.I Step 6: Running the Program Now.D.51: Output of the program Introduction to Programming I 239 .E. so in the case of our example. assuming that there are no problems during compilation (we'll explore more of the problems encountered during compilation in the next section). type in the command: java [filename without the extension]. type in: java Hello You can see on the screen that you have just run your first Java program that prints the message.

operable program or batch file. This means that either you haven't installed Java in your system yet. you can now use the Java commands. try setting the PATH variable to point to where the Java commands are installed. you encounter the message: 'javac' is not recognized as an internal or external command.E.53: Setting the path and running java Introduction to Programming I 240 . This will tell your system to look for the commands in the C:\j2sdk1. Figure 12. Figure 12.4.52: System did not recognize the javac command If you are sure that you've already installed Java in your system. After doing this. To do this. which is usually the default location wherein your Java files are placed during installation.I Setting the Path Sometimes.J. or you have to configure the path on where the Java commands are installed so that your system will know where to find them.D.4.2_04\bin folder.2_04\bin. type in the command: set PATH=C:\j2sdk1. when you try to invoke the javac or java command.

let's now see how to do all the processes we've described in the previous sections by using just one application. click on start-> All Programs-> NetBeans 4. Step 1: Run Netbeans To run Netbeans.0 -> NetBeans IDE Introduction to Programming I 241 . An IDE is a programming environment integrated into a software application that provides a GUI builder.E. which is an Integrated Development Environment or IDE.I Using Netbeans Now that we've tried doing our programs the complicated way. a text or code editor. we will be using Netbeans.D.J. In this part of the lesson. a compiler and/or interpreter and a debugger.

D.E.54: NetBeans IDE Introduction to Programming I 242 .I After you've open NetBeans IDE. Figure 12. you will see a graphical user interface (GUI) similar to what is shown below.J.

let's first make a project. Click on File-> New Project.D. a New Project dialog will appear. Introduction to Programming I 243 .J.E.I Step 2: Make a project Now. After doing this.

J. Introduction to Programming I 244 .I Now click on Java Application and click on the NEXT button. Edit the Project Name part and type in "HelloApplication". a New Application dialog will appear.E.D. Now.

J. on the Create Main Class textfield. and then click on the FINISH button.E. Follow the steps described in the previous section to go to your MYJAVAPROGRAMS folder. type in Hello as the main class' name.D. Finally. Introduction to Programming I 245 .I Figure 12.55: Change Project Name Now try to change the Application Location. by clicking on the BROWSE button.

J. Introduction to Programming I 246 .D. let us first describe the main window after creating the project. NetBeans automatically creates the basic code for your Java program. As shown below. where you set the Project location. You can just add your own statements to the generated code. On the left side of the window.E.I Step 3: Type in your program Before typing in your program. you can see a list of folders and files that NetBeans generated after creating the project. This can all be found in your MYJAVAPROGRAMS folder.

you could also use the shortcut button to compile your code. Or.J. just click on Build -> Build Main Project. Introduction to Programming I 247 . after the statement. to compile your program.println("Hello world!").E.out.I Now. try to modify the code generated by Netbeans. as we will explain the details of the code later. Insert the code: System. Step 4: Compile your program Now. Ignore the other parts of the program for now. //TODO code application logic here.D.

D.J.E.I Figure 12.56: Shortcut button to compile code Introduction to Programming I 248 .

E.D. Figure 12. you will see a build successful message on the output window.57: Output window just below the window where you type your source code Introduction to Programming I 249 .J.I If there are no errors in your program.

Or you could also use the shortcut button to run your program. Figure 12.J.E. click on Run-> Run Main Project. Figure 12.59: Output of Hello.I Step 5: Run your program To run your program.D.java Introduction to Programming I 250 .58: Shortcut button to run program The output of your program is displayed in the output window.

Baking Bread Pseudocode: prepare all ingredients pour all ingredients in mixing bowl while batter not smooth yet mix ingredients pour into bread pan place inside oven while bread not yet done wait Flowchart: remove from oven Introduction to Programming I 251 .D.1 Writing Algorithms 1.J.E.I Appendix C : Answers to Exercises Chapter 1 Exercises 1.

J.E.D.I 2. Logging into your laboratory's computer Pseudocode: Let power = computer's power button Let in = status of user (initially false) if power == off Press power button Enter "boot" process while in== false enter user name enter password if password and user name correct in = true end while Flowchart: Introduction to Programming I 252 .

J. Getting the average of three numbers Pseudocode: Let count = 0 Let sum = 0 Let average = 0 While count < 3 Get number sum = sum + number count++ average = sum/3 Flowchart: Display average Introduction to Programming I 253 .I 3.D.E.

hexadecimal and octal To Binary: 1980/2 = 990 990/2 = 495 495/2 = 247 247/2 = 123 123/2 = 61 61/2 = 30 30/2 = 15 15/2 = 7 7/2 = 3 3/2 = 1 1/2 = 0 Binary = 11110111100 To Hexadecimal: 0111. 3 Octal = 3674 110. B 1100. 198010 to binary. 7 100 4 Introduction to Programming I 254 .D. 6 111.2 Number Conversions 1.I 1. C 0 0 1 1 1 1 0 1 1 1 1 011.J.E. 7 Hexadecimal = 7BC To Octal: 1011.

D. 10010011012 to decimal. 1 Octal = 1115 001.E. 2 Hexadecimal = 24D To Octal: 0100. 1 101 5 Introduction to Programming I 255 .J.I 2. 4 1101 D 001. hexadecimal and octal To Decimal: 1*1 = 1 0*2 = 0 1*4 = 4 1*8 = 8 0 * 16 = 0 0 * 32 = 0 1 * 64 = 64 0 * 128 = 0 0 * 256 = 0 1 * 512 = 512 TOTAL= 589 Decimal = 589 To Hexadecimal: 0010. 1 001.

J.I 3. 3 Hexadecimal = 3E To Decimal: 6*1= 6 7 * 8 = 56 TOTAL = 62 Decimal = 62 1110. 7 Binary = 111110 To Hexadecimal: 110. 6 0011. 768 to binary.E. hexadecimal and decimal To Binary: 111.D. E Introduction to Programming I 256 .

43F16 to binary. Binary = 010000111111 To Decimal: F * 1 = 15 3 * 16 = 48 4 * 256 = 1024 TOTAL= 1087 Decimal = 1087 To Octal: 3 0011.D.E. 7 111 7 Chapter 2 (No exercises) Introduction to Programming I 257 . F 1111 010. 2 Octal = 02077 000 .J. 0 111 .I 4. decimal and octal To Binary: 4 0100.

println("A tree whose hungry mouth is pressed").println("I think I shall never see.").println("a poem as lovely as a tree.out.println("Against the Earth's flowing breast.out.out.J."). System.E.").println("Welcome to Java Programming [YourName]!!!"). } } 3.1 Hello World! /** * This class prints the line "Welcome to Java Programming [YourName]!!!" * on screen.I Chapter 3 Exercises 3. System. */ public class HelloWorld { public static void main(String[] args){ System.out.D. System.out. } } Introduction to Programming I 258 .2 The Tree /** * A program that prints four lines on screen */ public class TheTree { public static void main(String[] args){ System.

2 Getting the average of three numbers /** * A program that solves for the average * of the three numbers: 10.out. System. 45.20.I Chapter 4 Exercises 4. //prints the output on the screen System.out.out.out. } } 4.out.println("Number = "+number).println("str = "+str). 20.out.out.E.J. System.println("Average is = "+ave). //declares character letter with 'a' as initial value char letter = 'a'. System.D. System.println("number 2 = "+num2). and 45 * then outputs the result on the screen */ public class AverageNumber { public static void main(String[] args){ //declares int num1 = int num2 = int num3 = the three numbers 10. System.1 Declaring and printing variables /** * A program that declares different variables * then outputs the values of the variables */ public class VariableSample { public static void main(String[] args){ //declares integer number with 10 as initial value int number = 10. //get the average of the three numbers // and saves it inside the ave variable int ave = (num1+num2+num3)/3. //declares String str with "hello" as initial value String str = "hello". //prints the values of the variables on screen System.println("number 3 = "+num3). System.println("result = "+result).println("number 1 = "+num1). //declares boolean result with true as initial value boolean result = true.println("letter = "+letter). } } Introduction to Programming I 259 .out.

out.println("The highest number is = "+max).3 Output greatest value /** * A program that outputs the number with * the greatest value given thre numbers */ public class GreatestValue { public static void main(String[] args){ //declares the numbers int num1 = 10.println("number 2 = "+num2).out. System. //determines the highest number max = (num1>num2)?num1:num2. (((a/b)^c)^((d-e+f-(g*h))+i)) 2.out.D. //prints the output on the screen System.I 4.out.E. int max = 0. ((((((3*10)*2)/15)-2+4)^2)^2) 3.4 Operator precedence 1. System.println("number 1 = "+num1). ((r^((((s*t)/u)-v)+w))^(x-(y++))) Introduction to Programming I 260 .println("number 3 = "+num3). System. } } 4. max = (max>num3)?max:num3. int num3 = 5.J. int num2 = 23.

thirdWord = reader.readLine().in)).println(firstWord + " " + secondWord + " " + thirdWord).I Chapter 5 Exercises 5. try{ System. secondWord = reader.E. } //prints the phrase System. String secondWord = "".out.//gets the 2nd word System.out.io. firstWord = reader.*.//gets the 3rd word }catch( IOException e){ System.print("Enter word1: ").print("Enter word3: ").println("Error in getting input").J.readLine().1 Last 3 words (BufferedReader version) import java. String thirdWord = "".out.//gets the 1st word System. //declares the String variables for the three words String firstWord = "". /** * A program that asks three words from the user * and then prints it on the screen as a phrase */ public class LastThreeWords { public static void main(String[] args){ //declares the variable reader as the BufferedReader reader = new BufferedReader( new InputStreamReader( System.print("Enter word2: ").out. } } Introduction to Programming I 261 .D.out.readLine().

swing.D. //displays the message JoptionPane.showMessageDialog(null. //gets the second word from the user String secondWord = JoptionPane.firstWord+ " "+secondWord+ " "+thirdWord).I 5.showInputDialog ("Enter word1").JOptionPane.showInputDialog ("Enter word2"). /** * A program that asks three words from the user using the JOptionPane * and then displays these three words as a phrase on the screen */ public class LastThreeWords { public static void main(String[] args){ //gets the first word from the user String firstWord = JoptionPane.2 Last 3 words (JOptionPane version) import javax. } } Introduction to Programming I 262 .J.E. //gets the third word from the user String thirdWord = JoptionPane.showInputDialog ("Enter word3").

/** * Gets three number inputs from the user * then displays the average on the screen */ public class Grades { public static void main(String[] args){ //declares the variable reader as the BufferedReader reader = new BufferedReader ( new InputStreamReader( System.J.out.out.print("Third grade: ").readLine()). int thirdGrade = 0. //prints the average of the three exams System. int secondGrade = 0. System.in)).out.parseInt (reader.readLine()).print(" .print(" . try{ System.-("). } } Introduction to Programming I 263 .1 Grades Using BufferedReader: import java. secondGrade = Integer. double average = 0.out.E. } //solves for the average average = (firstGrade+secondGrade+thirdGrade)/3.I Chapter 6 Exercises 6.io.print("Average: "+average). firstGrade = Integer. System.D.parseInt (reader. else System.exit(0).println("Input is invalid").-)"). System.readLine()).print("First grade: "). }catch( Exception e){ System. if(average>=60) System. thirdGrade = Integer.*.out. int firstGrade = 0.out.print("Second grade: ").parseInt (reader.out.

J.I Using JOptionPane: import javax. } else{ JoptionPane."Average : "+average+" .showInputDialog ("First grade")). if(average>=60){ JoptionPane.showMessageDialog(null. average = 0.parseDouble (JoptionPane.showMessageDialog (null. "Input is invalid").E.showMessageDialog (null.-("). System. /** * Gets three number inputs from the user * then displays the average on the screen */ public class Grades { public static void main(String[] args){ double double double double try{ firstGrade = 0. secondGrade = 0.JOptionPane. } //solves for the average average = (firstGrade+secondGrade+thirdGrade)/3."Average : "+average+" . } } } Introduction to Programming I 264 .showInputDialog ("Third grade")).swing.exit(0).showInputDialog ("Second grade")).parseDouble (JoptionPane. firstGrade = Double.D. thirdGrade = Double.-)"). }catch( Exception e){ JoptionPane. secondGrade = Double.parseDouble (JOptionPane. thirdGrade = 0.

else if(input == 5) msg = "five".showInputDialog ("Enter number")).2 Number in words Using if-else statement: import javax.JOptionPane. else if(input == 6) msg = "six". //gets the input string input = Integer. else if(input == 2) msg = "two". //sets msg to the string equivalent of input if(input == 1) msg = "one". else if(input == 9) msg = "nine".parseInt(JOptionPane. else if(input == 10) msg = "ten".msg).swing.J. else if(input == 3) msg = "three". } } Introduction to Programming I 265 . else if(input == 8) msg = "eight". //displays the number in words if with in range JOptionPane. /** * Transforms a number input from 1-10 to words * using if-else */ public class NumWords { public static void main(String[] args){ String msg = "".I 6. else if(input == 7) msg = "seven".E.showMessageDialog(null.D. else if(input == 4) msg = "four". else msg = "Invalid number". int input = 0.

case 7: msg = "seven". break.I Using switch statement: import javax. break. case 9: msg = "nine". //sets msg to the string equivalent of input switch(input){ case 1: msg = "one".JOptionPane. case 3: msg = "three".D. case 2: msg = "two".J. case 4: msg = "four".showMessageDialog(null. break. */ public class NumWords { public static void main(String[] args){ String msg = "". break.showInputDialog ("Enter number")).msg). //gets the input string input = Integer. case 5: msg = "five". case 6: msg = "six". break. int input = 0.E. } //displays the number in words if with in range JOptionPane. break.parseInt (JOptionPane. break. break. break. default: msg = "Invalid number". break. break. /** * Transforms a number input from 1-10 to words * using switch.swing. case 8: msg = "eight". } } Introduction to Programming I 266 . case 10: msg = "ten".

out.println("Invalid input").io. int counter = 0.I 6.E.exit(0). } //while loop that prints the name one hundred times while(counter < 100){ System. //gets the users' name try{ System.print("Enter name: ").in)). } } } Introduction to Programming I 267 .D.3 Hundred Times Using while-loop: import java.out.J.out.*. /** * A program that prints a given name one hundred times * using while loop */ public class HundredNames{ public static void main(String[] args){ BufferedReader reader = new BufferedReader (new InputStreamReader ( System. }catch(Exception e){ System. name = reader. System. String name = "".println(name). counter++.readLine().

println("Invalid input").print("Enter name: "). counter++.out.out. }while(counter < 100).println(name).out. } } Introduction to Programming I 268 . }catch(Exception e){ System.exit(0). /** * A program that prints a given name one hundred times * using do-while loop */ public class HundredNames { public static void main(String[] args){ BufferedReader reader = new BufferedReader (new InputStreamReader ( System. name = reader.*.D.I Using do-while loop: import java. int counter = 0.readLine(). } times //do-while loop that prints the name one hundred do{ System. //gets the users' name try{ System.E.io.in)).J. System. String name = "".

counter < 100. //gets the users' name try{ System.exit(0). name = reader.io.out.D.out.I Using for loop: import java.E. counter++){ System.in)).out.println(name).println("Invalid input"). /** * A program that prints a given name one hundred times * using do-while loop */ public class HundredNames { public static void main(String[] args){ BufferedReader reader = new BufferedReader (new InputStreamReader ( System. } //for loop that prints the name one hundred times for(int counter = 0. }catch(Exception e){ System. String name = "".print("Enter name: "). } } } Introduction to Programming I 269 . System.*.readLine().J.

*/ public class Powers { public static void main(String[] args){ int int int int base = 0. exp = Integer.showInputDialog("Exponent")). } //while loop that solves for the power while(counter < exp){ power = power*base. } } Introduction to Programming I 270 . power = 1.parseInt (JOptionPane. System.showMessageDialog (null.4 Powers Using while-loop: import javax.I 6.base+" to the "+exp+ " is "+power).E.D. The exponent is limited to positive numbers only.showInputDialog("Base")).exit(0). counter++.J."Positive numbers only please"). } //displays the result JoptionPane. //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.parseInt (JOptionPane.showMessageDialog (null. /** * Computes the power of a number given the base and the * exponent. //gets the user input for base and power using // JOptionPane base = Integer.swing. counter = 0. exp = 0.JOptionPane.

E.parseInt(JOptionPane. The exponent is limited to positive numbers only."Positive numbers only please"). //displays the result JoptionPane. exp = 0.I Using do-while loop: import javax. power = 1.showMessageDialog (null.showMessageDialog(null.exit(0). } } Introduction to Programming I 271 .J. System. */ public class Powers { public static void main(String[] args){ int int int int base = 0.swing. counter = 0.D. //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane. } //do-while loop that solves the power given the base // and exponent do{ if(exp != 0) power = power*base.JOptionPane. exp = Integer.parseInt(JOptionPane. }while(counter < exp).showInputDialog ("Exponent")). //gets the user input for base and power //using JOptionPane base = Integer.base + " to the "+exp + " is "+power).showInputDialog ("Base")). /** * Computes the power of a number given the base and the * exponent. counter++.

JOptionPane."Positive numbers only please").parseInt(JOptionPane. System.J. } } Introduction to Programming I 272 . } //for loop for computing the power for(counter = 0.E.I Using for loop: import javax.base + " to the "+exp + " is "+power).D. power = 1. counter++){ power = power*base.swing. The exponent is limited to positive numbers only.exit(0).showInputDialog ("Exponent")). counter < exp. counter = 0.showInputDialog ("Base")). exp = Integer.parseInt(JOptionPane. exp = 0. //gets the user input for base and power using // JOptionPane base = Integer. */ public class Powers { public static void main(String[] args){ int int int int base = 0. //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.showMessageDialog(null. } //displays the result JoptionPane. /** * Computes the power of a number given the base and the * exponent.showMessageDialog(null.

int counter = 0."Friday". */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of // the week String[] days ={"Sunday".length). "Saturday"}. int counter = 0.out."Thursday".J.D."Monday".1 Days of the Week Using while loop: /** * Uses an array string to save the days of the wee * then prints it on the screen. //while loop that prints the days of the week while(counter < days."Friday".length){ System."Tuesday". "Wednesday". "Saturday"}."Tuesday"."Monday".E. counter++. } } Introduction to Programming I 273 . } } } Using do-while loop: /** * Uses an array string to save the days of the wee * then prints it on the screen with a do-while loop.out.I Chapter 7 Exercises 7. //do-while loop that prints the days of the // week do{ System."Thursday".println(days[counter]). "Wednesday". counter++. }while(counter < days.println(days[counter]). */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of the week String[] days = {"Sunday".

//gets the maximum number if((counter == 0)||(num[counter] > max)) max = num[counter]. Introduction to Programming I 274 . counter < 10. "Wednesday".showMessageDialog(null.length. */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of // the week String[] days ={"Sunday". "Saturday"}.J.JOptionPane. int max = 0.println(days[counter]). int counter."Thursday".E. //for loop that gets the 10 numbers from the user for(counter = 0.showInputDialog( "Enter number "+(counter+1))). //for loop that prints the days of the week for(int counter = 0. counter < days."Monday".parseInt (JoptionPane.out.2 Greatest number import javax. counter++) } } 7. */ public class GreatestNumber { public static void main(String[] args){ int[] num = new int[10]."Friday". /** * A program that uses JOptionPane to get ten numbers * from the user then outputs the largest number. } } } //displays the number with the greatest number JoptionPane.swing. System. "The number with the greatest value is "+max).D.I Using for loop: /** * Uses an array string to save the days of the wee * then prints it on the screen with a for loop. counter++){ num[counter] = Integer."Tuesday".

D. } } } Introduction to Programming I 275 .println(args[counter]). */ public class CommandLineSample { public static void main(String[] args){ //checks if a command line argument exists if(args.I Chapter 8 Exercises 8. //for loop that prints the arguments from the //command line for(int counter=0.length == 0) System.1 Print Arguments /** * A program that prints the string from the command line if any. counter++){ System.length.J.out.E.counter<args.exit(0).

//4. } } Class and Method declaration: 1. System. Class: System Method: public static void exit( int status ) 4. //5.isDigit('0')).exit(1). Class: Character Method: public static boolean isDigit( char ch ) Introduction to Programming I 276 . endsWith String str = "Hello". Class: String Method: public boolean endsWith( String suffix ) 2. Class: Math Method: public static double floor( double a ) 5.endsWith( "slo" ) ).out. 16) ).println( Math.1 Defining terms See definitions in book. forDIgit System.E. System. int radix ) 3. exit was not called").out.14)). //2.I Chapter 9 Exercises 9. Check the Java API for more answers. Class: Character Method: public static char forDigit( int digit.out. System.println( str.J. floor System. System.out.println("if this is executed.isDigit('A')). //3.println( "0=" + Character.out.floor(3.2 Java Scavenger Hunt To the teacher: These are just some sample methods in the Java API that you can use.forDigit(13.println( Character.println( "A=" +Character. 9.out. isDigit System. Sample Usage: public class Homework1 { public static void main(String []args){ //1.D.

add = add. int tel.I Chapter 10 Exercises 10. } /** * changes the variable name */ public void changeName(String name){ this. this. telephone number and email adress */ public AddressBookEntry(String name. address. String add. telephone number.tel = tel. } /** * Creates an AddressBookEntry object with the given * name. tel = 0.E.1 Address Book Entry /** * An address book class that record a persons * name. String email){ this. /** * default constructor */ public AddressBookEntry(){ name = "". email = "". add = "". and email address */ public class AddressBookEntry { private private private private String name. String email.name = name. this.D. address. int tel. this. String add.email = email. } /** * returns the variable add */ public String getAddress(){ return add. } Introduction to Programming I 277 .J. } /** * returns the variable name */ public String getName(){ return name.name = name.

D.J. } } Introduction to Programming I 278 . } /** * changes the variable tel */ public void changeTelNumber(int tel){ this. } /** * returns the variable tel */ public int getTelNumber(){ return tel. } /** * changes the variable email */ public void changeEmailAdd(String email){ this.tel = tel.E. } /** * returns the variable email */ public String getEmailAdd(){ return email.email = email.add = add.I /** * changes the variable add */ public void changeAddress(String add){ this.

/** * Creates an addresbook that contains 100 AddressBookEntries */ public class AddressBook { //index of the last entry private int top = 0. } Introduction to Programming I 279 .io. }catch(Exception e){ System. System. //array of Address Book Entries private AddressBookEntry[] list.*.out. System.readLine(). AddressBook addBook = new AddressBook(). System.J. /** * The main method */ public static void main(String[] args){ BufferedReader keyIn = new BufferedReader (new InputStreamReader (System.E.println("[Q] Quit"). try{ //gets the choice act = keyIn.println("Error").D.println("\n[A] Add entry"). //constant number that indicates the maximum //number of entries in the address book private static final int MAXENTRIES = 100.in)).out.out.println("[D] Delete entry").out.print("Enter desired action: ").out.println("[U] Update entry"). System. String act = "".println("[V] View all entries").out.I 10.out. while(true){ //displays the optons System.2 AddressBook import java. System.

out. Introduction to Programming I 280 .equals("U")||act.E.equals("A")||act.equals("d")) addBook.I } } //checks for the appropriate action for // his choice if(act.viewEntries().println ("Unknown command").addEntry().equals("D")||act.equals("V")||act. else if(act. else if(act.equals("Q")||act.equals("v")) addBook.D.J.delEntry().exit(0).equals("a")) addBook. else if(act.equals("q")) System.equals("u")) addBook.updateEntry(). else if(act. else System.

} AddressBookEntry entry = new AddressBookEntry (name. return. email).D.out.readLine(). }catch(Exception e){ System. } Introduction to Programming I 281 .J.print("Email Adress: ").readLine()).parseInt(keyIn. int tel = 0. add = keyIn.readLine(). } //asks the user for the data of the address book try{ System.println(e). tel.E.I /** * creates the AddressBook */ public AddressBook(){ list = new AddressBookEntry[MAXENTRIES]. top++. if(top == MAXENTRIES){ System. add.print("Address: "). System.out.print("Telephone number: ").print("Name: "). email = keyIn.exit(0). String add = "". list[top] = entry.out. tel = Integer. } /** * method for adding an AddressBookEntry to the Adressbook */ public void addEntry(){ BufferedReader keyIn = new BufferedReader (new InputStreamReader (System.readLine().out. System.out.println("Address Book is full"). String name = "". System. String email = "". System.out. name = keyIn.in)).

J. i++ ){ list[i] = list[i+1].println("Address:"+ list[index]. }else{ for( int i=index.out. System. int index = 0.println("Index Out Of Bounds").out.out.parseInt(keyIn.D.out. }catch(Exception e){} //checks if the index is with in bounds if(index < 0 || index >= top){ System. } } /** * method that prints all the entries in the AddressBook */ public void viewEntries(){ for(int index = 0. } } Introduction to Programming I 282 . } //asks for the entry which is to be deleted try{ //shows the current entries on the record book viewEntries(). //checks if the address book is empty if(top == 0){ System.out.E. i<top. index = Integer. index++){ System.in)).getTelNumber()).I /** * method that deletes an AddressBookEntry from the * Adressbook with the index */ public void delEntry(){ BufferedReader keyIn = new BufferedReader (new InputStreamReader(System. return.println((index+1)+" Name:"+ list[index]. System. } list[top] = null. System.getAddress()). return.getEmailAdd()). index < top.getName()). System.println("Address Book is empty").print("\nEnter entry number: ").println("Email Address:"+ list[index].out.println("Telephone Number:"+ list[index]. top--.readLine())-1.out.

int index = 0.in)). String add = "".print("Name: "). } //updates the entry AddressBookEntry entry = new AddressBookEntry (name. int tel = 0.out. list[index] = entry.print("Email Adress: ").readLine().readLine(). }catch(Exception e){ System. tel. email = keyIn. System.print("Telephone number: "). String name = "".I /** * method that updates an entry */ public void updateEntry(){ BufferedReader keyIn = new BufferedReader(new InputStreamReader (System. //asks for the entries data try{ System. System.readLine(). System.out. index =Integer.print("Entry number: ").parseInt(keyIn.J.E.exit(0). add = keyIn.readLine())-1.D.out. System. } } Introduction to Programming I 283 .out.out. name = keyIn. System. email). tel = Integer.println(e). add. String email = "".readLine()).parseInt(keyIn.out.print("Address: ").

D. protected double mathGrade. } /** * Returns the age of the student */ public int getAge(){ return age. } /** * Changes the address of the student */ public void setAddress(String temp){ address = temp. protected double englishGrade. protected static int studentCount. } /** * Changes the name of the student */ public void setName(String temp){ name = temp.E. } /** * Returns the address of the student */ public String getAddress(){ return address. } /** * Changes the age of the student */ public void setAge(int temp){ age = temp. protected String address.I Chapter 11 Exercises 11. /** * Returns the name of the student */ public String getName(){ return name. protected double scienceGrade. } Introduction to Programming I 284 . protected int age.J.1 Extending StudentRecord /** * An object that holds the data for a student */ public class StudentRecord { protected String name. protected double average.

} /** * Changes the englishGrade of the student */ public void setEnglishGrade(double temp){ englishGrade = temp. } /** * Returns the mathGrade of the student */ public double getMathGrade(){ return mathGrade.J. } /** * Returns the scienceGrade of the student */ public double getScienceGrade(){ return scienceGrade.I /** * Returns the englishGrade of the student */ public double getEnglishGrade(){ return englishGrade. math and * science grades */ public double getAverage(){ return (mathGrade+englishGrade+scienceGrade)/3.E. } /** * Returns the number of instances of the * StudentRecords */ public static int getStudentCount(){ return studentCount. } /** * Computes the average of the english.D. } /** * Changes the scienceGrade of the student */ public void setScienceGrade(double temp){ scienceGrade = temp. } /** * Changes the mathGrade of the student */ public void setMathGrade(double temp){ mathGrade = temp. } } Introduction to Programming I 285 .

} /** * Changes the studentNumber of the student */ public void setStudentNumber(String temp){ studentNumber = temp. } } Introduction to Programming I 286 .D. } /** * Changes the comSciGrade of the student */ public void setComSciGrade(double temp){ comSciGrade = temp. } /** * Returns the comSciGrade of the student */ public double getComSciGrade(){ return comSciGrade.I /** * A student record for a Computer Science student */ public class ComputerScienceStudentRecord extends StudentRecord { private String private double studentNumber.E.J. comSciGrade. /** * Returns the studentNumber of the student */ public String getStudentNumber(){ return studentNumber.

} /** * returns shape name */ public String getName(){ return "circle". } /** * Class definition for object circle */ public class Circle extends Shape { private static final double pi = 3.E. } } Introduction to Programming I 287 . } /** * returns area */ public double getArea(){ return pi*radius*radius. /** * returns the name of the shape */ public abstract String getName(). private double radius = 0.D.2 Abstract Classes /** * Definition of shape abstract class */ public abstract class Shape { /** * returns the area of a certain shape */ public abstract double getArea().J. } /** * set radius */ public void setRadius(double r){ radius = r. } /** * returns radius */ public double getRadius(){ return radius. /** * Constructor */ public Circle(double r){ setRadius( r ).I 11.1416.

I /** * Class definition for object square */ public class Square extends Shape { private double side = 0. } } Introduction to Programming I 288 . } /** * returns area */ public double getArea(){ return side*side.J. } /** * returns shape name */ public String getName(){ return "square". /** * Constructor */ public Square(double s){ setSide( s ).D.E. } /** * returns length of one side */ public double getSide(){ return side. } /** * set length of side */ public void setSide(double s){ side = s.

} } } //displays the number with the greatest number JoptionPane. wherein we included some exception handling. } } } 12. } }catch( ArrayIndexOutOfBoundsException e ){ System. int counter. System.I Chapter 12 Exercises 12.showInputDialog ("Enter number "+(counter+1))).E.D. int max = 0."). /** * A program that uses JOptionPane to get ten numbers * from the user then outputs the largest number.JOptionPane.parseInt (JoptionPane.showMessageDialog (null.showMessageDialog (null. import javax."The number with the greatest value is "+max).J. } //gets the maximum number if((counter == 0)||(num[counter] > max)) max = num[counter]. //for loop that gets the 10 numbers from the user for(counter = 0.swing. true.out. }catch(NumberFormatException e){ JoptionPane.println("Exception caught:"). System.println(" "+e).2 Catching Exceptions 2 Here are three sample programs that we did before. counter++){ try{ num[counter] = Integer.out..out. counter < 10. */ public class GreatestNumber { public static void main(String[] args){ int[] num = new int[10].println("args["+i+"]="+args[i]).println("Quiting.1 Catching Exceptions 1 public class TestExceptions{ public static void main( String[] args ){ try{ for( int i=0..out."Error "+e). i++ ){ System. Introduction to Programming I 289 .

case 6: msg = "six". Introduction to Programming I 290 try{ . */ public class NumWords { public static void main(String[] args){ String msg = "".I import javax. break. break. case 5: msg = "five". break.J.showMessageDialog(null. } //sets msg to the string equivalent of input switch(input){ case 1: msg = "one". break. break. } //displays the number in words if with in range JOptionPane. }catch(Exception e){ JOptionPane. case 4: msg = "four".swing.showMessageDialog(null. case 10: msg = "ten". case 2: msg = "two". case 9: msg = "nine". break. /** * Transforms a number input from 1-10 to words using switch.D. int input = 0. case 7: msg = "seven". break. case 8: msg = "eight". break.showInputDialog ("Enter number")). break.parseInt (JoptionPane. case 3: msg = "three"."Invalid input"). //gets the input string input = Integer. break.E.exit(0).msg). System. default: msg = "Invalid number". break.JOptionPane.

J.E.D.I

} } import javax.swing.JOptionPane; /** * Computes the power of a number given the base and the exponent. * The exponent is limited to positive numbers only. */ public class Powers { public static void main(String[] args){ int int int int base = 0; exp = 0; power = 1; counter = 0;

//gets the user input for base and power using JOptionPane try{ base = Integer.parseInt (JoptionPane.showInputDialog ("Base")); exp = Integer.parseInt (JoptionPane.showInputDialog ("Exponent")); }catch(NumberFormatException e){ JoptionPane.showMessageDialog (null,"Input Error"); System.exit(0); } //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.showMessageDialog (null,"Positive numbers only please"); System.exit(0); } //for loop for computing the power for(;counter < exp;counter++){ power = power*base; } //displays the result JoptionPane.showMessageDialog (null,base+" to the "+exp +" is "+power);

}

}

Introduction to Programming I

291

J.E.D.I

Appendix D : Machine Problems Machine Problem 1: Phone Book
Write a program that will create an phonebook, wherein you can add entries in the phonebook, delete entries, view all entries and search for entries. In viewing all entries, the user should have a choice, whether to view the entries in alphabetical order or in increasing order of telephone numbers. In searching for entries, the user should also have an option to search entries by name or by telephone numbers. In searching by name, the user should also have an option if he/she wants to search by first name or last name. MAIN MENU 1 - Add phonebook entry 2 - Delete phonebook entry 3 - View all entries a - alphabetical order b - increasing order of telephone numbers 4 - Search entries a - by name b - by telephone number 5 – Quit The following will appear when one of the choices in the main menu is chosen. Add phonebook entry Enter Name: Enter Telephone number: (* if entry already exists, warn user about this) View all entries Displays all entries in alphabetical order Displays all entries in increasing order of telephone #s Search entries Search phonebook entry by name Search phonebook entry by telephone number Quit close phonebook

Introduction to Programming I

292

J.E.D.I

Machine Problem 2: Minesweeper
This is a one player game of a simplified version of the popular computer game minesweeper. First, the user is asked if he or she wants to play on a 5x5 grid or 10x10 grid. You have two 2-dimensional arrays that contains information about your grid. An entry in the array should either contain a 0 or 1. A 1 signifies that there is a bomb in that location, and a 0 if none. For example, given the array: int bombList5by5[][]={{0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 0, 1, 1}, {0, 1, 1, 0, 0}}; Given the bomb list, we have 6 bombs on our list. The bombs are located in (row,col) cells, (0,2), (2,1), (3,3), (3,4), (4,1) and (4,2). If the user chooses a cell that contains a bomb, the game ends and all the bombs are displayed. If the user chooses a cell that does not contain a bomb, a number appears at that location indicating the number of neighbors that contain bombs. The game should end when all the cells that do not contain bombs have been marked (player wins) or when the user steps on a bomb(player loses). Here's a sample output of the game, given the bombList5by5. Welcome to Minesweeper! Choose size of grid (Press 1 for 5x5, Press 2 for 10x10): 1 [][][][][] [][][][][] [][][][][] [][][][][] [][][][][] Enter row and column of the cell you want to open[row col]: 1 1 [][][][][] [ ] [2] [ ] [ ] [ ] [ ] [ ] [] [ ] [ ] [][][][][] [][][][][] Enter row and column of the cell you want to open[row col]: 3 2 [][][][][] [ ] [2 ] [ ] [] [ ] [][][][][] [ ] [ ] [4 ] [ ] [ ] [][][][][] Enter row and column of the cell you want to open[row col]: 0 2 [] [ ] [ ] [ ] [ ] [ ] [2] [ ] [] [ ] [ ] [X ] [ ] [ ] [ ] [ ] [ ] [4] [ ] [ ] [][][][][] Ooppps! You stepped on a bomb. Sorry, game over!

Introduction to Programming I

293

J.E.D.I

Machine Problem 3: Number Conversion
Create your own scientific calculator that will convert the inputted numbers to the four number representations ( Decimal, Binary, Octal, Hexadecimal ). Your program should output the following menu on screen. MAIN MENU: Please type the number of your choice: 1 – Binary to Decimal 2 – Decimal to Octal 3 – Octal to Hexadecimal 4 – Hexadecimal to Binary 5 – Quit The following will appear when one of the choices in the main menu is chosen. Choice 1: Enter a binary number: 11000 11000 base 2 = 24 base 10 (goes back to main menu) Choice 2: Enter a Decimal number: 24 24 base 10 = 30 base 8 (goes back to main menu) Choice 3: Enter an Octal number: 30 30 base 8 = 18 base 16 (goes back to main menu) Choice 4: Enter a Hexadecimal number: 18 18 base 16 = 11000 base 2 Choice 1: Enter a binary number: 110A Invalid binary number! Enter a binary number: 1 1 base 2 = 1 base 10 (goes back to main menu) (user chooses 5) Goodbye! You can be more creative with your user interface if you want to, as long as the program outputs the correct conversion of numbers.

Introduction to Programming I

294

J.E.D.I

Appendix E : Hands-on Laboratory Note to the Teacher
This part of the manual is not included in the student's manual. You can give a copy of this to your students if you wish for them to do the exercises on their own. Some of the answers for "Creating your own" exercises are found in the last part of this section.

Chapter 1 Hands-on
None

Chapter 2 Hands-on
None

Introduction to Programming I

295

J.E.D.I

Chapter 3 Hands-on
3.1 Things to check before you start the lab
Once you installed J2SE SDK, please make sure you do the following: 1. Make sure the installation has set %JAVA_HOME% (Windows) or $JAVA_HOME (Solaris/Linux) environment variable to the installation directory of J2SE 1.4.2_06 (or later version) 2. Type "echo %JAVA_HOME%" (Windows) or "echo $JAVA_HOME" (Solaris/Linux) in a terminal window. You should see the following: c:\j2sdk1.4.2_06 (Windows) /usr/jdk/jdk1.4.2_06 (Solaris/Linux) 3. Make sure the installation has placed %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Solaris/Linux) in the "path" environment variable. Type "java -version" in a terminal window. You should see something like following: java version "1.4.2_06" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_06-b03) Java HotSpot(TM) Client VM (build 1.4.2_06-b03, mixed mode)

Introduction to Programming I

296

J.E.D.I

3.2 Write, Compile, and Run Hello Java Program
1. mkdir c:\lab 2. cd \lab 3. Create Hello.java using your editor of choice public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string "Hello world" on screen System.out.println("Hello world"); } }

4. Compile Hello.java javac Hello.java 5. Make sure Hello.class file has been created dir 6. Run the Hello program java Hello 7. Verify that the result is as following C:\lab>java Hello Hello world 8. Modify, compile, and run the Hello.java so that it prints the following "This is my first Java program" (instead of "Hello world")

Introduction to Programming I

297

I 3.java code in the source editor with the one in Chapter 2 while leaving the package statement on the top. Compile. Run Hello class • • Right click Hello. Modify the Hello class • Replace the code of Hello class of IDE generated Hello. and Run Hello Java Program using NetBeans 1.1 • • Windows: Start > All Programs > NetBeans 4.java code gets displayed in the source editor.Main) • Click Finish (from Figure 12. fill it with Hello • For Create Main Class field.D.java node under Hello->Source Packages->hello and select Run File (Shift+F6) Note that the Output window displays the result Introduction to Programming I 298 . Create a new NetBeans project and Hello main class • • • • Select File from the menu bar and select New Project. select General and Java Application Click Next. Start the NetBeans IDE 4. Under Choose Project. Under Name and Location pane. 4. 3.3 Write.E.1 > NetBeans IDE or click NetBeans IDE 4.Hello hello.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2. change it to hello.J.60 :Create new Java application • Note that the IDE generated Hello. (Figure-10 below) • For Project Name field.

Initializing.java java OutputVariable 3. } } 2. Print out the value of grade variable as following System.java using your editor of choice public class OutputVariable { public static void main( String[] args ){ int value = 10.I Chapter 4 Hands-on 4. x = 'A'. Verify that the result is as following C:\lab>java OutputVariable 10 The value of x=A 4. Printing Variables 1. Create OutputVariable. Introduction to Programming I 299 .out. char x. System.E.out.D.println( "The value of x=" + x ).1 Declaring.java as following and compile and run the code • • Define another primitive type as following double grade = 11.println( value ).J. Modify OutputVariable. Compile and run the code javac OutputVariable.println( "The value of grade =" + grade ).out. System.

E. Verify that the result is as following C:\lab>java ConditionalOperator Passed 4.I 4. compile and run the code int salary = 100000. } } 2.out. Compile and run the code javac ConditionalOperator.java using your editor of choice public class ConditionalOperator { public static void main( String[] args ){ String status = "". Modify ConditionalOperator.D.J. Print "poor" otherwise. Introduction to Programming I 300 . Print "rich" if the salary is over 50000. //get status of the student status = (grade >= 60)?"Passed":"Fail". //print status System.java java ConditionalOperator 3.println( status ). Create ConditionalOperator.2 Conditional Operator 1.java as following. int grade = 80.

in) ).D.java java GetInputFromKeyboard 3.out.J. } System.out.out.I Chapter 5 Hands-on 5.readLine(). }catch( IOException e ){ System.1 Getting Input From Keyboard via BufferedReader 1. compile and run the code • • Make the program to ask the following question Please enter your age Display the entered age as following • If the age is over 100.println("Hello " + name +"!").BufferedReader. Compile and run the code javac GetInputFromKeyboard. Modify GetInputFromKeyboard.InputStreamReader. display Hello <name> You are old! • Otherwise Hello <name> You are young! Introduction to Programming I 301 .java as following.java using your editor of choice import java. Create GetInputFromKeyboard. public class GetInputFromKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System. import java.IOException.io. try{ name = dataIn. } } 2. import java. String name = "".E.io.io. System.print("Please Enter Your Name:").println("Error!").

JOptionPane. } } 2. Create GetInputFromKeyboardJOptionPane.2 Getting Input From Keyboard via JOptionPane 1. Modify GetInputFromKeyboardJOptionPane.java java GetInputFromKeyboardJOptionPane Enter your name CTRL/C to close the application 3.showMessageDialog(null. msg).D. compile and run the code • • Make the program to ask the following question Please enter your age Display the entered age as following • If the age is over 100. Compile and run the code javac GetInputFromKeyboardJOptionPane.J. display Hello <name> You are old! • Otherwise Hello <name> You are young! Introduction to Programming I 302 .java as following. name=JOptionPane. public class GetInputFromKeyboardJOptionPane { public static void main( String[] args ){ String name = "". String msg = "Hello " + name + "!".E.JOptionPane.I 5.swing.showInputDialog("Please enter your name").java using your editor of choice import javax.

length."Bianca".i<names. } } if (foundName ) System.java using your editor of choice public class ForLoop { public static void main( String[] args ){ String names []= {"Beah".out."Lance".i++){ if (names [i ]. Compile and run the code javac ForLoop."Belle"."Ethan"}. Create ForLoop. break. boolean foundName =false.out."Yza". Modify ForLoop."Gem". } } 2.java as following.equals(searchName )){ foundName =true. compile and run the code • Change the code to use while loop Introduction to Programming I 303 .I Chapter 6 Hands-on 6. String searchName ="Yza".E.").D.J. else System."Nico".1 For Loop 1. Verify that the result is as following C:\lab>java ForLoop Yza is found! 4.println(searchName +" is not found.java java ForLoop 3. for (int i=0.println(searchName +" is found!").

Modify ArraySample. } } } 2.print( ages[i] ).out. Create ArraySample. i<ages.I Chapter 7 Hands-on 7. 101 to the next entry of the array.D. for( int i=0. ages[0].java java ArraySample 3. ages[1]. compile and run the code • Just before the for loop that prints out the value of each entry of the ages[] array.length.java as following. create another for loop in which a value of 100 is assigned to the first entry of the array.1 Arrays 1. and so on Introduction to Programming I 304 . Compile and run the code javac Arraysample.java using your editor of choice public class ArraySample { public static void main( String[] args ){ int[] ages = new int[100]. Verify the result is as following C:\lab>java ArraySample 000000000000000000000000000000000000000000000000000000000000000 00000000000000000 00000000000000000000 4.J. i++ ){ System.E.

out. //Call method test //and pass i to method test test( i ). Verify the result is as following C:\lab>java TestPassByValue 10 10 Introduction to Programming I 305 . } } 2. Create .E.J.out.I Chapter 8 Hands-on None Chapter 9 Hands-on 9.java using your editor of choice public class TestPassByValue { public static void main(String[] args){ int i = 10. //print the value of i System.println(i). i not changed System.D.1 Pass-by-Value 1.java java TestPassByValue 3. Compile and run the code javac TestPassByValue. } public static void test(int j){ // change value of parameter i j = 33.println(i). // print the value of i.

i++ ){ System. Verify the result is as following C:\lab>java TestPassByReference 10 11 12 50 51 52 Introduction to Programming I 306 .2 Pass-by-Reference 1. //print array values for (int i=0. //print array values again for (int i=0.java java TestPassByReference 3.java using your editor of choice public class TestPassByReference { public static void main(String[] args){ //create an array of integers int [] ages = {10. i<ages. } } public static void test(int[] arr){ // change values of array for (int i=0. 11. Create .out. } //call test and pass references to array test(ages). i<arr.println(ages[i]). i<ages.J. Compile and run the code javac TestPassByReference.length.I 9. i++ ){ arr[i] = i + 50.out.println(ages[i]).length. i++ ){ System.D.length. 12}.E. } } } 2.

integer1 = new Integer(5).D.J.java class EqualsTestInteger { public static void main(String[] arguments) { Integer integer1. .println("String2: " + str2).out. System.println("Same object? " + (str1 == str2)).println("Same value? " + str1. Compile and run the code javac EqualsTest.out. str2 = new String(str1).println("Integer2: " + integer2). Create EqualsTest.out.println("Same object? " + (str1 == str2)).I 9.E.println("Integer1: " + integer1). integer2. Create EqualsTestInteger. System.java java EqualsTestInteger Introduction to Programming I 307 periodicals. integer2 = new Integer(5). System.equals (integer2)).println("Integer1: " + integer1).3 Comparing Objects 1. integer1 = integer2.". str2 = str1. System.out.println("String1: " + str1).out. System.out. periodicals. System. System.out. str2.out. System. System.java using your editor of choice class EqualsTest { public static void main(String[] arguments) { String str1. str1 = "Free the bound periodicals.out. C:\lab>java EqualsTest String1: Free the bound String2: Free the bound Same object? true String1: Free the bound String2: Free the bound Same object? false Same value? true 4.out.out.out. } } 2.out.println("Same object? " + (integer1 == integer2)).java java EqualsTest 3. Verify the result is as following.println("Same object? " + (integer1 == integer2)).println("Same value? " + integer1.println("String1: " + str1).equals(str2)). System.out. System. System. periodicals.println("String2: " + str2). System. Compile and run the code javac EqualsTestInteger. periodicals. System. } } 5.println("Integer2: " + integer2).

return result. Create StudentRecordExample. result =(mathGrade+englishGrade+scienceGrade )/3.J.E. Create StudentRecord. } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount.D. Introduction to Programming I 308 . } } 2.java using your editor of choice public class StudentRecord { // instance variables private String name.I Chapter 10 Hands-on 10. private double average. } /** *Computes the average of the english. private double mathGrade. /** *Returns the name of the student */ public String getName(){ return name. private double englishGrade.1 Create your own class Using Text Editor: 1. } /** *Changes the name of the student */ public void setName(String temp ){ name =temp. private double scienceGrade.math and science *grades */ public double getAverage(){ double result =0. // static variables private static int studentCount = 0.java using your editor of choice public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord().

java StudentRecordExample.println(annaRecord. //set the name of the students annaRecord.setName("Cris").println ("Count="+StudentRecord. } } 3. Verify the result C:\lab1>java StudentRecordExample Anna Count=0 Introduction to Programming I 309 . StudentRecord crisRecord =new StudentRecord(). //print anna's name System. crisRecord. //print number of students System.getName()).I StudentRecord beahRecord =new StudentRecord().java) java StudentRecordExample 4.setName("Anna").out.java (or javac StudentRecord.E.D.out. beahRecord.J.setName("Beah"). Compile and run the code javac *.getStudentCount()).

J.E. Start the NetBeans IDE 4. select General and Java Application Click Next. (Figure-10 below) For Project Name field. change it to studentrecordexample.java code in the source editor with the one you have written before. 4.1 > NetBeans IDE or click NetBeans IDE 4. Modify the NetBeans generated code • Replace the NetBeans generated StudentRecordExample. Create a new NetBeans project and StudentRecordExample main class • • • • • • • Select File from the menu bar and select New Project. Write StudentRecord.1 (if you have not done so yet) • • Windows: Start > All Programs > NetBeans 4.Main) Click Finish 3.I Using Netbeans: 1. fill it with StudentRecordExample For Create Main Class field.StudentRecordExample (from studentrecordexample.D.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2. Under Choose Project.java Introduction to Programming I 310 . Under Name and Location pane.

6. Modify the NetBeans generated code • Replace the NetBeans generated StudentRecord.java code in the source editor with the one you have written before.java node under Hello->Source Packages>studentrecordexample and select Run File (Shift+F6) Note that the Output window displays the result Introduction to Programming I 311 . choose studentrecordexample from the drop-down menu (or you can type studentrecordexample) Click Finish 5. Run StudentRecordExample application • • Right click StudentRecordExample. The New Java Class window appears. for Class Name field.D.E. type StudentRecord for Package field.J. Under Name and Location pane.I • • • Right click StudentRecordExample project node and select New->Java Class.

call it myOwnRecord Call setName() method of the myOwnRecord object passing "myOwn" as the value to set Display the name of the myOwnRecord object Set Math grade of myOwnRecord object Set English grade of myOwnRecord object Set Science grade of myOwnRecord object Display the average grade of myOwnRecord 3.J. Modify StudentRecordExample. this method increase the static variable studentCount by 1 2. Run StudentRecordExample application Introduction to Programming I 312 .java as following • • • • • • • Create another StudentRecord object.. Modify StudentRecord.E.java as following • • • • Add setMathGrade(double grade) method Add setEnglishGrade(double grade) method Add setScienceGrade(double grade) method Add static method called increaseStudentCount().I Creating your own: 1.D.

If you experience compile errors. } } 3. Verify the result Name:Anna Name:Anna Average Grade:65..J. annaRecord.16666666666667 Introduction to Programming I 313 .setName("Anna").) methods. annaRecord. public void print(String name ){ System.5). Compile and run the code. annaRecord.println("Average Grade:"+averageGrade). annaRecord. Add two overloaded print(.out.java as follows public class StudentRecordExample2{ public static void main(String [] args) { StudentRecord annaRecord =new StudentRecord().Create StudentRecordExample2.setEnglishGrade(95. The code fragement that needs to be added is highlighted with bold. public class StudentRecord { . Modify StudentRecord.out. fix the compile errors.E.getName()).java as following.print(annaRecord.java StudentRecordExample2.. double averageGrade){ System. //overloaded methods annaRecord.setScienceGrade(100)..2 Overloading Using Text Editor: 1.out.getName().java) java StudentRecordExample2 4.getAverage()). System. annaRecord.print(annaRecord. javac *.I 10.print("Name:"+name+" "). } } 2.println("Name:"+name).D. } public void print(String name.java (or javac StudentRecord.

I Using Netbeans: It is assumed you are using the same NetBeans project you created in 10. Create StudentRecordExample2.E.java with the one of above while leaving the package statement at the top 4.java • • • • Right studentrecordexample package node (Not StudentRecordExample project node) and select New->Java Class Under Name and Location pane.D.1. Right click studentrecordexample package node (Not StudentRecordExample project node) and select Compile Package (F9) 5. type StudentRecordExamle2 Click Finish 3.J. 1.java • Replace the code of the NetBeans generated StudentRecordExample2. Modify the StudentRecord. for Class Name field. Right click StudentRecordExamle2 and select Run File Introduction to Programming I 314 .java 2. Modify the NetBeans generated StudentRecordExample2.

D.J.java as following • Add another print() method which takes the following three parameters • name • grade average • student count 2.I Creating your own: 1. Modify StudentRecord. Modify StudentRecordExmaple2.java as following • Invoke the newly added print() method Introduction to Programming I 315 .E.

E. return result.java and StudenRecordExample. please create StudentRecord. } } Introduction to Programming I 316 . /** *Returns the name of the student */ public String getName(){ return name. } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount.3 Packaging Please do this exercise at the command line instead of using NetBeans.J. private double scienceGrade. 0. If have used NetBeans to do the exercise 13 above.I 10. private double average. // static variables private static int studentCount = 0. private double englishGrade. result =(mathGrade+englishGrade+scienceGrade )/3. private double mathGrade.math and science *grades */ public double getAverage(){ double result =0. This is to learn the packaging structure without the help of NetBeans. } /** *Computes the average of the english. } /** *Changes the name of the student */ public void setName(String temp ){ name =temp.D.java as following public class StudentRecord { // instance variables private String name.

. Modify StudentRecord..java 4.getStudentCount()).getName()).. Modify StudentRecordExample. You will experience an NoClassDefFoundError exception. public class StudentRecord { .out. package studentpackage.println(annaRecord.out.ClassLoader.java as following to add a package statement. StudentRecord beahRecord =new StudentRecord(). Think about why you are getting this exception for a moment. //print number of students System. beahRecord.setName("Cris"). The code fragement that needs to be added is is in bold characters. public class StudentRecordExample{ . //print anna's name System.println ("Count="+StudentRecord.java as following to add a package statement. javac StudentRecord. crisRecord.lang.J. It is because the StudentRecordExample.java StudentRecordExample. package studentpackage.. //set the name of the students annaRecord. It is because the java runtime is trying to find StudentRecordExample. Run the code.NoClassDefFoundError: StudentRecordExample (wrong name: studentpackage/StudentRecordExample) at java. The code fragment that needs to be added is in bold characters.setName("Anna"). } } 1. Compile code.E. StudentRecord crisRecord =new StudentRecord(). • C:\lab>java StudentRecordExample Exception in thread "main" java.setName("Beah").D. } 2.lang. } 3.java now has a package statement which says the Java class file resides under studentpackage directory.class under studentpackage directory.I public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord().defineClass0(Native 317 Introduction to Programming I .

URLClassLoader.lang.net.findClass (URLClassLoader.URLClassLoader.loadClass (ClassLoader.run (URLClassLoader.defineClass (SecureClassLoader.lang.java C:\lab>dir studentpackage Volume in drive C is S3A1256D004 Volume Serial Number is 447E-6EBC Directory of C:\lab\studentpackage 07/06/2005 07/06/2005 07/06/2005 07/06/2005 07/06/2005 Introduction to Programming I 12:39 12:39 12:40 12:16 12:40 PM PM PM PM PM <DIR> <DIR> .java:55) at java. Note that the class files are now created under studentpackage directory not in the current directory javac studentpackage\StudentRecord.security. 1.URLClassLoader$1. .defineClass (ClassLoader.access$100 (URLClassLoader.class 1.doPrivileged (Native Method) at java. Compile the code using a directory structure.ClassLoader.ClassLoader..loadClass (ClassLoader.java 6.java:187) at java.java:194) at java.net.I Method) at java.AccessController.java StudentRecordExample.lang.net.java \lab\studentpackage\StudentRecordExample.425 StudentRecord.java under it.499 StudentRecord. You get this compile error because you are trying to compile the two Java files that are not present in the current directory anymore.java:123) at java.ClassLoader.misc.SecureClassLoader.loadClassInternal (ClassLoader.java:235) at java.java:289) at sun.java error: cannot read: StudentRecord.ClassLoader.defineClass (URLClassLoader.loadClass (Launcher.lang.net.class del StudentRecordExample.E.java move \lab\StudentRecord.java and StudentRecordExample.java:251) at java.java \lab\studentpackage\StudentRecord. You will experience compile errors as following.D. Compile code.java 880 318 .Launcher$AppClassLoader. The compilation should succeed. mkdir \lab\studentpackage move \lab\StudentRecordExample. Create a new directory called studentpackage and then move StudentRecord.java:539) at java.java studentpackage\StudentRecordExample.class C:\lab>javac StudentRecord.URLClassLoader.J. del StudentRecord.java 1 error 7.java:302) 5.java:274) at java.security.

You will experience NoClassDefFoundError because it is trying to find the class in the current directory instead of in the studentpackage directory.E. C:\lab>java studentpackage.java:194) at java.415.java:302) Introduction to Programming I 319 .856.lang.URLClassLoader$1.loadClass (Launcher.ClassLoader.lang. Run the code with propert package structure.access$100 (URLClassLoader.loadClassInternal (ClassLoader.misc.defineClass (ClassLoader.lang.defineClass (SecureClassLoader.I StudentRecordExample.java:289) at sun. It should work this time.J.lang.loadClass (ClassLoader.net.java:251) at java.loadClass (ClassLoader. It is because it is still looking for studentpackage/StudentRecordExample.URLClassLoader.defineClass (URLClassLoader.java:55) at java.ClassLoader. C:\lab>cd studentpackage C:\lab\studentpackage>java StudentRecordExample Exception in thread "main" java.Launcher$AppClassLoader. Run the code as follows.ClassLoader. And the following is what you will experience.net.ClassLoader.security.defineClass0(Native Method) at java. C:\lab>java StudentRecordExample Exception in thread "main" java.lang.ClassLoader.lang.class in the currently directory and it could not find it.java:187) at java.NoClassDefFoundError: StudentRecordExample 9.URLClassLoader.D.NoClassDefFoundError: StudentRecordExample (wrong name: studentpackage/StudentRecordExample) at java.net.java:539) at java.URLClassLoader.run (URLClassLoader.java:123) at java.class 07/06/2005 12:17 PM 690 StudentRecordExample.494 bytes 2 Dir(s) 1.128 bytes free 8.doPrivileged(Native Method) at java.findClass (URLClassLoader. Now you thught you should be able to run the application under the studentpackage directory itself so you go into the directory and run the code.AccessController.lang.java:235) at java.SecureClassLoader.security.java:274) at java.java 4 File(s) 4.net.StudentRecordExample Anna Count=0 10.

J.E.StudentRecordExample Anna Count=0 Creating your own: 1.fruitpackage Add a couple of methods of your own 2.java should have the following package statement at the top • package foodpackage.I 11.NoClassDefFoundError: StudentRecordExample C:\lab\studentpackage>java -classpath \lab studentpackage.lang. Create a class called Food under foodpackage. Create a class called FoodMain under foodpackage. Compile and run the code Introduction to Programming I 320 .fruitpackage package • • FoodMain class creates an Food object FoodMain class then calls a method of Food object 3. Now there is a way you can specify the classpath using -classpath command line option as following: C:\lab\studentpackage>java -classpath \lab StudentRecordExample Exception in thread "main" java.D.fruitpackage pacakge • • Food.

println("Inside Person:Constructor 2 receiving two parameters: " + name + ".I Chapter 11 Hands-on 11. this.println("Inside Person:Constructor").E.address = address.java package personpackage. } public void setAddress(String s){ address = s.1 Inheritance – Constructor 1. } public void setName(String s){ name = s. } public String getAddress(){ return address. } public String getName(){ System.println("Person: getName()"). } } Introduction to Programming I 321 . } public Person (String name.D. public class Person { private String name.J.out. this.out. Write Person. private String address. String address){ System.out. " + address).name = name. public Person(){ System. return name.

java java personpackage. public String getHobby(){ return hobby. Compile and run the code using a directory structure. } public void setHobby(String s){ hobby = s. cd \lab javac personpackage\*. Write Student. public class Student extends Person { private String hobby. } } 4.java package personpackage.I 2. } } } 3.D.Main 5. Verify the result is as following C:\lab>java personpackage. Write Main. public class Main { public static void main(String [] args ){ Student student1 =new Student().out. public Student(){ System.Main Inside Person:Constructor Inside Student:Constructor Introduction to Programming I 322 .E.java package personpackage.J.println("Inside Student:Constructor").

Main 8. Verify the result is as following C:\lab>java personpackage. System. Modify the Student.java java personpackage. cd \lab javac personpackage\*.println("Inside Student:Constructor"). public String getHobby(){ return hobby. Compile and run the code using a directory structure. } } } 7.Main Inside Person:Constructor 2 receiving two parameters: Sang. "1 Dreamland"). package personpackage.I 6. 1 Dreamland Inside Student:Constructor Introduction to Programming I 323 .E.J. } public void setHobby(String s){ hobby = s. public Student(){ super("Sang".D. The code fragment that needs to be added is in bold characters.java as following.out. public class Student extends Person { private String hobby.

java • • Right personpackage package node (not PersonPackage project node) and select New->Java Class Under Name and Location pane.java 6.I Using Netbeans: 1.java 4. Create Person. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9) 9.J.D. Create Student. Replace the code in the NetBeans generated Main. Replaced the code in the NetBeans generated Person. Replaced the code in the NetBeans generated Student. (Figure-10 below) • For Project Name field. • for Class Name field. Create a new NetBeans project and Main. Right click Main select Run File 10.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2.java 8. Start the NetBeans IDE 4. Under Choose Project. • for Class Name field.java main class • • • • Select File from the menu bar and select New Project. type Student • Click Finish 7.1 > NetBeans IDE or click NetBeans IDE 4. Under Name and Location pane.Modify the Student.java • Right personpackage node (not PersonPackage project node) and select New>Java Class • Under Name and Location pane.java. fill it with PersonPackage • Click Finish 3. select General and Java Application Click Next. Right click Main select Run File Introduction to Programming I 324 . 11. Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9) 12. type Person • Click Finish 5.E.1 (if you have not done so yet) • • Windows: Start > All Programs > NetBeans 4.

J. Student student3 =new TuftsStudent(). You should see the following: Inside Inside Inside Inside Inside Inside Inside Inside Person:Constructor Student:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Introduction to Programming I 325 . Write TuftsStudent.java to create an instance of TuftsStudent class as following TuftsStudent student2 =new TuftsStudent().println("Inside TuftsStudent:Constructor"). 3.out.E. Compile and run the code.I Creating your own: 1. } 2. Modify the Main.java as following • • TuftsStudent class extends Student class Write a constructor of the TuftsStudent class as following public TuftsStudent(){ System.D.

out.Overriding 1. package personpackage.setName("Sang").J.Main Inside Person:Constructor Inside Student:Constructor Person: getName() Calling getName() method: name is Sang Introduction to Programming I 326 .D.2 Inheritance . Compile and run the code using a directory structure.Main 3. public class Main { public static void main(String [] args ){ Student student1 =new Student(). The code fragment that needs to be added is in bold characters. System. } } 2.getName()).java as following. which is a parent class of Student class student1.println("Calling getName() method: name is " + student1.I 11.java java personpackage. Verify the result is as following C:\lab>java personpackage. Modify Main. // Calling methods defined in Person class. cd \lab javac personpackage\*.E.

out.out. public class Student extends Person { private String hobby. } // Override getName() method of the parent class public String getName(){ System. Verify the result is as following C:\lab>java personpackage. The code fragment that needs to be added is in bold characters. return "Passionate" + super.java as following. package personpackage. cd \lab javac personpackage\*. Compile and run the code using a directory structure.E.I 5. } public void setHobby(String s){ hobby = s.Main Inside Person:Constructor Inside Student:Constructor Student: getName() Person: getName() Calling getName() method: name is PassionateSang Introduction to Programming I 327 . public String getHobby(){ return hobby.getName(). } } } 6.java java personpackage.D.Main 7.println("Student: getName()").println("Inside Student:Constructor").J. Modify the Student. public Student(){ System.

Change Main.getHobby().out.J. Inside Inside Inside Inside Inside Inside Person:Constructor Student:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Person:Constructor 328 Introduction to Programming I . You should see the following result. // set hobbies of student2 and student3 student2. System.setHobby("dancing"). Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9) 6. Right click Main select Run File 4. // get hobbies of student2 and student3 String hobby2 = student2.println("Hobby of student2 " + hobby2).getHobby(). } 2. Right click Main select Run File Creating your own: 1. } public void setHobby(String s){ System. Modify the Student. Compile and run the code. String hobby3 = student3.I Using NetBeans: It is assumed you are using the same NetBeans project you are using the same NetBeans project you created in Chapter 10. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9) 3.java to invoke setHobby() and getHobby() methods of the newly created TuftsStudent object instances as follows. Modify the Main.out. student3.E. super.getHobby(). 2. In your TuftsStudent class.D.setHobby("swimming"). System.println("Inside TuftsStudent:setHobby() method").out.java.println("Inside TuftsStudent:getHobby() method").out. 1. return "My hobby is " + super. override getHobby() and setHobby() methods of the Student class as follows public String getHobby(){ System.println("Hobby of student3 " + hobby3).java 5.setHobby(s). 3.

I Inside Student:Constructor Inside TuftsStudent:Constructor Inside TuftsStudent:setHobby() method Inside TuftsStudent:setHobby() method Inside TuftsStudent:getHobby() method Hobby of student2 My hobby is swimming Inside TuftsStudent:getHobby() method Hobby of student3 My hobby is dancing Introduction to Programming I 329 .D.J.E.

} } Introduction to Programming I 330 . This is the same Person. private String address.E. } public void setAddress(String s){ address = s.println("Inside Person:Constructor"). return name.println("Inside Person:Constructor 2 receiving two parameters: " + name + ". public class Person { private String name. this.name = name.out.I 11.address = address. Write Person. this. } public String getName(){ System.java as in the previous exercise except the package name.println("Person: getName()").out.J. } public void setName(String s){ name = s.D. } public String getAddress(){ return address. public Person(){ System.3 Polymorphism 1.java. package polypackage. which you will write in the subsequent steps. String address){ System. } public Person (String name. Person class is a parent class of both Student and Employee classes.out. " + address).

" + address). package polypackage. Student class is a subclass of a Person class.out.getName(). address). String address){ super(name.J.I 2.println("Inside Student:Constructor 2 receiving two parameters: " + name + ".out.E.D. System.out. } public void setHobby(String s){ hobby = s. } } Introduction to Programming I 331 .println("Inside Student:Constructor"). } // Override getName() method of the parent class public String getName(){ System. } public Student (String name.java. } public String getHobby(){ return hobby. return "Passionate Student " + super. public class Student extends Person { private String hobby. public Student(){ System.println("Student: getName()"). Write Student.

String address){ super(name.D. return "Not so Passionate Employee " + super.println("Inside Employee:Constructor 2 receiving two parameters: " + name + ". public class Employee extends Person { private String hobby. address).J.E. } public void setHobby(String s){ hobby = s. Employee class is subclass of Person class. Write Employee.getName } (). package polypackage. public Employee(){ System. System.out.out.out.java. } Introduction to Programming I 332 . } public String getHobby(){ return hobby. } // Override getName() method of the parent class public String getName(){ System.println("Inside Employee:Constructor").println("Employee: getName()"). } public Employee(String name. " + address).I 3.

Employee employeeObject = new Employee("Young".java java polypackage. Note that depending on what object type the ref variable refers to.D. Verify the result is as following. "1 Dreamland"). //Person ref.java C:\lab>java polypackage. System. Compile and run the code using a directory structure.J.Main Inside Person:Constructor 2 receiving two parameters: Sang.Main 6. } } 5.getName(). System.I 4. points to an Employee object //getName of Employee class is called String temp2 = ref. 2 Dreamland Inside Employee:Constructor 2 receiving two parameters: Young. System. C:\lab>javac polypackage\*.E.out.java package polypackage. Student studentObject = new Student("Sang". Employee type or Student type. ref = employeeObject. cd \lab javac polypackage\*.out. "2 Dreamland"). points to a Student //getName of Student class is called String temp1=ref. public class Main { public static void main( String[] args ) { Person ref. proper method gets invoked. object ref = studentObject. Write Main. 1 Dreamland Inside Student:Constructor 2 receiving two parameters: Sang. 1 Dreamland Inside Person:Constructor 2 receiving two parameters: Young. //Person ref.getName().out.println( "temp1 -" + temp1 + "\n" ).println("\n").println( "temp2 -" + temp2 + "\n" ). 2 Dreamland Student: getName() Person: getName() temp1 -Passionate Student Sang Employee: getName() Person: getName() temp2 -Not so Passionate Employee Young Introduction to Programming I 333 .

E.D.I Introduction to Programming I 334 .J.

Replace the code in the NetBeans generated Main.java • • Right polypackage node (not PolyPackage project node) and select New->Java Class Under Name and Location pane. Under Name and Location pane. Create Employee. select General and Java Application Click Next.1 > NetBeans IDE or click NetBeans IDE 4. (Figure-10 below) • For Project Name field. type Student • Click Finish 7. fill it with PolyPackage • Click Finish 3.1 (if you have not done so yet) • • Windows: Start > All Programs > NetBeans 4.java • • Right polypackage node (not PolyPackage project node) and select New->Java Class Under Name and Location pane. Create Student. Start the NetBeans IDE 4.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2. • for Class Name field.D. type Person • Click Finish 5.java 8. Create a new NetBeans project and Main. Under Choose Project. Create Person. • for Class Name field. type Employee • Click Finish Introduction to Programming I 335 .E.I Using NetBeans: 1. • for Class Name field.java 4.java • • Right polypackage package node (not PolyPackage project node) and select New->Java Class Under Name and Location pane. Replaced the code in the NetBeans generated Student.J.java main class • • • • Select File from the menu bar and select New Project. Replaced the code in the NetBeans generated Person.java 6.

Right click polypackage pacakge node (not PolyPackage project node) and select Compile Package (F9) 14.out.Modify the Student.Main Inside Person:Constructor 2 receiving two parameters: Sang. Right click Main select Run File Creating your own: 1. C:\lab>java polypackage.println("Teacher: getName()"). Right click Main select Run File 12.java 13.java in which.java as following • • Teacher class extends Person class Teacher clsss also has the following method // Override getName() method of the parent class public String getName(){ System. 2 Dreamland Inside Employee:Constructor 2 receiving two parameters: Young. 1 Dreamland Inside Student:Constructor 2 receiving two parameters: Sang. 1 Dreamland Inside Person:Constructor 2 receiving two parameters: Young. return "Maybe Passionate Teacher" + super.getName().E. Modify the Main.D. 2 Dreamland Inside Person:Constructor 2 receiving two parameters: Wende.java 10. Replaced the code in the NetBeans generated Employee. Compile and run the code.J. You should see the following result. } 2. 21 New York Inside Teacher:Constructor 2 receiving two parameters: Wende.I 9. getName() method of the Teacher object gets called 3. Create another class called Teacher. 21 New York Student: getName() Person: getName() Passionate Student Sang temp1 -Passionate Student Sang Employee: getName() Person: getName() Not so Passionate Employee Young temp2 -Not so Passionate Employee Young Teacher: getName() Person: getName() temp3 -Maybe Passionate Teacher Wende Introduction to Programming I 336 . Right click polypackage package node (not PolyPackage project node) and select Compile Package (F9) 11.

Write Main. Note that you will experience a compile error since you cannot create an object instance from an abstract class.. Compile Livingthing. cd \lab javac abstractexercise\LivingThing.java package abstractexercise..java abstractexercise\Main.println("Living Thing breathing.java abstractexercise\Main.out..out. } 2..java and Main.").java. } public void eat(){ System.I 11. C:\lab>javac abstractexercise\LivingThing.D.E."). } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk().4 Abstract Classes 1. cannot be instantiated LivingThing x = new LivingThing(). Write abstract class called LivingThing.J.java abstractexercise\Main.LivingThing is abstract. public class Main { public static void main( String[] args ) { LivingThing x = new LivingThing().println("Living Thing eating. package abstractexercise. ^ 1 error Introduction to Programming I 337 .java. public abstract class LivingThing { public void breath(){ System.java:5: abstractexercise. } } 3.java 4.

Creating your own: 1.println("Human walks.. 2.java so that it calls dance(ds) method Introduction to Programming I 338 .java java abstractexercise.. package abstractexercise. } 3. Verify the result is as following. y.Main 8." + ds). Modify the Main.J.java that implements the dance() abstract method.java that extends the abstract LivingThing class package abstractexercise..out.I 5. Rewrite Main. Implement a concrete method in the Human.walk().java. C:\lab>java abstractexercise. Compile and run the code using a directory structure. public void dance(String ds){ System.. } } 7. cd \lab javac abstractexercise\*. } } 6. Human walks..walk().D. public class Human extends LivingThing { public void walk(){ System. Define another abstract method in the LivingThing.").java as following public abstract void dance(String dancingStyle). LivingThing y = new Human(). public class Main { public static void main( String[] args ) { Human x = new Human(). x. Write a concrete class called Human..println("Human dances..E.out.Main Human walks..

I 4. C:\lab>java abstractexercise..D.J. Compile and run the code.E.Main Human walks.. Human dances in Saturday Night Live Introduction to Programming I 339 .. You should see the following result.. Human dances in Swing Human walks.

cd \lab javac interfaceexercise\Relation.java interfaceexercise\Main.java and Main.java. Note that you will experience a compile error since you cannot create an object instance from an Interface. public class Main { public static void main( String[] args ) { Relation x = new Relation(). public boolean isEqual( Object a. cannot be instantiated Relation x = new Relation(). Write Relation.java 4. Object b).java which is an Interface.java:5: interfaceexercise. Compile Relation. } } 3.D. package interfaceexercise.J.java.java interfaceexercise\Main. public interface Relation { public boolean isGreater( Object a. ^ 1 error Introduction to Programming I 340 .E. package interfaceexercise. Object b). Object b).5 Interfaces 1 1. public boolean isLess( Object a. Write Main. C:\lab>javac interfaceexercise\Relation.Relation is abstract.I 11.java interfaceexercise\Main. } 2.

sqrt( (x2-x1)*(x2-x1) + (y2-y1)* (y2-y1) ). return (aLen == bLen). package interfaceexercise.getLength(). Object b){ double aLen = ((Line)a). return (aLen > bLen).getLength().double x2.I 5.E. } public boolean isLess( Object a. Write a concrete class that implements Relation.x2 = x2. Object b){ double aLen = ((Line)a).D. private double x2.x1 = x1.getLength(). return length.getLength(). } public boolean isGreater( Object a. this.double y2){ this. this. public class Line implements Relation { private double x1. public Line(double x1. private double y1. return (aLen < bLen). } } Introduction to Programming I 341 . this. double bLen = ((Line)b). private double y2. double bLen = ((Line)b).getLength().y2 = y2.double y1.y1 = y1. Object b){ double aLen = ((Line)a). } public double getLength(){ double length = Math. double bLen = ((Line)b). } public boolean isEqual( Object a.J.getLength().

out. 2.Main line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1.java.out.4142135623730951 Length of line3 is 5.out. 1. 1. 5.0.println("Length of line1 is " + line1. b1). System. System.0.4142135623730951 Length of line2 is 1.0.0. System. 5. boolean b1 = line1. 2. 3.0.getLength()).println("line1 is greater than line2: " + boolean b2 = line1. b2).out.println("Length of line2 is " + line2. boolean b3 = line3. Rewrite Main.0).E.println("line1 is equal with line3: " + b3). System.0.I 6.isEqual(line1. 3. 2. line2).Main 8.D.println("line1 is equal with line2: " + Line line3 = new Line(1.J.0. package interfaceexercise.0.isEqual(line1. System. Verify the result as following: C:\lab>java interfaceexercise. = new Line(2. line3).getLength()). Compile and run the code using a directory structure.out.isGreater(line1. cd \lab javac interfaceexercise\*.656854249492381 Introduction to Programming I 342 .java java interfaceexercise. } } 7. System.0).0).out.println("Length of line3 is " + line3.getLength()).0. line2). public class Main { public static void main( String[] args ) { Line line1 Line line2 = new Line(1.

D.Main line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1. You should see the following result • • C:\lab>java interfaceexercise.4142135623730951 Length of line3 is 5.656854249492381 1 is greater than 5 false 1 is equal with 5 false 1 is less than 5 true Introduction to Programming I 343 .E. 2.4142135623730951 Length of line2 is 1. 3. Modify Main class that compares two int type numbers.I Creating your own: 1. Create another implementation class called NumberComparison that implements Relation interface.J.

} 2. this. Write PersonInterface.out.I 11.out. public interface PersonInterface { public public public public String getName(). } } Introduction to Programming I 344 .name = name.println("Inside PersonImpl:Constructor"). } public void setAddress(String s){ address = s. public class PersonImpl implements PersonInterface { private String name.D. String getAddress(). } public String getAddress(){ return address. } public String getName(){ System.println("Inside PersonImpl:Constructor 2 receiving two parameters: " + name + ".6 Interfaces 2 1. public PersonImpl(){ System.address = address. void setName(String s). } public void setName(String s){ name = s. void setAddress(String s). } public PersonImpl (String name. this. String address){ System.println("PersonImpl: getName()").java which is an Interface.J. Write PersonImpl. package interfaceexercise2. " + address).out. package interfaceexercise2.java. private String address.E. return name. PersonImpl class implements PersonInterface Interface.

public interface StudentInterface extends PersonInterface { public String getHobby().out.java and PersonImpl. Compile PersonInterface. Write StudentInteface. package interfaceexercise2. Write StudentImpl. public class StudentImpl implements StudentInterface { private String hobby.D.println("StudentImpl: getHobby()"). } } Introduction to Programming I 345 . } public void setHobby(String s){ hobby = s. return hobby.java 4.java interfaceexercise2\PersonImpl.java. package interfaceexercise2. The StudentInteface interface extends PersonInterface interface. } 5. public void setHobby(String s).out. public StudentImpl(){ System.I 3.println("Inside StudentImpl:Constructor").java. cd \lab javac interfaceexercise2\PersonInterface. } public String getHobby(){ System.J.E.java.

} public String getHobby(){ System.java. javac interfaceexercise2\StudentInterface.java and StudentImpl.String) in interfaceexercise2.java.java:3: interfaceexercise2.java Introduction to Programming I 346 . Compilation should succeed.PersonInterface public class StudentImpl implements StudentInterface{ ^ 1 error 7.java interfaceexercise2\StudentImpl.D. return hobby.J.I 6. You will experience the compile error.out.java interfaceexercise2\StudentImpl. public class StudentImpl extends PersonImpl implements StudentInterface { private String hobby. } public void setHobby(String s){ hobby = s. This is because StudentImpl.println("StudentImpl: getHobby()").lang. Compile Studentnterface.java and StudentImpl. Modify StudentImpl.E. C:\lab>javac interfaceexercise2\StudentInterface.java.StudentImpl is not abstract and does not override abstract method setAddress(java. The code fragment that needs to be added is highlighted in bold font. public StudentImpl(){ System.java interfaceexercise2\StudentImpl. Compile Studentnterface.out.java did not implement all the abstract methods defined in both StudentInterface and PersonInteface interfaces. package interfaceexercise2.println("Inside StudentImpl:Constructor"). } } 8.

setName("Ann"). public class Main { public static void main(String [] args ){ StudentInterface student1 = new StudentImpl().out. Compile all the source code and run it. student1.I 9. Write Main.println("student1's hobby is " + s2).java java interfaceexercise2. String s1 = student1. String s2 = student1.Main 11.getName().J.getHobby().E.java. System.Main Inside PersonImpl:Constructor Inside StudentImpl:Constructor PersonImpl: getName() student1's name is Ann StudentImpl: getHobby() student1's hobby is Dancing Introduction to Programming I 347 . package interfaceexercise2.setHobby("Dancing").out. } } 10. javac interfaceexercise2\*. Verify the result is as following C:\lab>java interfaceexercise2.println("student1's name is " + s1). student1. System.D.

Write TuftsStudentImpl class. 3. int y). that it calls add and multiply methods of the 4. It should also "extend" StudentImpl class. Modify the Main. You should see the result something like following: C:\lab>java interfaceexercise2.D. public int add(int x.Main Inside PersonImpl:Constructor Inside StudentImpl:Constructor PersonImpl: getName() student1's name is Ann StudentImpl: getHobby() student1's hobby is Dancing Inside PersonImpl:Constructor Inside StudentImpl:Constructor PersonImpl: getName() tuftsstudent1's name is Mario StudentImpl: getHobby() tuftsstudent1's hobby is Tennis StudentImpl: add() tuftsstudent1's addition is 11 StudentImpl: multiply() tuftsstudent1's multiplication is 311.J. public double multiply(double p. Define the following new methods inside the TuftsStudentInterface interface. It should "extend" StudentInterface inteface. Write TuftsStudentInterface inteface. It "implements" TuftsStudentInterface.2 Introduction to Programming I 348 .I Creating your own: 1.java so TuftsStudentInterface interface. 2. double q).E.

} } } 2. Verify the result C:\lab>java exceptionexercise.java java exceptionexercise. } catch( ArrayIndexOutOfBoundsException exp ){ System. Write ExceptionExample.E. Compile and run the code using a directory structure. cd \lab javac exceptionexercise\*.ExceptionExample 3.out.J.out.println("Exception caught!").1 Exception Handling 1. public class ExceptionExample { public static void main( String[] args ){ try{ System.java package exceptionexercise.D.I Chapter 12 Hands-on 12.println( args[1] ).ExceptionExample Exception caught! Introduction to Programming I 349 .

getName()). StudentRecord myOwnRecord =new StudentRecord().setName("myOwn").increaseStudentCount(). //set the name of the students annaRecord.setName("Anna"). System.I Answers to Hands-on Exercises 10. StudentRecord.println("Average of my Own="+myOwnRecord. myOwnRecord.out.setEnglishGrade(90.setName("Cris").setName("Beah").increaseStudentCount().2). crisRecord. } } Introduction to Programming I 350 .setMathGrade(60.out.2).println(annaRecord. StudentRecord.E. StudentRecord beahRecord =new StudentRecord(). myOwnRecord.out.D.println(myOwnRecord.println ("Count="+StudentRecord.increaseStudentCount(). System.getAverage()).J. beahRecord. StudentRecord.increaseStudentCount().getName()).getStudentCount()).1 Create your own class StudentRecoredExample. StudentRecord. myOwnRecord. //print number of students System.out. //set grades myOwnRecord.setScienceGrade(70. StudentRecord crisRecord =new StudentRecord(). //print anna's name System.2).java public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord().

private double average. result =(mathGrade+englishGrade+scienceGrade )/3. } /** *Changes the name of the student */ public void setName(String temp ){ name =temp. } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount. return result.I StudentRecord. } /** *Computes the average of the english. // static variables private static int studentCount = 0. private double mathGrade. } public void setScienceGrade(double grade){ scienceGrade = grade.java public class StudentRecord { // instance variables private String name.J. private double scienceGrade.math and science *grades */ public double getAverage(){ double result =0. private double englishGrade. } public void setEnglishGrade(double grade){ englishGrade = grade. } public void setMathGrade(double grade){ mathGrade = grade.E. } } Introduction to Programming I 351 . /** *Returns the name of the student */ public String getName(){ return name. } public static void increaseStudentCount(){ studentCount++.D.

} /** *Changes the name of the student */ public void setName(String temp ){ name =temp.math and science *grades */ public double getAverage(){ double result =0. private double average. // static variables private static int studentCount = 0.I 10. private double mathGrade.J. result =(mathGrade+englishGrade+scienceGrade )/3. } public void setEnglishGrade(double grade){ englishGrade = grade. private double englishGrade. /** *Returns the name of the student */ public String getName(){ return name. } public static void increaseStudentCount(){ studentCount++. private double scienceGrade. } public void setMathGrade(double grade){ mathGrade = grade.E.D. } public void setScienceGrade(double grade){ scienceGrade = grade. return result.java public class StudentRecord { // instance variables private String name.2 Overloading StudentRecord. } Introduction to Programming I 352 . } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount. } /** *Computes the average of the english.

D. double averageGrade. int studentCount){ System.setName("Anna"). annaRecord.out. } } Introduction to Programming I 353 .print("Name:"+name+" "). annaRecord.out. //overloaded methods annaRecord.println("Student count:"+studentCount). annaRecord.getName()). annaRecord. } public void print(String name.J.out.java public class StudentRecordExample2{ public static void main(String [] args) { StudentRecord annaRecord =new StudentRecord().E.getName().print(annaRecord. System.setScienceGrade(100). annaRecord.print(annaRecord. System. } public void print(String name. System.print(annaRecord.getStudentCount()).I public void print(String name ){ System. double averageGrade){ System.5). annaRecord.println("Average Grade:"+averageGrade).println("Average Grade:"+averageGrade). } } StudentExample2.out.getAverage(). annaRecord.out.getName().setEnglishGrade(95.getAverage()).print("Name:"+name+" "). annaRecord.println("Name:"+name).out.

J. public class Food { //instance variables private String color = "white".E. Create Food.java under a proper directory structure FoodMain. public String getColor(){ return color.getColor } ()).fruitpackage.FoodMain 4.fruitpackage.java under a proper directory structure cd \lab mkdir foodpackage mkdir foodpackage\fruitpackage jedit foodpackage\fruitpackage\Food.java package foodpackage.out.3 Packaging 1.fruitpackage.D. public class FoodMain{ public static void main(String [] args ){ Food food1 =new Food().fruitpackage.println("Color of the food ="+food1. Create FoodMain.I 10. } 3. } } 2.java java foodpackage.java package foodpackage. Verify the result C:\lab>java foodpackage. System.FoodMain Color of the food =white Introduction to Programming I 354 .java Food. Compile and run the code cd \lab javac foodpackage\fruitpackage\*.

java public class Main { public static void main(String [] args ){ Student student1 =new Student(). TuftsStudent student2 =new TuftsStudent(). } public String getHobby(){ System.D. return "My hobby is " + super.setHobby(s).println("Inside TuftsStudent:setHobby() method"). } } 11. } } Introduction to Programming I 355 .out.out.println("Inside TuftsStudent:Constructor").java package personpackage.out.java public class TuftsStudent extends Student{ /** Creates a new instance of TuftsStudent */ public TuftsStudent() { System.J.2 Inheritance .E.out.println("Inside TuftsStudent:getHobby() method").Overriding TuftsStudent. /** * * @author sang */ public class TuftsStudent extends Student{ /** Creates a new instance of TuftsStudent */ public TuftsStudent() { System. } } Main. super. Student student3 =new TuftsStudent().1 Inheritance – Constructor TuftsStudent.I 11.getHobby(). } public void setHobby(String s){ System.println("Inside TuftsStudent:Constructor").

out.setHobby("dancing").setHobby("swimming"). Student student3 =new TuftsStudent().I Main. System.D. TuftsStudent student2 =new TuftsStudent().E. String hobby3 = student3. // get hobbies of student2 and student3 String hobby2 = student2. // set hobbies of student2 and student3 student2.J.getHobby(). student3. System.java package personpackage.println("Hobby of student3 " + hobby3). public class Main { public static void main(String [] args ){ Student student1 =new Student(). } } Introduction to Programming I 356 .println("Hobby of student2 " + hobby2).getHobby().out.

out.J. System.out.I 11.println("\n").java package polypackage. Employee employeeObject = new Employee("Young".println( "temp1 -" + temp1 + "\n" ). } public Teacher(String name. " + address).out. public Teacher(){ System. points to a // Student object //getName of Student class is called String temp1=ref.D. "1 Dreamland"). public class Main { public static void main( String[] args ) { Person ref. points to an // Employee object Introduction to Programming I 357 . "21 New York").println("Teacher: getName()").E.println("Inside Teacher:Constructor").out.getName(). Student studentObject = new Student("Sang". } // Override getName() method of the parent class public String getName(){ System. Teacher teacherObject = new Teacher("Wende". String address){ super(name. //Person ref. System. "2 Dreamland").out.println("Inside Teacher:Constructor 2 receiving two parameters: " + name + ". ref = studentObject.out. public class Teacher extends Person { private String hobby. return "Maybe Passionate Teacher " + super.java package polypackage. ref = employeeObject.3 Polymorphism Teacher. address). } } Main. //Person ref.println( temp1 ). System. System.getName(). } public String getHobby(){ return hobby. } public void setHobby(String s){ hobby = s.

} public void eat(){ System. points to an // Teacher object //getName of Employee class is called String temp3 = ref..println( "temp2 -" + temp2 + "\n" ).getName(). } Introduction to Programming I 358 .getName().D.println( temp2 ).java package abstractexercise. System. } } 11.println( "temp3 -" + temp3 + "\n" ).J."). public abstract class LivingThing { public void breath(){ System. } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk()..4 Abstract Classes LivingThing. ref = teacherObject.. /** * abstract method dance * We want this method to be overridden by subclasses of * LivingThing */ public abstract void dance(String dancingStyle).out.out.println("Living Thing breathing. //Person ref. System..out.I //getName of Employee class is called String temp2 = ref.E.out.out. System.println("Living Thing eating.").

x.").walk().dance("Saturday Night Live").out. } } Introduction to Programming I 359 .J.E. y.I Human. LivingThing y = new Human(). y.walk().. } } Main.java package abstractexercise.dance("Swing"). public class Human extends LivingThing { public void walk(){ System.println("Human walks. public class Main { public static void main( String[] args ) { Human x = new Human().out.D. x.. } public void dance(String ds){ System.java package abstractexercise.println("Human dances in " + ds).

intValue() > bi. 3. line2).println("line1 is equal with line3: " + b3). Integer bi = (Integer)b.out. line2).D. System.isEqual(line1. Object b){ Integer ai = (Integer)a.out. boolean b3 = line3. public class Main { public static void main( String[] args ) { Line line1 Line line2 = new Line(1.out.0. Relation r1 = new NumberComparison().println(""). System. } public boolean isEqual(Object a.intValue() == bi. 2.I 11. System. 5.println("line1 is equal with line2: " + b2).println("Length of line1 is " + line1. Introduction to Programming I 360 .java package interfaceexercise. boolean b1 = line1.println("Length of line2 is " + line2.intValue()).println("line1 is greater than line2: " + boolean b2 = line1. public class NumberComparison implements Relation { public boolean isGreater(Object a. = new Line(2.0. 2.intValue()). System. Integer x = new Integer(1). Object b){ Integer ai = (Integer)a. 2. 1. System.isGreater(line1.out. } public boolean isLess(Object a. Integer bi = (Integer)b. line3). return (ai. 3.java package interfaceexercise.out.getLength()).0). Integer bi = (Integer)b.0.0. Integer y = new Integer(5).intValue() < bi. Line line3 = new Line(1.0. } } Main.5 Interfaces 1 NumberComparion.out.0. b1).J. return (ai. System.0). Object b){ Integer ai = (Integer)a. 1.getLength()).0.println("Length of line3 is " + line3.getLength()).isEqual(line1.0.E. return (ai. 5.out.0.0). System.intValue()).

+ " " + b6).E.out. System.isGreater(x.println(x + " is less than " + y + " " + b5).out. System. y). y).println(x + " is equal with " + y boolean b6 = r1.println(x + " is greater than " + y boolean b5 = r1.D.isLess(x.J. } + " " + } Introduction to Programming I 361 . System.isEqual(x.out. boolean b4 = r1. y).I b4).

println("StudentImpl: add()"). public double multiply(double p. student1. double q). System. int y).J. student1. tuftsstudent1.getHobby(). System.println("tuftsstudent1's name is " + s3). double q){ System. return x+y. Introduction to Programming I 362 .setHobby("Tennis").I 11. } TuftsStudentImpl.println("student1's hobby is " + s2). String s2 = student1. public interface TuftsStudentInterface extends StudentInterface { public int add(int x. int y){ System.setHobby("Dancing").6 Interfaces 2 TuftsStudentInterface.out. tuftsstudent1.E. public class TuftsStudentImpl extends StudentImpl implements TuftsStudentInterface { public int add(int x.println("").out.setName("Ann"). System. System. String s1 = student1.out.println("StudentImpl: multiply()").java package interfaceexercise2. String s3 = tuftsstudent1.getName(). public class Main { public static void main(String [] args ){ StudentInterface student1 = new StudentImpl().java package interfaceexercise2. } public double multiply(double p.D. TuftsStudentInterface tuftsstudent1 = new TuftsStudentImpl().java package interfaceexercise2.out.setName("Mario"). return p*q.out.getName().out.println("student1's name is " + s1). } } Main.

System. + d1).println("tuftsstudent1's addition is " + double d1 = tuftsstudent1.D.out.multiply(10.out.add(5. 6).println("tuftsstudent1's hobby is " + s4). 31.0.println("tuftsstudent1's multiplication is " i1).getHobby().I String s4 = tuftsstudent1.12).out. System.J. int i1 = tuftsstudent1. } } Introduction to Programming I 363 . System.E.

D.com/SiliconValley/Park/3230/java/javl1002. High-Level Programming Language.com/basic_flow_chart_symbols. Available at http://www. Available at http://home.Inheritance and Polymorphism.html 8.com at http://www.developer. February 2001. Java for Engineers and Scientists 2nd Edition.wikipedia. Available at http://home.webopedia. Available at http://java.Gary B.org/wiki/High-level_programming_language 5. Available at http://java.sun.html 3. Java How to Program 5th Edition.answers.com/docs/books/tutorial/java/nutsandbolts/branch. From Webopedia at http://www. Sun Microsystems. Variables and Expressions.php/983081 22. 23.html 7.html 27.com/TERM/I/integrated_development_environment. Writing Abstract Classes and Methods. Defining an Interface. Java Programming Complete Concepts and Techniques.com/TERM/p/programming_language.ca/~ve3ll/jatutor7.org/wiki/Programming_language 2.com/topic/programming-language 4. Thomas J. From Answers.The Essence of OOP using Java. Available at http://www.Sun Java Programming Student Guide SL-275. 26.sun.Stephen J.htm 6.html.J.Java Branching Statements.geocities. Joy L.com/docs/books/tutorial/java/interpack/interfaceDef.htm 21. Course Technology Thomson Learning.htm.com/tech/article.Deitel & Deitel.html 9. Shelly. Cashman.com/javaworld/javaqa/2000-05/03-qa-0526-pass.cogeco.com/docs/books/tutorial/java/javaOO/abstract. Defining Flowchart Symbols. 2001. Chapman.E. From Webopedia at http://www. Integrated Development Environment.Does Java pass by reference or pass by value? Why can't you swap in Java? Available at http://www.wikipedia.webopedia. From Wikipedia at http://en. Introduction to Programming I 364 . 2004 24.Encapsulation.sun. Pearson Prentice Hall. From Wikipedia at http://en. Programming Language.javaworld.html 20.ca/~ve3ll/jatutor4. Runtime Polymorphism through Inheritance.pattonpatton.cogeco. Programming Language. 25. 28. Starks. Programming Language. Available at http://www. Available at http://java.I References 1.

Sign up to vote on this title
UsefulNot useful