JEDI Course Notes Intro1 Master Document
JEDI Course Notes Intro1 Master Document
JEDI Course Notes Intro1 Master Document
Introduction to Programming I
Introduction to Programming I
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
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
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
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
J.E.D.I
Revision History
For Version 1.1 August 2005 Section Version Number Revision History Appendix E: Hands-on Lab Exercises
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
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
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
J.E.D.I
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
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
J.E.D.I
11 Inheritance, Polymorphism and Interfaces....................................................... 182 11.1 Objectives............................................................................................ 182 11.2 Inheritance.......................................................................................... 182 11.2.1 Defining Superclasses and Subclasses............................................... 183 11.2.2 The super keyword......................................................................... 185 11.2.3 Overriding Methods........................................................................ 186 11.2.4 Final Methods and Final Classes........................................................ 187 11.3 Polymorphism...................................................................................... 188 11.4 Abstract Classes................................................................................... 190 11.5 Interfaces............................................................................................ 192 11.5.1 Why do we use Interfaces?.............................................................. 192 11.5.2 Interface vs. Abstract Class.............................................................. 192 11.5.3 Interface vs. Class.......................................................................... 193 11.5.4 Creating Interfaces......................................................................... 193 11.5.5 Relationship of an Interface to a Class............................................... 195 11.5.6 Inheritance among Interfaces........................................................... 195 11.6 Exercises............................................................................................. 196 11.6.1 Extending StudentRecord................................................................ 196 11.6.2 The Shape abstract class................................................................. 196 12 Basic Exception Handling.............................................................................. 197 12.1 Objectives............................................................................................ 197 12.2 What are Exceptions?............................................................................ 197 12.3 Handling Exceptions.............................................................................. 197 12.4 Exercises............................................................................................. 200 12.4.1 Catching Exceptions1...................................................................... 200 12.4.2 Catching Exceptions 2..................................................................... 200 Appendix A : Java and Netbeans Installation......................................................... 201 Installing Java in Linux.................................................................................. 202 Installing Java in Windows............................................................................. 210 Installing Netbeans in Linux............................................................................ 213 Installing Netbeans in Windows....................................................................... 222 Appendix B: Getting to know your Programming Environment (Windows XP version).. 226 My First Java Program................................................................................... 226 Using a Text Editor and Console...................................................................... 227 Setting the Path........................................................................................ 240 Using Netbeans............................................................................................. 241 Appendix C : Answers to Exercises...................................................................... 251 Chapter 1 Exercises....................................................................................... 251 1.1 Writing Algorithms............................................................................... 251 1.2 Number Conversions............................................................................ 254 Chapter 2 (No exercises)................................................................................ 257 Chapter 3 Exercises....................................................................................... 258 3.1 Hello World!........................................................................................ 258 3.2 The Tree............................................................................................. 258 Chapter 4 Exercises....................................................................................... 259 4.1 Declaring and printing variables............................................................. 259 4.2 Getting the average of three numbers..................................................... 259 4.3 Output greatest value........................................................................... 260 4.4 Operator precedence............................................................................ 260 Chapter 5 Exercises....................................................................................... 261 5.1 Last 3 words (BufferedReader version).................................................... 261 5.2 Last 3 words (JOptionPane version)........................................................ 262 Chapter 6 Exercises....................................................................................... 263
Introduction to Programming I
J.E.D.I
6.1 Grades .............................................................................................. 263 6.2 Number in words................................................................................. 265 6.3 Hundred Times.................................................................................... 267 6.4 Powers............................................................................................... 270 Chapter 7 Exercises....................................................................................... 273 7.1 Days of the Week................................................................................. 273 7.2 Greatest number................................................................................. 274 Chapter 8 Exercises....................................................................................... 275 8.1 Print Arguments.................................................................................. 275 Chapter 9 Exercises....................................................................................... 276 9.1 Defining terms.................................................................................... 276 9.2 Java Scavenger Hunt............................................................................ 276 Chapter 10 Exercises..................................................................................... 277 10.1 Address Book Entry............................................................................ 277 10.2 AddressBook..................................................................................... 279 Chapter 11 Exercises..................................................................................... 284 11.1 Extending StudentRecord.................................................................... 284 11.2 Abstract Classes................................................................................ 287 Chapter 12 Exercises..................................................................................... 289 12.1 Catching Exceptions 1......................................................................... 289 12.2 Catching Exceptions 2......................................................................... 289 Appendix D : Machine Problems.......................................................................... 292 Machine Problem 1: Phone Book...................................................................... 292 Machine Problem 2: Minesweeper.................................................................... 293 Machine Problem 3: Number Conversion........................................................... 294 Appendix E : Hands-on Laboratory...................................................................... 295 Note to the Teacher....................................................................................... 295 Chapter 1 Hands-on...................................................................................... 295 Chapter 2 Hands-on...................................................................................... 295 Chapter 3 Hands-on...................................................................................... 296 3.1 Things to check before you start the lab ................................................. 296 3.2 Write, Compile, and Run Hello Java Program........................................... 297 3.3 Write, Compile, and Run Hello Java Program using NetBeans..................... 298 Chapter 4 Hands-on...................................................................................... 299 4.1 Declaring, Initializing, Printing Variables................................................. 299 4.2 Conditional Operator............................................................................ 300 Chapter 5 Hands-on...................................................................................... 301 5.1 Getting Input From Keyboard via BufferedReader..................................... 301 5.2 Getting Input From Keyboard via JOptionPane......................................... 302 Chapter 6 Hands-on...................................................................................... 303 6.1 For Loop............................................................................................. 303 Chapter 7 Hands-on...................................................................................... 304 7.1 Arrays................................................................................................ 304 Chapter 8 Hands-on...................................................................................... 305 Chapter 9 Hands-on...................................................................................... 305 9.1 Pass-by-Value..................................................................................... 305 9.2 Pass-by-Reference............................................................................... 306 9.3 Comparing Objects.............................................................................. 307 Chapter 10 Hands-on..................................................................................... 308 10.1 Create your own class......................................................................... 308 10.2 Overloading...................................................................................... 313 10.3 Packaging......................................................................................... 316 Chapter 11 Hands-on..................................................................................... 321
Introduction to Programming I
J.E.D.I
11.1 Inheritance Constructor.................................................................... 321 11.2 Inheritance - Overriding...................................................................... 326 11.3 Polymorphism.................................................................................... 330 11.4 Abstract Classes................................................................................ 337 11.5 Interfaces 1....................................................................................... 340 11.6 Interfaces 2....................................................................................... 344 Chapter 12 Hands-on..................................................................................... 349 12.1 Exception Handling............................................................................. 349 Answers to Hands-on Exercises....................................................................... 350 10.1 Create your own class......................................................................... 350 10.2 Overloading...................................................................................... 352 10.3 Packaging......................................................................................... 354 11.1 Inheritance Constructor.................................................................... 355 11.2 Inheritance - Overriding...................................................................... 355 11.3 Polymorphism.................................................................................... 357 11.4 Abstract Classes................................................................................ 358 11.5 Interfaces 1....................................................................................... 360 11.6 Interfaces 2....................................................................................... 362
Introduction to Programming I
10
J.E.D.I
1.2 Introduction
A computer is a machine that performs a variety of tasks according to specific instructions. It is a data processing machine which accepts data via an input device and its processor manipulates the data according to a program. The computer has two major components. The first one is the Hardware which is the tangible part of the computer. It is composed of electronic and mechanical parts. The second major component is the software which is the intangible part of a computer. It consists of data and the computer programs.
Introduction to Programming I
11
J.E.D.I
Introduction to Programming I
12
J.E.D.I
1.3.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. Examples of input devices are keyboards, mice and microphones. Examples of output devices are monitors, printers and speakers.
1.3.2 Software
A software is the program that a computer uses in order to function. It is kept on some hardware device like a hard disk, but it itself is intangible. The data that the computer uses can be anything that a program needs. Programs acts like instructions for the processor. Some Types of Computer Programs: 1. Systems Programs Programs that are needed to keep all the hardware and software systems running together smoothly Examples: Operating Systems like Linux, Windows, Unix, Solaris, MacOS
2. Application Programs Programs that people use to get their work done Examples: Word Processor Game programs Spreadsheets
3. Compilers The computer understands only one language: machine language. Machine language is in the form of ones and zeros. 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, for this purpose, there exists compilers.
Introduction to Programming I
13
J.E.D.I
2. Low-level Assembly Language Assembly languages are similar to machine languages, but they are much easier to program in because they allow a programmer to substitute names for numbers. Assembly languages are available for each CPU family, and each assembly instruction is translated into one machine instruction by an assembler program.
Note: The terms "high-level" and "low-level" are inherently relative. Originally, assembly language was considered low-level and COBOL, C, etc. were considered high-level. Many programmers today might refer to these latter languages as low-level.
Introduction to Programming I
14
J.E.D.I
In order to understand the basic steps in solving a problem on a computer, let us define a single problem that we will solve step-by-step as we discuss the problem solving methodologies in detail. The problem we will solve will be defined in the next section.
Introduction to Programming I
15
J.E.D.I
Introduction to Programming I
16
J.E.D.I
YES
Introduction to Programming I
17
J.E.D.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.2: Example of a pseudocode
1.5.3.1 Flowcharting Symbols and their meanings A flowchart is a design tool used to graphically represent the logic in a solution. Flowcharts typically do not display programming language commands. Rather, they state the concept in English or mathematical notation. Here are some guidelines for commonly used symbols in creating flowcharts. You can use any symbols in creating your flowcharts, as long as you are consistent in using them. Symbol Name Meaning
Represents the process of executing a defined operation or groups of operations that results in a Process Symbol change in value, form, or location of information. Also functions as the default symbol when no other symbol is available. Represents an I/O function, which makes data available for processing (input) or displaying (output)of processed information.
Represents the sequence of available information and executable operations.The lines connect Flowline Symbol other symbols, and the arrowheads are mandatory only for right-to-left and bottom-totop flow. Represents the addition of descriptive information, comments, or explanatory notes as clarification. The vertical line and the broken line may be placed on the left, as shown, or on the right.
Annotation Symbol
Decision Symbol
Terminal Symbol
Introduction to Programming I
18
J.E.D.I
Symbol
Meaning
Represents any entry from, or exit to, another part of the flowchart. Also serves as an off-page connector.
Represents a named process consisting of one or more operations or program steps that are specified elsewhere.
Introduction to Programming I
19
J.E.D.I
1.6.1 Decimal
We normally represent numbers in their decimal form. Numbers in decimal form are in base 10. This means that the only digits that appear are 0-9. Here are examples of numbers written in decimal form: 12610 (normally written as just 126) 1110 (normally written as just 11)
1.6.2 Binary
Numbers in binary form are in base 2. This means that the only legal digits are 0 and 1. We need to write the subscript 2 to indicate that the number is a binary number. Here are examples of numbers written in binary form: 11111102 10112
1.6.3 Octal
Numbers in octal form are in base 8. This means that the only legal digits are 0-7. We need to write the subscript 8 to indicate that the number is an octal number. Here are examples of numbers written in octal form: 1768 138
1.6.4 Hexadecimal
Numbers in hexadecimal form are in base 16. This means that the only legal digits are 09 and the letters A-F (or a-f, lowercase or uppercase does not matter). We need to write the subscript 16 to indicate that the number is a hexadecimal 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
Introduction to Programming I
20
J.E.D.I
1.6.5 Conversions
1.6.5.1 Decimal to Binary / Binary to Decimal To convert a decimal number to binary, continuously divide the number by 2 and get the remainder (which is either 0 or 1), and get that number as a digit of 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. We then get all the remainders starting from the last remainder, and the result is the binary form of the number. NOTE: For the last digit which is already less than the divisor (which is 2) just copy the value to the remainder portion. 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, writing the remainders from the bottom up, we get the binary number 11111102 To convert a binary number to decimal, we multiply the binary digit to "2 raised to the position of the binary number". We then add all the products to get the resulting decimal number. For Example: 11111102 = ?
Position
10
Binary Digits
Introduction to Programming I
21
J.E.D.I
1.6.5.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. However, instead of having 2 as the divisor, you replace it with 8(for octal) or 16 (for hexadecimal). For Example (Octal): 12610 = ? 8 Quotient 126 / 8 = 15 / 8 = 1/8= 15 1 Remainder 6 7 1
Write it this way
So, 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, 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. To do that, we will just replace the base number 2 with 8 for Octal and 16 for hexadecimal. For Example (Octal): 1768 = ? 10
Position
Octal Digits
6 6 x 80 = 6 7 x 81 = 56 1 x 82 = 64 TOTAL: 126
Introduction to Programming I
22
J.E.D.I
Hex Digits
1.6.5.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. We then convert each partition into its corresponding octal digit. The following is a table showing the binary representation of each octal digit. Octal Digit 0 1 2 3 4 5 6 7 Binary Representation 000 001 010 011 100 101 110 111
0 1
1 7
1 6
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. The result is the binary representation.
Introduction to Programming I
23
J.E.D.I
1.6.5.4 Binary to Hexadecimal / Hexadecimal to Binary To convert from binary numbers to hexadecimal, we partition the binary number into groups of 4 digits (from right to left), and pad it with zeros if the number of digits is not divisible by 4. We then convert each partition into its corresponding hexadecimal digit. The following is a table showing the binary representation of each hexadecimal digit. 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
16
1 7
1 E
Equivalent Hexadecimal number Converting hexadecimal numbers to binary is just the opposite of what is given above. Simply convert each hexadecimal digit into its binary representation (given the table) and concatenate them. The result is the binary representation.
Introduction to Programming I
24
J.E.D.I
1.7 Exercises
1.7.1 Writing Algorithms
Given the following set of tasks, create an algorithm to accomplish the following tasks. You may write your algorithms using pseudocodes or you can use flowcharts. 1. Baking Bread 2. Logging into your laboratory's computer 3. Getting the average of three numbers
Introduction to Programming I
25
J.E.D.I
2 Introduction to Java
2.1 Objectives
In this section, we will be discussing a little bit of Java history and what is Java Technology. We will also discuss the phases that a Java program undergoes. At the end of the lesson, the student should be able to: Describe the features of Java technology such as the Java virtual machine, garbage collection and code security Describe the different phases of a Java program
Introduction to Programming I
26
J.E.D.I
2.2.2.4 A deployment environment There are two main deployment environments: First, the JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on. The other main deployment environment is on your web browser. Most commercial browsers supply a Java technology interpreter and runtime environment.
Introduction to Programming I
27
J.E.D.I
2.2.3.3 Code Security Code security is attained in Java through the implementation of its Java Runtime Environment (JRE). The JRE runs code compiled for a JVM and performs class loading (through the class loader), code verification (through the bytecode verifier) and finally code execution. The Class Loader is responsible for loading all classes needed for the Java program. It adds security by separating the namespaces for the classes of the local file system from those that are imported from network sources. This limits any Trojan horse applications since local classes are always loaded first. After loading all the classes, the memory layout of the executable is then determined. This adds protection against unauthorized access to restricted areas of the code since the memory layout is determined during runtime. After loading the class and layouting of memory, 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. After all of these have been done, the code is then finally executed.
Introduction to Programming I
28
J.E.D.I
The first step in creating a Java program is by writing your programs in a text editor. Examples of text editors you can use are notepad, vi, emacs, etc. This file is stored in a disk file with the extension .java. After creating and saving your Java program, compile the program by using the Java Compiler. The output of this process is a file of Java bytecodes with the file extension . class. The .class file is then interpreted by the Java interpreter that converts the bytecodes into the machine language of the particular computer you are using.
Task Write the program Compile the program Run the program
Output File with .java extension File with .class extension (Java bytecodes) Program Output
Introduction to Programming I
29
J.E.D.I
3.2 Introduction
An IDE is a programming environment integrated into a software application that provides a GUI builder, a text or code editor, a compiler and/or interpreter and a debugger. This tutorial uses RedHat Linux as the operating system. Make sure that before you do this tutorial, you have installed Java and Netbeans in your system. For instructions on how to install Java and Netbeans, please refer to Appendix A. For the Windows XP version of this section, please refer to Appendix B. Before going into details, let us first take a look at the first Java program you will be writing.
Before we try to explain what the program means, let's first try to write this program in a file and try to run it.
Introduction to Programming I 30
J.E.D.I
Introduction to Programming I
31
J.E.D.I
Step 2: Open Terminal To open Terminal in Linux, click on Menu-> System Tools-> Terminal.
Introduction to Programming I
32
J.E.D.I
Step 3: Write your the source code of your Java program in the Text Editor
Figure 3.5: Writing the Source Code with the Text Editor
Introduction to Programming I
33
J.E.D.I
Step 4: Save your Java Program We will save our program on a file named "Hello.java", and we will be saving it inside a folder named MYJAVAPROGRAMS. To open the Save dialog box, click on the File menu found on the menubar and then click on Save.
Introduction to Programming I
34
J.E.D.I
After doing the procedure described above, a dialog box will appear as shown in Figure below.
Introduction to Programming I
35
J.E.D.I
Now, we'll create a new folder inside the root folder where we will save your programs. We shall name this folder MYJAVAPROGRAMS. Click on the button encircled in the figure below to create the folder. A dialog box named "New Folder" will then appear. Type on the "Folder Name" Textbox MYJAVAPROGRAMS, and click on the CREATE button.
Introduction to Programming I
36
J.E.D.I
Now that we've created the folder where we will save all the files, double click on that folder to open it.
Introduction to Programming I
37
J.E.D.I
You will see a similar figure as shown below after you clicked on MYJAVAPROGRAMS. The folder should be empty for now since it's a newly created folder and we haven't saved anything in it yet.
Introduction to Programming I
38
J.E.D.I
Now, in the Selection textbox, type in the filename of your program, which is "Hello.java", and then click on the OK button.
Figure 3.11: Saving the Source Code Inside the Created Folder
Introduction to Programming I
39
J.E.D.I
Now that you've saved your file, notice how the title of the frame changes from "Untitled 1 (modified) gedit" to "/root/MYJAVAPROGRAMS/Hello.java - gedit". Take note that if you want to make changes in your file, you can just edit it, and then save it again by clicking on File -> Save.
Introduction to Programming I
40
J.E.D.I
Step 5: Compiling your program Now, the next step is to compile your program. Go to the Terminal window we just opened a while ago. Typically, when you open the terminal window, it opens up and takes you directly to what is called your home folder. To see what is inside that home folder, type ls and then press ENTER. What you will see is a list of files and folders inside your home folder.
Now, you can see here that there is a folder named "MYJAVAPROGRAMS" which we have created a while ago, and where we saved our Hello.java program. Now let's go inside that directory.
Introduction to Programming I
41
J.E.D.I
To go inside a directory, you type in the command: cd [directory name]. The "cd" command stands for, change directory. In this case, since the name of our directory is MYJAVAPROGRAMS, you type in: cd MYJAVAPROGRAMS
Introduction to Programming I
42
J.E.D.I
Once inside the folder where your Java programs are, let us now start compiling your Java program. Take note that, you should make sure that the file is inside the folder where you are in. In order to do that, execute the "ls" command again to see if your file is inside that folder.
Introduction to Programming I
43
J.E.D.I
To compile a Java program, we type in the command: javac [filename]. So in this case, type in: javac Hello.java.
During compilation, javac adds a file to the disk called [filename].class, or in this case, Hello.class, which is the actual bytecode.
Introduction to Programming I
44
J.E.D.I
Step 6: Running the Program Now, assuming that there are no problems during compilation (we'll explore more of the problems encountered during compilation in the next section), we are now ready to run your program. To run your Java program, type in the command: java [filename without the extension], so in the case of our example, type in: java Hello You can see on the screen that you have just run your first Java program that prints the message, "Hello world!".
Introduction to Programming I
45
J.E.D.I
3.4.1 Errors
What we've shown so far is a Java program wherein we didn't encounter any problems in compiling and running. However, this is not always the case. As what we have discussed in the first part of this course, we usually encounter errors along the way. As discussed before, there are two types of errors. The first one is a compile-time error or also called as syntax error. The second one is the runtime error. 3.4.1.1 Syntax Errors Syntax errors are usually typing errors. You may have misspelled a command in Java or forgot to write a semi-colon at the end of a statement. Java attempts to isolate the error by displaying the line of code and pointing to the first incorrect character in that line. However, the problem may not be at the exact point. Other common mistakes are in capitalization, spelling, the use of incorrect special characters, and omission of correct punctuation. Let's take for example, our Hello.java program wherein we intentionally omit the semicolon at one statement and we try to type the incorrect spelling of a command.
Introduction to Programming I
46
J.E.D.I
See the error messages generated after compiling the program. 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, which should be spelled as static. The second error message suggests that there is a missing semicolon after your statement.
As a rule of thumb, if you encounter a lot of error messages, try to correct the first mistake in a long list, and try to compile the program again. Doing so may reduce the total number of errors dramatically. 3.4.1.2 Run-time Errors Run-time errors are errors that will not display until you run or execute your program. Even programs that compile successfully may display wrong answers if the programmer has not thought through the logical processes and structures of the program.
Introduction to Programming I
47
J.E.D.I
Introduction to Programming I
48
J.E.D.I
The second way to run Netbeans, is by clicking on Menu-> Programming-> More Programming Tools-> Netbeans.
Introduction to Programming I
49
J.E.D.I
After you've open NetBeans IDE, you will see a graphical user interface (GUI) similar to what is shown below.
Introduction to Programming I
50
J.E.D.I
Step 2: Make a project Now, let's first make a project. Click on File-> New Project.
Introduction to Programming I
51
J.E.D.I
Introduction to Programming I
52
J.E.D.I
Introduction to Programming I
53
J.E.D.I
Now, a New Application dialog will appear. Edit the Project Name part and type in "HelloApplication".
Introduction to Programming I
54
J.E.D.I
Now try to change the Application Location, by clicking on the BROWSE button.
Introduction to Programming I
55
J.E.D.I
A Select Project Location dialog will then appear. Double-click on the root folder.
Introduction to Programming I
56
J.E.D.I
The contents of the root folder is then displayed. MYJAVAPROGRAMS folder and click on the OPEN button.
Now
double-click
on
the
Introduction to Programming I
57
J.E.D.I
Location
and
Project
Folder
is
changed
to
Introduction to Programming I
58
J.E.D.I
Finally, on the Create Main Class textfield, type in Hello as the main class' name, and then click on the FINISH button.
Introduction to Programming I
59
J.E.D.I
Step 3: Type in your program Before typing in your program, let us first describe the main window after creating the project. As shown below, NetBeans automatically creates the basic code for your Java program. You can just add your own statements to the generated code. On the left side of the window, 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, where you set the Project location.
Introduction to Programming I
60
J.E.D.I
Now, try to modify the code generated by Netbeans. Ignore the other parts of the program for now, as we will explain the details of the code later. Insert the code: System.out.println("Hello world!"); after the statement, //TODO code application logic here.
Introduction to Programming I
61
J.E.D.I
Step 4: Compile your program Now, to compile your program, just click on Build -> Build Main Project.
Or, you could also use the shortcut button to compile your code.
Introduction to Programming I
62
J.E.D.I
If there are no errors in your program, you will see a build successful message on the output window.
Introduction to Programming I
63
J.E.D.I
Step 5: Run your program To run your program, click on Run-> Run Main Project.
Or you could also use the shortcut button to run your program.
Introduction to Programming I
64
J.E.D.I
Introduction to Programming I
65
J.E.D.I
3.6 Exercises
3.6.1 Hello World!
Using Netbeans, create a class named: [YourName]. The program should output on the screen: Welcome to Java Programming [YourName]!!!
Introduction to Programming I
66
J.E.D.I
4 Programming Fundamentals
4.1 Objectives
In this section, we will be discussing the basic parts of a Java program. We will start by trying to explain the basic parts of the Hello.java program introduced in the previous section. We will also be discussing some coding guidelines or code conventions along the way to help in effectively writing readable programs. At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals, primitive data types, variable types ,identifiers and operators Develop a simple valid Java program using the concepts learned in this chapter
The first line of the code, public class Hello indicates the name of the class which is Hello. In Java, all code should be placed inside a class declaration. We do this by using the class keyword. In addition, the class uses an access specifier public, which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). We will be covering packages and access specifiers later. The next line which contains a curly brace { indicates the start of a block. In this code, we placed the curly brace at the next line after the class declaration, however, we can also place this next to the first line of our code. So, we could actually write our code as: public class Hello { public class Hello {
or
Introduction to Programming I
67
J.E.D.I
The next three lines indicates a Java comment. A comment is something used to document a part of a code. It is not part of the program itself, but used for documentation purposes. It is good programming practice to add comments to your code. /** * My first java program */ A comment is indicated by the delimiters /* and */. Anything within these delimiters are ignored by the Java compiler, and are treated as comments. The next line, public static void main(String[] args) { or can also be written as, public static void main(String[] args) { indicates the name of one method in Hello which is the main method. The main method is the starting point of a Java program. All programs except Applets written in Java start with the main method. Make sure to follow the exact signature. The next line is also a Java comment, //prints the string "Hello world" on screen Now, we learned two ways of creating comments. The first one is by placing the comment inside /* and */, and the other one is by writing // at the start of the comment. The next line, System.out.println("Hello world!"); prints the text Hello World! on screen. The command System.out.println(), prints the text enclosed by quotation on the screen. The last two lines which contains the two curly braces is used to close the main method and class respectively. Coding Guidelines: 1. Your Java programs should always end with the .java extension. 2. Filenames should match the name of your public class. So for example, if the name of your public class is Hello, you should save it in a file called Hello.java. 3. You should write comments in your code explaining what a certain class does, or what a certain method do.
Introduction to Programming I
68
J.E.D.I
Introduction to Programming I
69
J.E.D.I
Introduction to Programming I
70
J.E.D.I
Introduction to Programming I
71
J.E.D.I
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.
Introduction to Programming I
72
J.E.D.I
Introduction to Programming I
73
J.E.D.I
Introduction to Programming I
74
J.E.D.I
To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. For example, '\'' '\"' //for single quotes //for double quotes
Although, String is not a primitive data type (it is a Class), we will just introduce String in this section. A String represents a data type that contains multiple characters. It is not a primitive data type, it is a class. It has its literal enclosed in double quotes(). For example, String message=Hello world!
Introduction to Programming I
75
J.E.D.I
Integral types has int as default data type. You can define its long value by appending the letter l or L. 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
Coding Guidelines: In defining a long value, a lowercase L is not recommended because it is hard to distinguish from the digit 1.
Introduction to Programming I
76
J.E.D.I
Introduction to Programming I
77
J.E.D.I
4.9 Variables
A variable is an item of data used to store state of objects. A variable has a data type and a name. The data type indicates the type of value that the variable can hold. The variable name must follow rules for identifiers.
Coding Guidelines: 1. It always good to initialize your variables as you declare them. 2. Use descriptive names for your variables. Like for example, if you want to have a variable that contains a grade for a student, name it as, grade and not just some random letters you choose. 3. Declare one variable per line of code. For example, the variable declarations, double exam=0; double quiz=10; double grade = 0; is preferred over the declaration, double exam=0, quiz=10, grade=0;
Introduction to Programming I
78
J.E.D.I
The program will output the following text on screen, 10 The value of x=A
Introduction to Programming I
79
J.E.D.I
As you can see, for the primitive variable num, the data is on the actual location of where the variable is. For the reference variable name, the variable just holds the address of where the actual data is.
Introduction to Programming I
80
J.E.D.I
4.10 Operators
In Java, there are different types of operators. There are arithmetic operators, relational operators, logical operators and conditional operators. 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.
Introduction to Programming I
81
J.E.D.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; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); //adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); //subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); //multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i System.out.println(" x * y = " + (x //dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i System.out.println(" x / y = " + (x numbers
//computing the remainder resulting from dividing System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); //mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x));
Introduction to Programming I
82
J.E.D.I
Here is the output of the program, Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 x + y = 34.695 Subtracting... i - j = -5 x - y = 20.255 Multiplying... i * j = 1554 x * y = 198.37 Dividing... i / j = 0 x / y = 3.8054 Computing the remainder... i % j = 37 x % y = 5.815 Mixing types... j + y = 49.22 i * x = 1016.58 Note: When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. The integer is implicitly converted to a floating-point number before the operation takes place.
Introduction to Programming I
83
J.E.D.I
--
op--
--
--op
The increment and decrement operators can be placed before or after an operand. When used before an operand, it causes the variable to be incremented or decremented by 1, and then the new value is used in the expression in which it appears. For example, int i = 10, int j = 3; int k = 0; k = ++j + i; //will result to k = 4+10 = 14
Introduction to Programming I
84
J.E.D.I
When the increment and decrement operators are placed after the operand, the old value of the variable will be used in the expression where it appears. For example, int i = 10, int j = 3; int k = 0; k = j++ + i; //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
J.E.D.I
Introduction to Programming I
86
J.E.D.I
Here's a sample program that uses relational operators, public class RelationalDemo { public static void main(String[] args) { //a few numbers int i = 37; int j = 42; int k = 42; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" k = " + k); //greater than System.out.println("Greater System.out.println(" i > System.out.println(" j > System.out.println(" k > than..."); j = " + (i > j)); //false i = " + (j > i)); //true j = " + (k > j)); //false or equal to..."); " + (i >= j)); //false " + (j >= i)); //true " + (k >= j)); //true
//greater than or equal to System.out.println("Greater than System.out.println(" i >= j = System.out.println(" j >= i = System.out.println(" k >= j =
//less than System.out.println("Less than..."); System.out.println(" i < j = " + (i < j)); //true System.out.println(" j < i = " + (j < i)); //false System.out.println(" k < j = " + (k < j)); //false //less than or equal to System.out.println("Less than or equal to..."); System.out.println(" i <= j = " + (i <= j)); //true System.out.println(" j <= i = " + (j <= i)); //false System.out.println(" k <= j = " + (k <= j)); //true //equal to System.out.println("Equal to..."); System.out.println(" i == j = " + (i == j)); //false System.out.println(" k == j = " + (k == j)); //true //not equal to System.out.println("Not equal to..."); System.out.println(" i != j = " + (i != j)); //true System.out.println(" k != j = " + (k != j)); //false } }
Introduction to Programming I
87
J.E.D.I
Here's the output from this program: Variable values... i = 37 j = 42 k = 42 Greater than... i > j = false j > i = true k > j = false Greater than or equal to... i >= j = false j >= i = true k >= j = true Less than... i < j = true j < i = false k < j = false Less than or equal to... i <= j = true j <= i = false k <= j = true Equal to... i == j = false k == j = true Not equal to... i != j = true k != j = false
Introduction to Programming I
88
J.E.D.I
Introduction to Programming I
89
J.E.D.I
4.10.4.1 && (logical AND) and & (boolean logical AND) Here is the truth table for && and &, x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE FALSE FALSE FALSE
The basic difference between && and & operators is that && supports short-circuit evaluations (or partial evaluations), while & doesn't. What does this mean? Given an expression, exp1 && exp2 && will evaluate the expression exp1, and immediately return a false value is exp1 is false. If exp1 is false, the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2. In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer. Here's a sample source code that uses logical and boolean AND, public class TestAND { public static void main( String[] args ){ int i = 0; int j = 10; boolean test= false; //demonstrate && test = (i > 10) && (j++ > 9); System.out.println(i); System.out.println(j); System.out.println(test); //demonstrate & test = (i > 10) & (j++ > 9); System.out.println(i); System.out.println(j); System.out.println(test);
Introduction to Programming I
90
J.E.D.I
The output of the program is, 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
J.E.D.I
4.10.4.2 || (logical OR) and | (boolean logical inclusive OR) Here is the truth table for || and |, x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE TRUE TRUE FALSE
The basic difference between || and | operators is that || supports short-circuit evaluations (or partial evaluations), while | doesn't. What does this mean? Given an expression, exp1 || exp2 || will evaluate the expression exp1, and immediately return a true value is exp1 is true. If exp1 is true, the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2. In contrast, the | operator always evaluates both exp1 and exp2 before returning an answer. Here's a sample source code that uses logical and boolean OR, public class TestOR { public static void main( String[] args ){ int i = 0; int j = 10; boolean test= false; //demonstrate || test = (i < 10) || (j++ > 9); System.out.println(i); System.out.println(j); System.out.println(test); //demonstrate | test = (i < 10) | (j++ > 9); System.out.println(i); System.out.println(j); System.out.println(test);
Introduction to Programming I
92
J.E.D.I
The output of the program is, 0 10 true 0 11 true Note, that the j++ on the line containing the || operator is not evaluated since the first expression (i<10) is already equal to true.
Introduction to Programming I
93
J.E.D.I
4.10.4.3 ^ (boolean logical exclusive OR) Here is the truth table for ^, x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE
Table 15: Truth table for ^
The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is false. Note that both operands must always be evaluated in order to calculate the result of an exclusive OR. Here's a sample source code that uses the logical exclusive OR operator, public class TestXOR { public static void main( String[] args ){ boolean val1 = true; boolean val2 = true; System.out.println(val1 ^ val2); val1 = false; val2 = true; System.out.println(val1 ^ val2); val1 = false; val2 = false; System.out.println(val1 ^ val2); val1 = true; val2 = false; System.out.println(val1 ^ val2);
Introduction to Programming I
94
J.E.D.I
4.10.4.4 ! (logical NOT) The logical NOT takes in one argument, wherein that argument can be an expression, variable or constant. Here is the truth table for !, x1 TRUE FALSE Result FALSE TRUE
Here's a sample source code that uses the logical NOT operator, public class TestNOT { public static void main( String[] args ){ boolean val1 = true; boolean val2 = false; System.out.println(!val1); System.out.println(!val2);
Introduction to Programming I
95
J.E.D.I
Introduction to Programming I
96
J.E.D.I
Here is another program that uses the ?: operator, class ConditionalOperator { public static void main( String[] args ){ int char score = 0; answer = 'a';
Introduction to Programming I
97
J.E.D.I
Given a complicated expression, 6%2*5+4/2+88-10 we can re-write the expression and place some parenthesis base on operator precedence, ((6%2)*5)+(4/2)+88-10; Coding Guidelines To avoid confusion in evaluating mathematical operations, keep your expressions simple and use parenthesis.
Introduction to Programming I
98
J.E.D.I
4.11 Exercises
4.11.1 Declaring and printing variables
Given the table below, declare the following variables with the corresponding data types and initialization values. Output to the screen the variable names together with the values. 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, Number = 10 letter = a result = true str = hello
Introduction to Programming I
99
J.E.D.I
Introduction to Programming I
100
J.E.D.I
Here is the complete source code: import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class GetInputFromKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ); String name = ""; System.out.print("Please Enter Your Name:"); try{ name = dataIn.readLine(); }catch( IOException e ){ System.out.println("Error!");
} }
Now let's try to explain each line of code: The statements, import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; indicate that we want to use the classes BufferedReader, InputStreamReader and IOException which is inside the java.io package. The Java Application Programming Interface (API) contains hundreds of predefined classes that you can use in your programs. These classes are organized into what we call packages. Packages contain classes that have related purpose. Just like in our example, the java.io package contains classes that allow programs to input and output data. The statements can also be rewritten as, import java.io.*; which will load all the classes found in the package, and then we can use those classes inside our program.
Introduction to Programming I
101
J.E.D.I
The next two statements, public class GetInputFromKeyboard { public static void main( String[] args ){ were already discussed in the previous lesson. This means we declare a class named GetInputFromKeyboard and we declare the main method. In the statement, BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ); we are declaring a variable named dataIn with the class type BufferedReader. Don't worry about what the syntax means for now. We will cover more about this later in the course. Now, we are declaring a String variable with the identifier name, String name = ""; This is where we will store the input of the user. The variable name is initialized to an empty String "". It is always good to initialize your variables as you declare them. The next line just outputs a String on the screen asking for the user's name. System.out.print("Please Enter Your Name:"); Now, the following block defines a try-catch block, try{ name = dataIn.readLine(); }catch( IOException e ){ System.out.println("Error!"); } This assures that the possible exceptions that could occur in the statement name = dataIn.readLine(); will be catched. We will cover more about exception handling in the latter part of this course, but 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
102
J.E.D.I
Now going back to the statement, name = dataIn.readLine(); the method call, dataIn.readLine(), gets input from the user and will return a String value. This value will then be saved to our name variable, which we will use in our final statement to greet the user, System.out.println("Hello " + name + "!");
Introduction to Programming I
103
J.E.D.I
Introduction to Programming I
104
J.E.D.I
The first statement, import javax.swing.JOptionPane; indicates that we want to import the class JOptionPane from the javax.swing package. We can also write this as, import javax.swing.*; The statement, name = JOptionPane.showInputDialog("Please enter your name"); creates a JOptionPane input dialog, which will display a dialog with a message, a textfield and an OK button as shown in the figure. This returns a String which we will save in the name variable. Now we create the welcome message, which we will store in the msg variable, String msg = "Hello " + name + "!"; The next line displays a dialog which contains a message and an OK button. JOptionPane.showMessageDialog(null, msg);
Introduction to Programming I
105
J.E.D.I
5.4 Exercises
5.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, Enter word1:Goodbye Enter word2:and Enter word3:Hello Goodbye and Hello
J.E.D.I
6 Control Structures
6.1 Objectives
In the previous sections, we have given examples of sequential programs, wherein statements are executed one after another in a fixed order. In this section, we will be discussing control structures, which allows us to change the ordering of how the statements in our programs are executed. At the end of the lesson, the student should be able to: Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed Use repetition control structures (while, do-while, for) which allow executing specific sections of code a number of times Use branching statements (break, continue, return) which allows redirection of program flow
6.2.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. The if-statement has the form, if( boolean_expression ) statement; or if( boolean_expression ){ statement1; statement2; . . . } where, boolean_expression is either a boolean expression or boolean variable.
Introduction to Programming I
107
J.E.D.I
if( grade > 60 ) System.out.println("Congratulations!"); or int grade = 68; if( grade > 60 ){ System.out.println("Congratulations!"); System.out.println("You passed!"); } Coding Guidelines: 1. The boolean_expression part of a statement should evaluate to a boolean value. That means that the execution of the condition should either result to a value of true or a false. 2. Indent the statements inside the if-block.For example, if( boolean_expression ){ //statement1; //statement2; }
Introduction to Programming I
108
J.E.D.I
Introduction to Programming I
109
J.E.D.I
Coding Guidelines: 1. To avoid confusion, always place the statement or statements of an if or if-else block inside brackets {}. 2. You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block.For example, if( boolean_expression ){ if( boolean_expression ){ ... } } else{ . . . }
Introduction to Programming I
110
J.E.D.I
Introduction to Programming I
111
J.E.D.I
For example, given the code snippet, int grade = 68; if( grade > 90 ){ System.out.println("Very good!"); } else if( grade > 60 ){ System.out.println("Very good!"); } else{ System.out.println("Sorry you failed"); }
Introduction to Programming I
112
J.E.D.I
Introduction to Programming I
113
J.E.D.I
where, switch_expression is an integer or character expression and, case_selector1, case_selector2 and so on, are unique integer or character constants. When a switch is encountered, Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression. The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure. If none of the cases are satisfied, the default block is executed. Take note however, that the default part is optional. A switch statement can have no default block. NOTES: Unlike with the if statement, the multiple statements are executed in the switch statement without needing the curly braces. When a case in a switch statement has been matched, all the statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed. To prevent the program from executing statements in the subsequent cases, we use a break statement as our last statement.
Introduction to Programming I
114
J.E.D.I
Coding Guidelines: 1. Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors. 2. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value. Also, the value provided to each case statement must be unique.
Introduction to Programming I
115
J.E.D.I
Introduction to Programming I
116
J.E.D.I
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
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.
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
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
J.E.D.I
System.out.println("There are " + count + " Beahs in the list"); 6.4.2.2 Labeled continue statement The labeled form of the continue statement skips the current iteration of an outer loop marked with the given label. outerLoop: for( int i=0; i<5; i++ ){ for( int j=0; j<5; j++ ){ System.out.println("Inside for(j) loop"); //message1 if( j == 2 ) continue outerLoop; } } System.out.println("Inside for(i) loop"); //message2
In this example, message 2 never gets printed since we have the statement continue outerloop which skips the iteration.
Introduction to Programming I
123
J.E.D.I
The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value. For example, return; We will cover more about return statements later when we discuss about methods.
Introduction to Programming I
124
J.E.D.I
6.5 Exercises
6.5.1 Grades
Get three exam grades from the user and compute the average of the grades. Output the average of the three exams. Together with the average, also include a smiley face in the output if the average is greater than or equal to 60, otherwise output :-(. 1. Use BufferedReader to get input from the user, and System.out to output the result. 2. Use JOptionPane to get input from the user and to output the result.
6.5.4 Powers
Compute the power of a number given the base and exponent. Do three versions of this program using a while loop, a do-while loop and a for-loop.
Introduction to Programming I
125
J.E.D.I
7 Java Arrays
7.1 Objectives
In this section, we will be discussing about Java Arrays. First, we are going to define what arrays are, and then we are going to discuss on how to declare and use them. At the end of the lesson, 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
An array stores multiple data items of the same datatype, in a contiguous block of memory, divided into a number of slots. Think of an array as a stretched variable a location that still has one identifier name, but can hold more than one value.
Introduction to Programming I
126
J.E.D.I
Introduction to Programming I
127
J.E.D.I
Examples are, //creates an array of boolean variables with ientifier //results. This array contains 4 elements that are //initialized to values {true, false, true, false} boolean results[] ={ true, false, true, false }; //creates an array of 4 double variables initialized //to the values {100, 90, 80, 75}; double []grades = {100, 90, 80, 75}; //creates an array of Strings with identifier days and //initialized. This array contains 7 elements String days[] = { Mon, Tue, Wed, Thu, Fri, Sat, Sun};
Introduction to Programming I
128
J.E.D.I
} Coding Guidelines:
1. It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration, int []arr = new int[100]; is preferred over, int []arr; arr = new int[100]; 2. The elements of an n-element array have indexes from 0 to n-1. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception. 3. You cannot resize an array.
Introduction to Programming I
129
J.E.D.I
} Coding Guidelines:
1. When creating for loops to process the elements of an array, use the array object's length field in the condition statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays. 2. Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example, final int ARRAY_SIZE = 1000; //declare a constant ... int[] ages = new int[ARRAY_SIZE];
Introduction to Programming I
130
J.E.D.I
Introduction to Programming I
131
J.E.D.I
7.7 Exercises
7.7.1 Days of the Week
Create an array of Strings which are initialized to the 7 days of the week. For Example, String days[] = {Monday, Tuesday.}; Using a while-loop, print all the contents of the array. (do the same for do-while and forloop)
Introduction to Programming I
132
J.E.D.I
8 Command-line Arguments
8.1 Objectives
In this section, we will study on how to process input from the command-line by using arguments pass onto a Java program. At the end of the lesson, 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
J.E.D.I
In the Java language, when you invoke an application, the runtime system passes the command-line arguments to the application's main method via an array of Strings. Each String in the array contains one of the command-line arguments. 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. In the previous example, the command-line arguments passed to the Sort application is an array that contains five strings which are: "5", "4", "3", "2" and "1". You can derive the number of command-line arguments with the array's length attribute. For example, int numberOfArgs = args.length; If your program needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a number. Here's a code snippet that converts a command-line argument to an integer, int firstArg = 0; if (args.length > 0){ firstArg = Integer.parseInt(args[0]); } parseInt throws a NumberFormatException (ERROR) if the format of args[0] isn't valid (not a number). Coding Guidelines: Before using command-line arguments, always check if the number of arguments before accessing the array elements so that there will be no exception generated.
Introduction to Programming I
134
J.E.D.I
Now, run netbeans and create a new project and name this CommandLineExample. Copy the code shown above and compile the code. Now, follow these steps to pass arguments to your program using Netbeans. Click on Projects (encircled below).
Introduction to Programming I
135
J.E.D.I
Right-click on the CommandLineExample icon, and a popup menu will appear. Click on Properties.
J.E.D.I
On the Arguments textbox, type the arguments you want to pass to your program. In this case we typed in the arguments 5 4 3 2 1. Then, click on the OK button.
Introduction to Programming I
137
J.E.D.I
As you can see here, the output to your program is the number of arguments which is 5, and the first argument which is 5.
Introduction to Programming I
138
J.E.D.I
8.4 Exercises
8.4.1 Print arguments
Get input from the user using command-line arguments and print all the arguments to the screen. For example, if the user entered, java Hello world that is all
Introduction to Programming I
139
J.E.D.I
Lion
Introduction to Programming I
140
J.E.D.I
With these descriptions, the objects in the physical world can easily be modeled as software objects using the properties as data and the behaviors as methods. 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.
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
When instantiated, each object gets a fresh set of state variables. However, the method implementations are shared among objects of the same class. Classes provide the benefit of reusability. Software programmers can use a class over and over again to create many objects.
Introduction to Programming I
Instance
Methods
141
J.E.D.I
9.3.2 Encapsulation
Encapsulation is the method of hiding certain elements of the implementation of a certain class. By placing a boundary around the properties and methods of our objects, we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways. 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. We will learn more about how Java implements encapsulation as we discuss more about classes.
100 km/h
Introduction to Programming I
Instance
Methods Variable
Class
142
J.E.D.I
The new operator allocates a memory for that object and returns a reference of that memory location to you. When you create an object, you actually invoke the class' constructor. The constructor is a method where you place all the initializations, it has the same name as the class.
Introduction to Programming I
143
J.E.D.I
9.4 Methods
9.4.1 What are Methods and Why Use Methods?
In the examples we discussed before, we only have one method, and that is the main() method. In Java, 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. 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. Parameters are also called function arguments. After the method has finished execution, it goes back to the method that called it. Now, 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. We can do this in Java by creating methods to solve a specific part of the problem. Taking a problem and breaking it into small, manageable pieces is critical to writing large programs.
Introduction to Programming I
144
J.E.D.I
public boolean equalsIgnoreCase Compares this String to another String, ignoring (String anotherString) case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.
Table 20: Sample Methods of class String
Using the methods, String char String str1 = "Hello"; x = str2.charAt(0); //will return the character H //and store it to variable x str2 = "hello";
//this will return a boolean value true boolean result = str1.equalsIgnoreCase( str1 );
Introduction to Programming I
145
J.E.D.I
In the given example, we called the method test and passed the value of i as parameter. The value of i is copied to the variable of the method j. Since j is the variable changed in the test method, it will not affect the variable value if i in main since it is a different copy of the variable. By default, all primitive data types when passed to a method are pass-by-value.
Introduction to Programming I
146
J.E.D.I
9.4.3.2 Pass-by-reference When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that, the method makes a copy of the reference of the variable passed to the method. However, unlike in pass-by-value, the method can modify the actual object that the reference is pointing to, since, although different references are used in the methods, the location of the data they are pointing to is the same. For example, class TestPassByReference { public static void main( String[] args ){ //create an array of integers int []ages = {10, 11, 12}; //print array values for( int i=0; i<ages.length; i++ ){ System.out.println( ages[i] ); } //call test and pass reference to array test( ages );
Pass ages as parameter which is copied to variable arr
//print array values again for( int i=0; i<ages.length; i++ ){ System.out.println( ages[i] ); }
public static void test( int[] arr ){ //change values of array for( int i=0; i<arr.length; i++ ){ arr[i] = i + 50; } }
Introduction to Programming I
147
J.E.D.I
Coding Guidelines: A common misconception about pass-by-reference in Java is when creating a swap method using Java references. Take note that Java manipulates objects 'by reference,' but it passes object references to methods 'by value.'" As a result, you cannot write a standard swap method to swap objects.
Introduction to Programming I
148
J.E.D.I
Introduction to Programming I
149
J.E.D.I
Now, given the two methods main and test in our previous examples, class TestPassByReference { public static void main( String[] args ){ //create an array of integers int []ages = {10, 11, 12}; //print array values for( int i=0; i<ages.length; i++ ){ System.out.println( ages[i] ); } //call test and pass reference to array test( ages ); //print array values again for( int i=0; i<ages.length; i++ ){ System.out.println( ages[i] ); }
B A
C }
public static void test( int[] arr ){ //change values of array for( int i=0; i<arr.length; i++ ){ arr[i] = i + 50; } }
In the main method, the scope of the variables are, ages[] - scope A i in B - scope B i in C scope C In the test method, the scope ofthe variables are, arr[] i in E - scope D - scope E
Introduction to Programming I
150
J.E.D.I
When declaring variables, only one variable with a given identifier or name can be declared in a scope. That means that if you have the following declaration, { } int test = 10; int test = 20;
your compiler will generate an error since you should have unique names for your variables in one block. However, you can have two variables of the same name, if they are not declared in the same block. For example, int test = 0; System.out.print( test ); //..some code here { int test = 20; System.out.print( test ); } When the first System.out.print is invoke, it prints the value of the first test variable since it is the variable seen at that scope. For the second System.out.print, the value 20 is printed since it is the closest test variable seen at that scope. Coding Guidelines: Avoid having variables of the same name declared inside one method to avoid confusion.
Introduction to Programming I
151
J.E.D.I
Introduction to Programming I
152
J.E.D.I
When we convert a data that has a large type to a smaller type, we must use an explicit cast. Explicit casts take the following form: (dataType)value where, dataType, is the name of the data type you're converting to value, is an expression that results in the value of the source type.
For example, double valDouble = 10.12; int valInt = (int)valDouble; //convert valDouble to int type double x = 10.2; int y = 2; int int result = (int)(x/y); //typecast result of operation to
Introduction to Programming I
153
J.E.D.I
This is true in the reverse, and you can use a superclass when a subclass is expected. There is a catch, however: Because subclasses contain more behavior than their superclasses, there's a loss in precision involved. Those superclass objects might not have all the behavior needed to act in place of a subclass object. For example, if you have an operation that calls methods in objects of the class Integer, using an object of class Number won't include many methods specified in Integer. Errors occur if you try to call methods that the destination object doesn't have. To use superclass objects where subclass objects are expected, you must cast them explicitly. You won't lose any information in the cast, but you gain all the methods and variables that the subclass defines. To cast an object to another class, you use the same operation as for primitive types: To cast, (classname)object where, classname, is the name of the destination class object, is a reference to the source object.
Introduction to Programming I
154
J.E.D.I
Note: that casting creates a reference to the old object of the type classname; the old object continues to exist as it did before.
The following example casts an instance of the class VicePresident to an instance of the class Employee; VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges, Employee emp = new Employee(); VicePresident veep = new VicePresident(); emp = veep; // no cast needed for upward use veep = (VicePresident)emp; // must cast explicitlyCasting
Introduction to Programming I
155
J.E.D.I
Introduction to Programming I
156
J.E.D.I
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.";
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: falsethey are not the same object in memory. Testing them using the equals() method also returns the expected answer: truethey have the same values.
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
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
Introduction to Programming I
160
J.E.D.I
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
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
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.
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
J.E.D.I
we use the keyword static to indicate that a variable is a static variable. So far, our whole code now looks like this. public class StudentRecord { private String name; private String address; private int age; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; private static int studentCount; } //we'll add more code here later
where, <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>[,]
Introduction to Programming I
164
J.E.D.I
The statement, return name; in our program signifies that it will return the value of the instance variable name to the calling method. Take note that the return type of the method should have the same data type as the data in the return statement. You usually encounter the following error if the two does not have the same data type, StudentRecord.java:14: incompatible types found : int required: java.lang.String return age; ^ 1 error
Introduction to Programming I
165
J.E.D.I
Another example of an accessor method is the getAverage method, public class StudentRecord { private String name; : : public double getAverage(){ double result = 0; result = ( mathGrade+englishGrade+scienceGrade )/3; } return result;
The getAverage method computes the average of the 3 grades and returns the result.
Introduction to Programming I
166
J.E.D.I
- means that the method can be called from objects outside the class - means that the method is static and should be called by typing, [ClassName].[methodName]. For example, in this case, we call the method StudentRecord.getStudentCount() - is the return type of the method. This means that the method should return a value of type int - the name of the method - this means that our method does not have any parameters
For now, getStudentCount will always return the value zero since we haven't done anything yet in our program in order to set its value. We will try to change the value of studentCount later on when we discuss constructors. Coding Guidelines: 1. Method names should start with a SMALL letter. 2. Method names should be verbs 3. Always provide documentation before the declaration of the method. You can use javadocs style for this. Please see example.
Introduction to Programming I 167
J.E.D.I
private static int studentCount; /** * Returns the name of the student */ public String getName(){ return name; } /** * Changes the name of the student */ public void setName( String temp ){ name = temp; } // other code here .... /** * Computes the average of the english, math and science * grades */ public double getAverage(){ double result = 0; result = ( mathGrade+englishGrade+scienceGrade )/3; } return result;
/** * returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; }
Introduction to Programming I
168
J.E.D.I
Now, here's a sample code of a class that uses our StudentRecord class. 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.setName("Anna"); beahRecord.setName("Beah"); crisRecord.setName("Cris"); //print anna's name System.out.println( annaRecord.getName() ); //print number of students System.out.println("Count="+StudentRecord.getStudentCount } record StudentRecord(); StudentRecord(); StudentRecord();
()); }
Introduction to Programming I
169
J.E.D.I
Introduction to Programming I
170
J.E.D.I
Introduction to Programming I
171
J.E.D.I
When we try to call this in the following main method, public static void main( String[] args ) { StudentRecord annaRecord = new StudentRecord(); annaRecord.setName("Anna"); annaRecord.setAddress("Philippines"); annaRecord.setAge(15); annaRecord.setMathGrade(80); annaRecord.setEnglishGrade(95.5); annaRecord.setScienceGrade(100); //overloaded methods annaRecord.print( annaRecord.getName() ); annaRecord.print( annaRecord.getEnglishGrade(), annaRecord.getMathGrade(), annaRecord.getScienceGrade());
we will have the output for the first call to print, Name:Anna Address:Philippines Age:15 we will have the output for the second call to print, Name:Anna Math Grade:80.0 English Grade:95.5 Science Grade:100.0 Always remember that overloaded methods have the following properties, the same name different parameters return types can be different or the same
Introduction to Programming I
172
J.E.D.I
J.E.D.I
Now, before we move on, let us go back to the static variable studentCount we have declared a while ago. The purpose of the studentCount is to count the number of objects that are instantiated with the class StudentRecord. So, what we want to do here is, everytime an object of class StudentRecord is instantiated, we increment the value of studentCount. A good location to modify and increment the value of studentCount is in the constructors, because it is always called everytime an object is instantiated. For example, public StudentRecord(){ //some initialization code here studentCount++; //add a student } public StudentRecord(String temp){ this.name = temp; studentCount++; //add a student } public StudentRecord(String name, String address){ this.name = name; this.address = address; studentCount++; //add a student } public StudentRecord(double mGrade, double eGrade, double sGrade){ mathGrade = mGrade; englishGrade = eGrade; scienceGrade = sGrade; studentCount++; //add a student }
Introduction to Programming I
174
J.E.D.I
Introduction to Programming I
175
J.E.D.I
10.8 Packages
Packages are Javas means of grouping related classes and interfaces together in a single unit (interfaces will be discussed later). This powerful feature provides for a convenient mechanism for managing a large group of classes and interfaces while avoiding potential naming conflicts.
J.E.D.I
Introduction to Programming I
177
J.E.D.I
Take note that you can set the classpath anywhere. You can also set more than one classpath, we just have to separate them by ;(for windows) and : (for Unix based systems). For example, set classpath=C:\myClasses;D:\;E:\MyPrograms\Java and for Unix based systems, export classpath=/usr/local/java:/usr/myClasses
Introduction to Programming I
178
J.E.D.I
In this example, the instance variable name and the method getName() can be accessed from other objects, as long as the object belongs to the same package where the class StudentRecord belongs to.
In this example, the instance variable name and the method getName() can be accessed from other objects.
Introduction to Programming I
179
J.E.D.I
In this example, the instance variable name and the method getName() can be accessed only from methods inside the class and from subclasses of StudentRecord. We will discuss about subclasses on the next chapter.
In this example, the instance variable name and the method getName() can be accessed only from methods inside the class.
Coding Guidelines: The instance variables of a class should normally be declared private, and the class will just provide accessor and mutator methods to these variables.
Introduction to Programming I
180
J.E.D.I
10.10 Exercises
10.10.1 Address Book Entry
Your task is to create a class that contains an address book entry. The following table describes the information that an adressbook entry has. 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, create the following: 1. Provide the necessary accessor and mutator methods for all the attributes. 2. Constructors
10.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). You should provide the following methods for the address book. 1. 2. 3. 4. Add entry Delete entry View all entries Update an entry
Introduction to Programming I
181
J.E.D.I
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.
Introduction to Programming I
182
J.E.D.I
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.
Introduction to Programming I
184
J.E.D.I
Introduction to Programming I
185
J.E.D.I
Introduction to Programming I
186
J.E.D.I
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
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
J.E.D.I
Going back to our main method, when we try to call the getName method of the reference Person ref, the getName method of the Student object will be called. Now, if we assign ref to an Employee object, the getName method of Employee will be called. public static main( String[] args ) { Person ref; Student Employee studentObject = new Student(); employeeObject = new Employee();
ref = studentObject; //Person reference points to a // Student object String temp = ref.getName(); //getName of Student //class is called System.out.println( temp ); ref = employeeObject; //Person reference points to an // Employee object String temp = ref.getName(); //getName of Employee //class is called System.out.println( temp );
This ability of our reference to change behavior according to what object it is holding is called polymorphism. Polymorphism allows multiple objects of different subclasses to be treated as objects of a single superclass, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to. Another example that exhibits the property of polymorphism is when we try to pass a reference to methods. Suppose we have a static method printInformation that takes in a Person object as reference, 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. public static main( String[] args ) { Student studentObject = new Student(); Employee employeeObject = new Employee(); printInformation( studentObject ); } printInformation( employeeObject );
Introduction to Programming I
189
J.E.D.I
In order to do this, we can create a superclass that has some methods with implementations and others which do not. This kind of class is called an abstract class. An abstract class is a class that cannot be instantiated. It often appears at the top of an object-oriented programming class hierarchy, defining the broad types of actions possible with objects of all subclasses of the class. Those methods in the abstract classes that do not have implementation are called abstract methods. To create an abstract method, just write the method declaration without the body and use the abstract keyword. For example, public abstract void someMethod();
Introduction to Programming I
190
J.E.D.I
Now, let's create an example abstract class. public abstract class LivingThing { public void breath(){ System.out.println("Living Thing breathing..."); } public void eat(){ System.out.println("Living Thing eating..."); } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk();
When a class extends the LivingThing abstract class, it is required to override the abstract method walk(), or else, that subclass will also become an abstract class, and therefore cannot be instantiated. For example, public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } } If the class Human does not override the walk method, we would encounter the following error message, Human.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, and use its subclasses to provide implementation details of the abstract class.
Introduction to Programming I
191
J.E.D.I
11.5 Interfaces
An interface is a special kind of block containing method signatures (and possibly constants) only. Interfaces define the signatures of a set of methods without the body. Interfaces define a standard and public way of specifying the behavior of classes. They allow classes, regardless of their location in the class hierarchy, to implement common behaviors. Note that interfaces exhibit polymorphism as well, 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.
Introduction to Programming I
192
J.E.D.I
However, you cannot create an instance from an interface. An example of this is: PersonInterface pi = new PersonInterface(); //COMPILE //ERROR!!!
Another common characteristic is that both interface and class can define methods. However, an interface does not have an implementation code while the class have one.
J.E.D.I
public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen > bLen); } public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen < bLen); } public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen); }
When your class tries to implement an interface, always make sure that you implement all the methods of that interface, or else, you would encounter this error, Line.java:4: Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.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. Once a set of standard method definition is created, you can write a single method to manipulate all of the classes that implement the interface.
Introduction to Programming I
194
J.E.D.I
Another example of a class that extends one super class and implements an interface is, public class ComputerScienceStudent extends Student implements PersonInterface, LivingThing { } //some code here
Take note that an interface is not part of the class inheritance hierarchy. Unrelated classes can implement the same interface.
Introduction to Programming I
195
J.E.D.I
11.6 Exercises
11.6.1 Extending StudentRecord
In this exercise, we want to create a more specialized student record that contains additional information about a Computer Science student. Your task is to extend the StudentRecord class that was implemented in the previous lessons. Add some attributes and methods that you think are needed for a Computer Science student record. Try to override some existing methods in the superclass StudentRecord, if you really need to.
Introduction to Programming I
196
J.E.D.I
} . . . 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.E.D.I
Exceptions thrown during execution of the try block can be caught and handled in a catch block. The code in the finally block is always executed. The following are the key aspects about the syntax of the try-catch-finally construct: The block notation is mandatory. For each try block, there can be one or more catch blocks, but only one finally block. The catch blocks and finally blocks must always appear in conjunction with the try block, and in the above order. A try block must be followed by at least one catch block OR one finally block, or both. Each catch block defines an exception handle. The header of the catch block takes exactly one argument, which is the exception its block is willing to handle. The exception must be of the Throwable class or one of its subclasses.
Let's take for example a code that prints the second argument when we try to run the code using command-line arguments. Suppose, there is no checking inside your code for the number of arguments and we just access the second argument args[1] right away, we'll get the following exception. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at ExceptionExample.main(ExceptionExample.java:5)
Introduction to Programming I
198
J.E.D.I
To prevent this from happening, we can place the code inside a try-catch block. The finally block is just optional. For this example, we won't use the finally block. public class ExceptionExample { public static void main( String[] args ){ System.out.println( args[1] ); }catch( ArrayIndexOutOfBoundsException exp ){ System.out.println("Exception caught!"); } } try{
So when we try to run the program again without arguments, the output would be, Exception caught!
Introduction to Programming I
199
J.E.D.I
12.4 Exercises
12.4.1 Catching Exceptions1
Given the following code: public class TestExceptions{ public static void main( String[] args ){ for( int i=0; true; i++ ){ System.out.println("args["+i+"]="+ args[i]); } } } Compile and run the TestExceptions program. 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.lang.ArrayIndexOutOfBoundsException: 3 at TestExceptions.main(1.java:4) Modify the TestExceptions program to handle the exception. 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.lang.ArrayIndexOutOfBoundsException: 3 Quiting...
Introduction to Programming I
200
J.E.D.I
Introduction to Programming I
201
J.E.D.I
Introduction to Programming I
202
J.E.D.I
Step 2: Go to the folder where you copied the Java installer. To go to the folder, type: cd /usr/java
Introduction to Programming I
203
J.E.D.I
To make sure that all installers you need are already in the folder, type: ls The ls (list) command will list all the files inside your directory.
Make your installer file executable by using the chmod command. To do this, type: chmod u+x jdk-1_5_0_01-linux-i586.bin
Introduction to Programming I
204
J.E.D.I
Step 3: Run the installer To run the installer, just type: ./jdk-1_5_0_01-linux-i586.bin
Introduction to Programming I
205
J.E.D.I
After pressing ENTER, you will see the license agreement displayed on the console. Just press enter, until you see the question: Do you agree to the above license terms? [yes or no]. Just type: yes, and press ENTER.
Figure 12.9: License agreement Figure 12.8: License agreement Introduction to Programming I 206
J.E.D.I
Just wait for the installer to finish unpacking all its contents and installing java.
Introduction to Programming I
207
J.E.D.I
Step 4: Creating symbolic links In order to run java commands anywhere, we need to create symbolic links for all the commands in JDK inside the /usr/local/bin directory. To do this, go to the directory:/usr/local/bin. Type: cd /usr/local/bin
Introduction to Programming I
208
J.E.D.I
Introduction to Programming I
209
J.E.D.I
Introduction to Programming I
210
J.E.D.I
Step 2: Run the installer To run the installer, just double-click on the installer icon. A J2SE installer dialog will then appear. Click on the radio button labeled "I accept the terms in the license agreement" and press NEXT.
Introduction to Programming I
211
J.E.D.I
Introduction to Programming I
212
J.E.D.I
Introduction to Programming I
213
J.E.D.I
Step 2: Go to the folder where you copied the Netbeans installer. To go to the folder, type: cd /usr/java
Introduction to Programming I
214
J.E.D.I
To make sure that all installers you need are already in the folder, type: ls The ls (list) command will list all the files inside your directory.
Make your installer file executable by using the chmod command. To do this, type: chmod u+x netbeans-4_0-bin-linux.bin
Introduction to Programming I
215
J.E.D.I
Figure
Introduction to Programming I
216
J.E.D.I
Click on the radio button that says "I accept the terms in the license agreement". And then click on NEXT.
For the directory name, change it to: /usr/java/netbeans-4.0, then click on NEXT.
Introduction to Programming I
217
J.E.D.I
For the JDK directory, choose /usr/java/jdk1.5.0_01, and then click on NEXT.
The next dialog just shows information about Netbeans thatyou will install. Just click again on NEXT.
Introduction to Programming I
218
J.E.D.I
J.E.D.I
Step 4: Creating symbolic links In order to run netbeans anywhere, we need to create symbolic link for it. To do this, go first to the directory:/usr/local/bin. Type: cd /usr/local/bin
J.E.D.I
Now, you can run netbeans in any directory by typing: netbeans &
Introduction to Programming I
221
J.E.D.I
Step 2: Run the installer To run the installer, just double-click on the installer icon. After clicking on the netbeans4_0-bin-windows icon, the Netbeans installation wizard will appear. Click on NEXT to enter installation process.
Introduction to Programming I
222
J.E.D.I
The agreement page will the appear. Choose to ACCEPT and click NEXT to continue.
Then you will be given the choice on which directory to place the Netbeans. You can move on by clicking NEXT or you can click on BROWSE to choose a different directory.
Introduction to Programming I
223
J.E.D.I
Next is choosing the Standard Edition JDKs from your machine. If you have finished installing Java, the jdk1.5.0_01 chould appear from your choices. Click on NEXT to continue.
It will then inform you the location and size of Netbeans which will be installed to your machine. Click on NEXT to finish installation.
J.E.D.I
You have installed Netbeans on your computer. Click on FINISH to complete installation.
Introduction to Programming I
225
J.E.D.I
Before we try to explain what the program means, let's first try to write this program in a file and try to run it.
Introduction to Programming I
226
J.E.D.I
Introduction to Programming I
227
J.E.D.I
Step 2: Open the Command Prompt window To open the MSDOS command prompt in Windows, click on start-> All programs-> Accessories-> Command Prompt.
Introduction to Programming I
228
J.E.D.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.java", and we will be saving it inside a folder named MYJAVAPROGRAMS. To open the Save dialog box, click on the File menu found on the menubar and then click on Save.
Introduction to Programming I
229
J.E.D.I
After doing the procedure described above, a dialog box will appear as shown in Figure below.
Figure 12.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.
Introduction to Programming I
230
J.E.D.I
Now, we'll create a new folder inside the My Documents folder where we will save your programs. We shall name this folder MYJAVAPROGRAMS. Click on the button encircled in the figure below to create the folder.
Figure 12.44: Click on the button encircled. This will open your "My Documents" folder
Figure 12.45: Clicking on the encircled button will create a New Folder.
Introduction to Programming I
231
J.E.D.I
After the folder is created, you can type in the desired name for this folder. In this case, type in MYJAVAPROGRAMS, and then press ENTER.
Introduction to Programming I
232
J.E.D.I
Now that we've created the folder where we will save all the files, double click on that folder to open it. You will see a similar figure as shown below. The folder should be empty for now since it's a newly created folder and we haven't saved anything in it yet.
Introduction to Programming I
233
J.E.D.I
Now click on the drop down list box "Save as type", so that we can choose what kind of file we want to save. Click on the "All Files" option.
Now, in the Filename textbox, type in the filename of your program, which is "Hello.java", and then click on the SAVE button.
Introduction to Programming I
234
J.E.D.I
Now that you've saved your file, notice how the title of the frame changes from UntitledNotepad to Hello.java-Notepad. Take note that if you want to make changes in your file, you can just edit it, and then save it again by clicking on File -> Save.
Introduction to Programming I
235
J.E.D.I
Step 5: Compiling your program Now, the next step is to compile your program. Go to the MSDOS command prompt window we just opened a while ago. Typically, when you open the command prompt window, it opens up and takes you directly to what is called your home folder. To see what is inside that home folder, type DIR or dir and then press ENTER. What you will see is a list of files and folders inside your home folder.
Figure 12.46: List of files and folders shown after executing the command DIR.
Now, you can see here that there is a folder named "My Documents" where we created your MYJAVAPROGRAMS folder. Now let's go inside that directory.
Introduction to Programming I
236
J.E.D.I
To go inside a directory, you type in the command: cd [directory name]. The "cd" command stands for, change directory. In this case, since the name of our directory is My Documents, you type in: cd My Documents.
Now that you are inside the "My Documents" folder, try typing in the "dir" command again, and tell me what you see.
Now perform the same steps described before to go inside the MYJAVAPROGRAMS folder.
Introduction to Programming I
237
J.E.D.I
Once inside the folder where your Java programs are, let us now start compiling your Java program. Take note that, you should make sure that the file is inside the folder where you are in. In order to do that, execute the dir command again to see if your file is inside that folder. To compile a Java program, we type in the command: javac [filename]. So in this case, type in: javac Hello.java.
During compilation, javac adds a file to the disk called [filename].class, or in this case, Hello.class, which is the actual bytecode.
Introduction to Programming I
238
J.E.D.I
Step 6: Running the Program Now, assuming that there are no problems during compilation (we'll explore more of the problems encountered during compilation in the next section), we are now ready to run your program. To run your Java program, type in the command: java [filename without the extension], so in the case of our example, type in: java Hello You can see on the screen that you have just run your first Java program that prints the message, "Hello world!".
Introduction to Programming I
239
J.E.D.I
If you are sure that you've already installed Java in your system, try setting the PATH variable to point to where the Java commands are installed. To do this, type in the command: set PATH=C:\j2sdk1.4.2_04\bin. This will tell your system to look for the commands in the C:\j2sdk1.4.2_04\bin folder, which is usually the default location wherein your Java files are placed during installation. After doing this, you can now use the Java commands.
Introduction to Programming I
240
J.E.D.I
Using Netbeans
Now that we've tried doing our programs the complicated way, let's now see how to do all the processes we've described in the previous sections by using just one application. In this part of the lesson, we will be using Netbeans, which is an Integrated Development Environment or IDE. An IDE is a programming environment integrated into a software application that provides a GUI builder, a text or code editor, a compiler and/or interpreter and a debugger. Step 1: Run Netbeans To run Netbeans, click on start-> All Programs-> NetBeans 4.0 -> NetBeans IDE
Introduction to Programming I
241
J.E.D.I
After you've open NetBeans IDE, you will see a graphical user interface (GUI) similar to what is shown below.
Introduction to Programming I
242
J.E.D.I
Step 2: Make a project Now, let's first make a project. Click on File-> New Project.
Introduction to Programming I
243
J.E.D.I
Now, a New Application dialog will appear. Edit the Project Name part and type in "HelloApplication".
Introduction to Programming I
244
J.E.D.I
Now try to change the Application Location, by clicking on the BROWSE button. Follow the steps described in the previous section to go to your MYJAVAPROGRAMS folder.
Finally, on the Create Main Class textfield, type in Hello as the main class' name, and then click on the FINISH button.
Introduction to Programming I
245
J.E.D.I
Step 3: Type in your program Before typing in your program, let us first describe the main window after creating the project. As shown below, NetBeans automatically creates the basic code for your Java program. You can just add your own statements to the generated code. On the left side of the window, 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, where you set the Project location.
Introduction to Programming I
246
J.E.D.I
Now, try to modify the code generated by Netbeans. Ignore the other parts of the program for now, as we will explain the details of the code later. Insert the code: System.out.println("Hello world!"); after the statement, //TODO code application logic here.
Step 4: Compile your program Now, to compile your program, just click on Build -> Build Main Project. Or, you could also use the shortcut button to compile your code.
Introduction to Programming I
247
J.E.D.I
Introduction to Programming I
248
J.E.D.I
If there are no errors in your program, you will see a build successful message on the output window.
Figure 12.57: Output window just below the window where you type your source code
Introduction to Programming I
249
J.E.D.I
Step 5: Run your program To run your program, click on Run-> Run Main Project. Or you could also use the shortcut button to run your program.
Introduction to Programming I
250
J.E.D.I
Introduction to Programming I
251
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.E.D.I
3. 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
J.E.D.I
110, 6
111, 7
100 4
Introduction to Programming I
254
J.E.D.I
2. 10010011012 to decimal, 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:
0100, 4
1101 D
001, 1
001, 1
101 5
Introduction to Programming I
255
J.E.D.I
110, 6
1110, E
Introduction to Programming I
256
J.E.D.I
4. 43F16 to binary, decimal and octal To Binary: 4 0100, Binary = 010000111111 To Decimal: F * 1 = 15 3 * 16 = 48 4 * 256 = 1024 TOTAL= 1087 Decimal = 1087 To Octal: 3 0011, F 1111
000 , 0
111 , 7
111 7
Introduction to Programming I
257
J.E.D.I
Chapter 3 Exercises
3.1 Hello World!
/** * This class prints the line "Welcome to Java Programming [YourName]!!!" * on screen. */ public class HelloWorld { public static void main(String[] args){ System.out.println("Welcome to Java Programming [YourName]!!!"); } }
Introduction to Programming I
258
J.E.D.I
Chapter 4 Exercises
4.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; //declares character letter with 'a' as initial value char letter = 'a'; //declares boolean result with true as initial value boolean result = true; //declares String str with "hello" as initial value String str = "hello"; //prints the values of the variables on screen System.out.println("Number = "+number); System.out.println("letter = "+letter); System.out.println("result = "+result); System.out.println("str = "+str);
//get the average of the three numbers // and saves it inside the ave variable int ave = (num1+num2+num3)/3; //prints the output on the screen System.out.println("number 1 = "+num1); System.out.println("number 2 = "+num2); System.out.println("number 3 = "+num3); System.out.println("Average is = "+ave);
Introduction to Programming I
259
J.E.D.I
Introduction to Programming I
260
J.E.D.I
Chapter 5 Exercises
5.1 Last 3 words (BufferedReader version)
import java.io.*; /** * 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.in)); //declares the String variables for the three words String firstWord = ""; String secondWord = ""; String thirdWord = ""; try{ System.out.print("Enter word1: "); firstWord = reader.readLine();//gets the 1st word System.out.print("Enter word2: "); secondWord = reader.readLine();//gets the 2nd word System.out.print("Enter word3: "); thirdWord = reader.readLine();//gets the 3rd word }catch( IOException e){ System.out.println("Error in getting input"); } //prints the phrase System.out.println(firstWord + " " + secondWord + " " + thirdWord); } }
Introduction to Programming I
261
J.E.D.I
Introduction to Programming I
262
J.E.D.I
Chapter 6 Exercises
6.1 Grades
Using BufferedReader: import java.io.*; /** * 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.in)); int firstGrade = 0; int secondGrade = 0; int thirdGrade = 0; double average = 0; try{ System.out.print("First grade: "); firstGrade = Integer.parseInt (reader.readLine()); System.out.print("Second grade: "); secondGrade = Integer.parseInt (reader.readLine()); System.out.print("Third grade: "); thirdGrade = Integer.parseInt (reader.readLine()); }catch( Exception e){ System.out.println("Input is invalid"); System.exit(0); } //solves for the average average = (firstGrade+secondGrade+thirdGrade)/3; //prints the average of the three exams System.out.print("Average: "+average); if(average>=60) System.out.print(" ;-)"); else System.out.print(" ;-("); } }
Introduction to Programming I
263
J.E.D.I
Using JOptionPane: import javax.swing.JOptionPane; /** * 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; thirdGrade = 0; average = 0;
firstGrade = Double.parseDouble (JOptionPane.showInputDialog ("First grade")); secondGrade = Double.parseDouble (JoptionPane.showInputDialog ("Second grade")); thirdGrade = Double.parseDouble (JoptionPane.showInputDialog ("Third grade"));
}catch( Exception e){ JoptionPane.showMessageDialog(null, "Input is invalid"); System.exit(0); } //solves for the average average = (firstGrade+secondGrade+thirdGrade)/3; if(average>=60){ JoptionPane.showMessageDialog (null,"Average : "+average+" ;-)"); } else{ JoptionPane.showMessageDialog (null,"Average : "+average+" ;-("); } } }
Introduction to Programming I
264
J.E.D.I
Introduction to Programming I
265
J.E.D.I
Using switch statement: import javax.swing.JOptionPane; /** * Transforms a number input from 1-10 to words * using switch. */ public class NumWords { public static void main(String[] args){ String msg = ""; int input = 0; //gets the input string input = Integer.parseInt (JOptionPane.showInputDialog ("Enter number")); //sets msg to the string equivalent of input switch(input){ case 1: msg = "one"; break; case 2: msg = "two"; break; case 3: msg = "three"; break; case 4: msg = "four"; break; case 5: msg = "five"; break; case 6: msg = "six"; break; case 7: msg = "seven"; break; case 8: msg = "eight"; break; case 9: msg = "nine"; break; case 10: msg = "ten"; break; default: msg = "Invalid number"; break; } //displays the number in words if with in range JOptionPane.showMessageDialog(null,msg);
Introduction to Programming I
266
J.E.D.I
Introduction to Programming I
267
J.E.D.I
Using do-while loop: import java.io.*; /** * 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.in)); String name = ""; int counter = 0; //gets the users' name try{ System.out.print("Enter name: "); name = reader.readLine(); }catch(Exception e){ System.out.println("Invalid input"); System.exit(0); } times //do-while loop that prints the name one hundred do{ System.out.println(name); counter++; }while(counter < 100);
Introduction to Programming I
268
J.E.D.I
Using for loop: import java.io.*; /** * 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.in)); String name = ""; //gets the users' name try{ System.out.print("Enter name: "); name = reader.readLine(); }catch(Exception e){ System.out.println("Invalid input"); System.exit(0); } //for loop that prints the name one hundred times for(int counter = 0; counter < 100; counter++){ System.out.println(name); }
Introduction to Programming I
269
J.E.D.I
6.4 Powers
Using while-loop: 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 base = Integer.parseInt (JOptionPane.showInputDialog("Base")); exp = Integer.parseInt (JOptionPane.showInputDialog("Exponent")); //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.showMessageDialog (null,"Positive numbers only please"); System.exit(0); } //while loop that solves for the power while(counter < exp){ power = power*base; counter++; } //displays the result JoptionPane.showMessageDialog (null,base+" to the "+exp+ " is "+power);
Introduction to Programming I
270
J.E.D.I
Using do-while loop: 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 base = Integer.parseInt(JOptionPane.showInputDialog ("Base")); exp = Integer.parseInt(JOptionPane.showInputDialog ("Exponent")); //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.showMessageDialog (null,"Positive numbers only please"); System.exit(0); } //do-while loop that solves the power given the base // and exponent do{ if(exp != 0) power = power*base; counter++; }while(counter < exp); //displays the result JoptionPane.showMessageDialog(null,base + " to the "+exp + " is "+power); }
Introduction to Programming I
271
J.E.D.I
Using for loop: 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 base = Integer.parseInt(JOptionPane.showInputDialog ("Base")); exp = Integer.parseInt(JOptionPane.showInputDialog ("Exponent")); //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 = 0; counter < exp; counter++){ power = power*base; } //displays the result JoptionPane.showMessageDialog(null,base + " to the "+exp + " is "+power); }
Introduction to Programming I
272
J.E.D.I
Chapter 7 Exercises
7.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. */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of the week String[] days = {"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"}; int counter = 0; //while loop that prints the days of the week while(counter < days.length){ System.out.println(days[counter]); counter++; } } }
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. */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of // the week String[] days ={"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"}; int counter = 0; //do-while loop that prints the days of the // week do{ System.out.println(days[counter]); counter++; }while(counter < days.length); } }
Introduction to Programming I
273
J.E.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. */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of // the week String[] days ={"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"}; //for loop that prints the days of the week for(int counter = 0; counter < days.length; System.out.println(days[counter]);
counter++) } }
//displays the number with the greatest number JoptionPane.showMessageDialog(null, "The number with the greatest value is "+max);
Introduction to Programming I
274
J.E.D.I
Chapter 8 Exercises
8.1 Print Arguments
/** * A program that prints the string from the command line if any. */ public class CommandLineSample { public static void main(String[] args){ //checks if a command line argument exists if(args.length == 0) System.exit(0); //for loop that prints the arguments from the //command line for(int counter=0;counter<args.length; counter++){ System.out.println(args[counter]); }
Introduction to Programming I
275
J.E.D.I
Chapter 9 Exercises
9.1 Defining terms
See definitions in book.
Class and Method declaration: 1. Class: String Method: public boolean endsWith( String suffix ) 2. Class: Character Method: public static char forDigit( int digit, int radix ) 3. Class: System Method: public static void exit( int status ) 4. Class: Math Method: public static double floor( double a ) 5. Class: Character Method: public static boolean isDigit( char ch )
Introduction to Programming I
276
J.E.D.I
Chapter 10 Exercises
10.1 Address Book Entry
/** * An address book class that record a persons * name, address, telephone number, and email address */ public class AddressBookEntry { private private private private String name; String add; int tel; String email;
/** * default constructor */ public AddressBookEntry(){ name = ""; add = ""; tel = 0; email = ""; } /** * Creates an AddressBookEntry object with the given * name, address, telephone number and email adress */ public AddressBookEntry(String name, String add, int tel, String email){ this.name = name; this.add = add; this.tel = tel; this.email = email; } /** * returns the variable name */ public String getName(){ return name; } /** * changes the variable name */ public void changeName(String name){ this.name = name; } /** * returns the variable add */ public String getAddress(){ return add; }
Introduction to Programming I
277
J.E.D.I
/** * changes the variable add */ public void changeAddress(String add){ this.add = add; } /** * returns the variable tel */ public int getTelNumber(){ return tel; } /** * changes the variable tel */ public void changeTelNumber(int tel){ this.tel = tel; } /** * returns the variable email */ public String getEmailAdd(){ return email; } /** * changes the variable email */ public void changeEmailAdd(String email){ this.email = email; }
Introduction to Programming I
278
J.E.D.I
10.2 AddressBook
import java.io.*; /** * Creates an addresbook that contains 100 AddressBookEntries */ public class AddressBook { //index of the last entry private int top = 0; //constant number that indicates the maximum //number of entries in the address book private static final int MAXENTRIES = 100; //array of Address Book Entries private AddressBookEntry[] list; /** * The main method */ public static void main(String[] args){ BufferedReader keyIn = new BufferedReader (new InputStreamReader (System.in)); AddressBook addBook = new AddressBook(); String act = ""; while(true){ //displays the optons System.out.println("\n[A] Add entry"); System.out.println("[D] Delete entry"); System.out.println("[V] View all entries"); System.out.println("[U] Update entry"); System.out.println("[Q] Quit"); System.out.print("Enter desired action: "); try{ //gets the choice act = keyIn.readLine();
Introduction to Programming I
279
J.E.D.I
} }
//checks for the appropriate action for // his choice if(act.equals("A")||act.equals("a")) addBook.addEntry(); else if(act.equals("D")||act.equals("d")) addBook.delEntry(); else if(act.equals("V")||act.equals("v")) addBook.viewEntries(); else if(act.equals("U")||act.equals("u")) addBook.updateEntry(); else if(act.equals("Q")||act.equals("q")) System.exit(0); else System.out.println ("Unknown command");
Introduction to Programming I
280
J.E.D.I
/** * creates the AddressBook */ public AddressBook(){ list = new AddressBookEntry[MAXENTRIES]; } /** * method for adding an AddressBookEntry to the Adressbook */ public void addEntry(){ BufferedReader keyIn = new BufferedReader (new InputStreamReader (System.in)); String name = ""; String add = ""; int tel = 0; String email = ""; if(top == MAXENTRIES){ System.out.println("Address Book is full"); return; } //asks the user for the data of the address book try{ System.out.print("Name: "); name = keyIn.readLine(); System.out.print("Address: "); add = keyIn.readLine(); System.out.print("Telephone number: "); tel = Integer.parseInt(keyIn.readLine()); System.out.print("Email Adress: "); email = keyIn.readLine(); }catch(Exception e){ System.out.println(e); System.exit(0); } AddressBookEntry entry = new AddressBookEntry (name, add, tel, email); list[top] = entry; top++;
Introduction to Programming I
281
J.E.D.I
/** * method that deletes an AddressBookEntry from the * Adressbook with the index */ public void delEntry(){ BufferedReader keyIn = new BufferedReader (new InputStreamReader(System.in)); int index = 0; //checks if the address book is empty if(top == 0){ System.out.println("Address Book is empty"); return; } //asks for the entry which is to be deleted try{ //shows the current entries on the record book viewEntries(); System.out.print("\nEnter entry number: "); index = Integer.parseInt(keyIn.readLine())-1; }catch(Exception e){} //checks if the index is with in bounds if(index < 0 || index >= top){ System.out.println("Index Out Of Bounds"); return; }else{ for( int i=index; i<top; i++ ){ list[i] = list[i+1]; } list[top] = null; top--; }
/** * method that prints all the entries in the AddressBook */ public void viewEntries(){ for(int index = 0; index < top; index++){ System.out.println((index+1)+" Name:"+ list[index].getName()); System.out.println("Address:"+ list[index].getAddress()); System.out.println("Telephone Number:"+ list[index].getTelNumber()); System.out.println("Email Address:"+ list[index].getEmailAdd()); }
Introduction to Programming I
282
J.E.D.I
/** * method that updates an entry */ public void updateEntry(){ BufferedReader keyIn = new BufferedReader(new InputStreamReader (System.in)); int index = 0; String name = ""; String add = ""; int tel = 0; String email = ""; //asks for the entries data try{ System.out.print("Entry number: "); index =Integer.parseInt(keyIn.readLine())-1; System.out.print("Name: "); name = keyIn.readLine(); System.out.print("Address: "); add = keyIn.readLine(); System.out.print("Telephone number: "); tel = Integer.parseInt(keyIn.readLine()); System.out.print("Email Adress: "); email = keyIn.readLine(); }catch(Exception e){ System.out.println(e); System.exit(0); } //updates the entry AddressBookEntry entry = new AddressBookEntry (name, add, tel, email); list[index] = entry;
Introduction to Programming I
283
J.E.D.I
Chapter 11 Exercises
11.1 Extending StudentRecord
/** * An object that holds the data for a student */ public class StudentRecord { protected String name; protected String address; protected int age; protected double mathGrade; protected double englishGrade; protected double scienceGrade; protected double average; protected static int studentCount; /** * Returns the name of the student */ public String getName(){ return name; } /** * Changes the name of the student */ public void setName(String temp){ name = temp; } /** * Returns the address of the student */ public String getAddress(){ return address; } /** * Changes the address of the student */ public void setAddress(String temp){ address = temp; } /** * Returns the age of the student */ public int getAge(){ return age; } /** * Changes the age of the student */ public void setAge(int temp){ age = temp; }
Introduction to Programming I 284
J.E.D.I
/** * Returns the englishGrade of the student */ public double getEnglishGrade(){ return englishGrade; } /** * Changes the englishGrade of the student */ public void setEnglishGrade(double temp){ englishGrade = temp; } /** * Returns the mathGrade of the student */ public double getMathGrade(){ return mathGrade; } /** * Changes the mathGrade of the student */ public void setMathGrade(double temp){ mathGrade = temp; } /** * Returns the scienceGrade of the student */ public double getScienceGrade(){ return scienceGrade; } /** * Changes the scienceGrade of the student */ public void setScienceGrade(double temp){ scienceGrade = temp; } /** * Computes the average of the english, math and * science grades */ public double getAverage(){ return (mathGrade+englishGrade+scienceGrade)/3; } /** * Returns the number of instances of the * StudentRecords */ public static int getStudentCount(){ return studentCount; }
Introduction to Programming I
285
J.E.D.I
/** * A student record for a Computer Science student */ public class ComputerScienceStudentRecord extends StudentRecord { private String private double studentNumber; comSciGrade;
/** * Returns the studentNumber of the student */ public String getStudentNumber(){ return studentNumber; } /** * Changes the studentNumber of the student */ public void setStudentNumber(String temp){ studentNumber = temp; } /** * Returns the comSciGrade of the student */ public double getComSciGrade(){ return comSciGrade; } /** * Changes the comSciGrade of the student */ public void setComSciGrade(double temp){ comSciGrade = temp; }
Introduction to Programming I
286
J.E.D.I
/** * Class definition for object circle */ public class Circle extends Shape { private static final double pi = 3.1416; private double radius = 0; /** * Constructor */ public Circle(double r){ setRadius( r ); } /** * returns area */ public double getArea(){ return pi*radius*radius; } /** * returns shape name */ public String getName(){ return "circle"; } /** * set radius */ public void setRadius(double r){ radius = r; } /** * returns radius */ public double getRadius(){ return radius; }
Introduction to Programming I
287
J.E.D.I
/** * Class definition for object square */ public class Square extends Shape { private double side = 0; /** * Constructor */ public Square(double s){ setSide( s ); } /** * returns area */ public double getArea(){ return side*side; } /** * returns shape name */ public String getName(){ return "square"; } /** * set length of side */ public void setSide(double s){ side = s; } /** * returns length of one side */ public double getSide(){ return side; }
Introduction to Programming I
288
J.E.D.I
Chapter 12 Exercises
12.1 Catching Exceptions 1
public class TestExceptions{ public static void main( String[] args ){ try{ for( int i=0; true; i++ ){ System.out.println("args["+i+"]="+args[i]); } }catch( ArrayIndexOutOfBoundsException e ){ System.out.println("Exception caught:"); System.out.println(" "+e); System.out.println("Quiting..."); } } }
//displays the number with the greatest number JoptionPane.showMessageDialog (null,"The number with the greatest value is "+max);
Introduction to Programming I
289
J.E.D.I
import javax.swing.JOptionPane; /** * Transforms a number input from 1-10 to words using switch. */ public class NumWords { public static void main(String[] args){ String msg = ""; int input = 0; //gets the input string input = Integer.parseInt (JoptionPane.showInputDialog ("Enter number")); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid input"); System.exit(0); } //sets msg to the string equivalent of input switch(input){ case 1: msg = "one"; break; case 2: msg = "two"; break; case 3: msg = "three"; break; case 4: msg = "four"; break; case 5: msg = "five"; break; case 6: msg = "six"; break; case 7: msg = "seven"; break; case 8: msg = "eight"; break; case 9: msg = "nine"; break; case 10: msg = "ten"; break; default: msg = "Invalid number"; break; } //displays the number in words if with in range JOptionPane.showMessageDialog(null,msg);
Introduction to Programming I 290
try{
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
Introduction to Programming I
292
J.E.D.I
Introduction to Programming I
293
J.E.D.I
Introduction to Programming I
294
J.E.D.I
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
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
J.E.D.I
3.3 Write, Compile, and Run Hello Java Program using NetBeans
1. Start the NetBeans IDE 4.1 Windows: Start > All Programs > NetBeans 4.1 > NetBeans IDE or click NetBeans IDE 4.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans
2. Create a new NetBeans project and Hello main class Select File from the menu bar and select New Project. Under Choose Project, select General and Java Application Click Next. Under Name and Location pane, (Figure-10 below) For Project Name field, fill it with Hello For Create Main Class field, change it to hello.Hello hello.Main) Click Finish
(from
Note that the IDE generated Hello.java code gets displayed in the source editor.
3. Modify the Hello class Replace the code of Hello class of IDE generated Hello.java code in the source editor with the one in Chapter 2 while leaving the package statement on the top.
4. Run Hello class Right click Hello.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
J.E.D.I
Chapter 4 Hands-on
4.1 Declaring, Initializing, Printing Variables
1. Create OutputVariable.java using your editor of choice public class OutputVariable { public static void main( String[] args ){ int value = 10; char x; x = 'A'; System.out.println( value ); System.out.println( "The value of x=" + x ); } }
2. Compile and run the code javac OutputVariable.java java OutputVariable 3. Verify that the result is as following C:\lab>java OutputVariable 10 The value of x=A 4. Modify OutputVariable.java as following and compile and run the code Define another primitive type as following double grade = 11; Print out the value of grade variable as following System.out.println( "The value of grade =" + grade );
Introduction to Programming I
299
J.E.D.I
} }
2. Compile and run the code javac ConditionalOperator.java java ConditionalOperator 3. Verify that the result is as following C:\lab>java ConditionalOperator Passed 4. Modify ConditionalOperator.java as following, compile and run the code int salary = 100000; Print "rich" if the salary is over 50000. Print "poor" otherwise.
Introduction to Programming I
300
J.E.D.I
Chapter 5 Hands-on
5.1 Getting Input From Keyboard via BufferedReader
1. Create GetInputFromKeyboard.java using your editor of choice import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class GetInputFromKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ); String name = ""; System.out.print("Please Enter Your Name:"); try{ name = dataIn.readLine(); }catch( IOException e ){ System.out.println("Error!"); } System.out.println("Hello " + name +"!");
} }
2. Compile and run the code javac GetInputFromKeyboard.java java GetInputFromKeyboard 3. Modify GetInputFromKeyboard.java as following, 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, display Hello <name> You are old! Otherwise Hello <name> You are young!
Introduction to Programming I
301
J.E.D.I
Introduction to Programming I
302
J.E.D.I
Chapter 6 Hands-on
6.1 For Loop
1. Create ForLoop.java using your editor of choice public class ForLoop { public static void main( String[] args ){ String names []= {"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"}; String searchName ="Yza"; boolean foundName =false; for (int i=0;i<names.length;i++){ if (names [i ].equals(searchName )){ foundName =true; break; } } if (foundName ) System.out.println(searchName +" is found!"); else System.out.println(searchName +" is not found."); } }
2. Compile and run the code javac ForLoop.java java ForLoop 3. Verify that the result is as following C:\lab>java ForLoop Yza is found! 4. Modify ForLoop.java as following, compile and run the code Change the code to use while loop
Introduction to Programming I
303
J.E.D.I
Chapter 7 Hands-on
7.1 Arrays
1. Create ArraySample.java using your editor of choice public class ArraySample { public static void main( String[] args ){ int[] ages = new int[100]; for( int i=0; i<ages.length; i++ ){ System.out.print( ages[i] ); } } }
2. Compile and run the code javac Arraysample.java java ArraySample 3. Verify the result is as following C:\lab>java ArraySample 000000000000000000000000000000000000000000000000000000000000000 00000000000000000 00000000000000000000 4. Modify ArraySample.java as following, compile and run the code Just before the for loop that prints out the value of each entry of the ages[] array, create another for loop in which a value of 100 is assigned to the first entry of the array, ages[0], 101 to the next entry of the array, ages[1], and so on
Introduction to Programming I
304
J.E.D.I
Chapter 8 Hands-on
None
Chapter 9 Hands-on
9.1 Pass-by-Value
1. Create .java using your editor of choice public class TestPassByValue { public static void main(String[] args){ int i = 10; //print the value of i System.out.println(i); //Call method test //and pass i to method test test( i ); // print the value of i. i not changed System.out.println(i); } public static void test(int j){ // change value of parameter i j = 33; }
2. Compile and run the code javac TestPassByValue.java java TestPassByValue 3. Verify the result is as following C:\lab>java TestPassByValue 10 10
Introduction to Programming I
305
J.E.D.I
9.2 Pass-by-Reference
1. Create .java using your editor of choice public class TestPassByReference { public static void main(String[] args){ //create an array of integers int [] ages = {10, 11, 12}; //print array values for (int i=0; i<ages.length; i++ ){ System.out.println(ages[i]); } //call test and pass references to array test(ages); //print array values again for (int i=0; i<ages.length; i++ ){ System.out.println(ages[i]); } } public static void test(int[] arr){ // change values of array for (int i=0; i<arr.length; i++ ){ arr[i] = i + 50; } }
2. Compile and run the code javac TestPassByReference.java java TestPassByReference 3. Verify the result is as following C:\lab>java TestPassByReference 10 11 12 50 51 52
Introduction to Programming I
306
J.E.D.I
2. Compile and run the code javac EqualsTest.java java EqualsTest 3. Verify the result is as following. 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. Create EqualsTestInteger.java class EqualsTestInteger { public static void main(String[] arguments) { Integer integer1, integer2; integer1 = new Integer(5); integer2 = new Integer(5); System.out.println("Integer1: " + integer1); System.out.println("Integer2: " + integer2); System.out.println("Same object? " + (integer1 == integer2)); integer1 = integer2; System.out.println("Integer1: " + integer1); System.out.println("Integer2: " + integer2); System.out.println("Same object? " + (integer1 == integer2)); System.out.println("Same value? " + integer1.equals (integer2)); } } 5. Compile and run the code javac EqualsTestInteger.java java EqualsTestInteger
Introduction to Programming I 307
J.E.D.I
Chapter 10 Hands-on
10.1 Create your own class
Using Text Editor: 1. Create StudentRecord.java using your editor of choice public class StudentRecord { // instance variables private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // static variables private static int studentCount = 0; /** *Returns the name of the student */ public String getName(){ return name; } /** *Changes the name of the student */ public void setName(String temp ){ name =temp; } /** *Computes the average of the english,math and science *grades */ public double getAverage(){ double result =0; result =(mathGrade+englishGrade+scienceGrade )/3; return result; } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; } } 2. Create StudentRecordExample.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();
Introduction to Programming I 308
J.E.D.I
StudentRecord beahRecord =new StudentRecord(); StudentRecord crisRecord =new StudentRecord(); //set the name of the students annaRecord.setName("Anna"); beahRecord.setName("Beah"); crisRecord.setName("Cris"); //print anna's name System.out.println(annaRecord.getName()); //print number of students System.out.println ("Count="+StudentRecord.getStudentCount()); } } 3. Compile and run the code javac *.java (or javac StudentRecord.java StudentRecordExample.java) java StudentRecordExample 4. Verify the result C:\lab1>java StudentRecordExample Anna Count=0
Introduction to Programming I
309
J.E.D.I
Using Netbeans: 1. Start the NetBeans IDE 4.1 (if you have not done so yet) Windows: Start > All Programs > NetBeans 4.1 > NetBeans IDE or click NetBeans IDE 4.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans
2. Create a new NetBeans project and StudentRecordExample main class Select File from the menu bar and select New Project. Under Choose Project, select General and Java Application Click Next. Under Name and Location pane, (Figure-10 below) For Project Name field, fill it with StudentRecordExample For Create Main Class field, change it to studentrecordexample.StudentRecordExample (from studentrecordexample.Main) Click Finish
3. Modify the NetBeans generated code Replace the NetBeans generated StudentRecordExample.java code in the source editor with the one you have written before.
4. Write StudentRecord.java
Introduction to Programming I
310
J.E.D.I
Right click StudentRecordExample project node and select New->Java Class. The New Java Class window appears. Under Name and Location pane, for Class Name field, type StudentRecord for Package field, choose studentrecordexample from the drop-down menu (or you can type studentrecordexample) Click Finish
5. Modify the NetBeans generated code Replace the NetBeans generated StudentRecord.java code in the source editor with the one you have written before.
6. Run StudentRecordExample application Right click StudentRecordExample.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
J.E.D.I
Creating your own: 1. Modify StudentRecord.java as following Add setMathGrade(double grade) method Add setEnglishGrade(double grade) method Add setScienceGrade(double grade) method Add static method called increaseStudentCount(), this method increase the static variable studentCount by 1
2.. Modify StudentRecordExample.java as following Create another StudentRecord object, 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
Introduction to Programming I
312
J.E.D.I
10.2 Overloading
Using Text Editor: 1. Modify StudentRecord.java as following. The code fragement that needs to be added is highlighted with bold. Add two overloaded print(..) methods. public class StudentRecord { ... public void print(String name ){ System.out.println("Name:"+name); } public void print(String name, double averageGrade){ System.out.print("Name:"+name+" "); System.out.println("Average Grade:"+averageGrade); } } 2.Create StudentRecordExample2.java as follows public class StudentRecordExample2{ public static void main(String [] args) { StudentRecord annaRecord =new StudentRecord(); annaRecord.setName("Anna"); annaRecord.setEnglishGrade(95.5); annaRecord.setScienceGrade(100); //overloaded methods annaRecord.print(annaRecord.getName()); annaRecord.print(annaRecord.getName(), annaRecord.getAverage()); } } 3. Compile and run the code. If you experience compile errors, fix the compile errors. javac *.java (or javac StudentRecord.java StudentRecordExample2.java) java StudentRecordExample2 4. Verify the result Name:Anna Name:Anna Average Grade:65.16666666666667
Introduction to Programming I
313
J.E.D.I
Using Netbeans: It is assumed you are using the same NetBeans project you created in 10.1. 1. Modify the StudentRecord.java 2. Create StudentRecordExample2.java Right studentrecordexample package node (Not StudentRecordExample project node) and select New->Java Class Under Name and Location pane, for Class Name field, type StudentRecordExamle2 Click Finish
3. Modify the NetBeans generated StudentRecordExample2.java Replace the code of the NetBeans generated StudentRecordExample2.java with the one of above while leaving the package statement at the top
4. Right click studentrecordexample package node (Not StudentRecordExample project node) and select Compile Package (F9) 5. Right click StudentRecordExamle2 and select Run File
Introduction to Programming I
314
J.E.D.I
Creating your own: 1. Modify StudentRecord.java as following Add another print() method which takes the following three parameters name grade average student count
Introduction to Programming I
315
J.E.D.I
10.3 Packaging
Please do this exercise at the command line instead of using NetBeans. This is to learn the packaging structure without the help of NetBeans. 0. If have used NetBeans to do the exercise 13 above, please create StudentRecord.java and StudenRecordExample.java as following public class StudentRecord { // instance variables private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // static variables private static int studentCount = 0; /** *Returns the name of the student */ public String getName(){ return name; } /** *Changes the name of the student */ public void setName(String temp ){ name =temp; } /** *Computes the average of the english,math and science *grades */ public double getAverage(){ double result =0; result =(mathGrade+englishGrade+scienceGrade )/3; return result; } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; } }
Introduction to Programming I
316
J.E.D.I
public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord(); StudentRecord beahRecord =new StudentRecord(); StudentRecord crisRecord =new StudentRecord(); //set the name of the students annaRecord.setName("Anna"); beahRecord.setName("Beah"); crisRecord.setName("Cris"); //print anna's name System.out.println(annaRecord.getName()); //print number of students System.out.println ("Count="+StudentRecord.getStudentCount()); } } 1. Modify StudentRecord.java as following to add a package statement. The code fragment that needs to be added is in bold characters. package studentpackage; public class StudentRecord { ... } 2. Modify StudentRecordExample.java as following to add a package statement. The code fragement that needs to be added is is in bold characters. package studentpackage; public class StudentRecordExample{ ... } 3. Compile code. javac StudentRecord.java StudentRecordExample.java 4. Run the code. You will experience an NoClassDefFoundError exception. Think about why you are getting this exception for a moment. It is because the java runtime is trying to find StudentRecordExample.class under studentpackage directory. It is because the StudentRecordExample.java now has a package statement which says the Java class file resides under studentpackage directory. C:\lab>java StudentRecordExample Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample (wrong name: studentpackage/StudentRecordExample) at java.lang.ClassLoader.defineClass0(Native
317
Introduction to Programming I
J.E.D.I
Method)
at java.lang.ClassLoader.defineClass (ClassLoader.java:539) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass (URLClassLoader.java:251) at java.net.URLClassLoader.access$100 (URLClassLoader.java:55) at java.net.URLClassLoader$1.run (URLClassLoader.java:194) at java.security.AccessController.doPrivileged (Native Method) at java.net.URLClassLoader.findClass (URLClassLoader.java:187) at java.lang.ClassLoader.loadClass (ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass (Launcher.java:274) at java.lang.ClassLoader.loadClass (ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal (ClassLoader.java:302) 5. Create a new directory called studentpackage and then move StudentRecord.java and StudentRecordExample.java under it. mkdir \lab\studentpackage move \lab\StudentRecordExample.java \lab\studentpackage\StudentRecordExample.java move \lab\StudentRecord.java \lab\studentpackage\StudentRecord.java 6. Compile code. You will experience compile errors as following. You get this compile error because you are trying to compile the two Java files that are not present in the current directory anymore. del StudentRecord.class del StudentRecordExample.class C:\lab>javac StudentRecord.java StudentRecordExample.java error: cannot read: StudentRecord.java 1 error 7. Compile the code using a directory structure. The compilation should succeed. Note that the class files are now created under studentpackage directory not in the current directory javac studentpackage\StudentRecord.java studentpackage\StudentRecordExample.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
PM PM PM PM PM
<DIR> <DIR>
J.E.D.I
StudentRecordExample.class 07/06/2005 12:17 PM 690 StudentRecordExample.java 4 File(s) 4,494 bytes 2 Dir(s) 1,415,856,128 bytes free 8. Run the code as follows. You will experience NoClassDefFoundError because it is trying to find the class in the current directory instead of in the studentpackage directory. C:\lab>java StudentRecordExample Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample 9. Run the code with propert package structure. It should work this time. C:\lab>java studentpackage.StudentRecordExample Anna Count=0 10. 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. And the following is what you will experience. It is because it is still looking for studentpackage/StudentRecordExample.class in the currently directory and it could not find it. C:\lab>cd studentpackage C:\lab\studentpackage>java StudentRecordExample Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample (wrong name: studentpackage/StudentRecordExample) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass (ClassLoader.java:539) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass (URLClassLoader.java:251) at java.net.URLClassLoader.access$100 (URLClassLoader.java:55) at java.net.URLClassLoader$1.run (URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass (URLClassLoader.java:187) at java.lang.ClassLoader.loadClass (ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass (Launcher.java:274) at java.lang.ClassLoader.loadClass (ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal (ClassLoader.java:302)
Introduction to Programming I
319
J.E.D.I
11. 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.lang.NoClassDefFoundError: StudentRecordExample C:\lab\studentpackage>java -classpath \lab studentpackage.StudentRecordExample Anna Count=0 Creating your own: 1. Create a class called Food under foodpackage.fruitpackage pacakge Food.java should have the following package statement at the top package foodpackage.fruitpackage Add a couple of methods of your own
2. Create a class called FoodMain under foodpackage.fruitpackage package FoodMain class creates an Food object FoodMain class then calls a method of Food object
Introduction to Programming I
320
J.E.D.I
Chapter 11 Hands-on
11.1 Inheritance Constructor
1. Write Person.java package personpackage; public class Person { private String name; private String address; public Person(){ System.out.println("Inside Person:Constructor"); } public Person (String name, String address){ System.out.println("Inside Person:Constructor 2 receiving two parameters: " + name + ", " + address); this.name = name; this.address = address; } public String getName(){ System.out.println("Person: getName()"); return name; } public void setName(String s){ name = s; } public String getAddress(){ return address; } public void setAddress(String s){ address = s; }
Introduction to Programming I
321
J.E.D.I
2. Write Student.java package personpackage; public class Student extends Person { private String hobby; public Student(){ System.out.println("Inside Student:Constructor"); public String getHobby(){ return hobby; } public void setHobby(String s){ hobby = s; }
} 3. Write Main.java
package personpackage; public class Main { public static void main(String [] args ){ Student student1 =new Student(); } } 4. Compile and run the code using a directory structure. cd \lab javac personpackage\*.java java personpackage.Main 5. Verify the result is as following C:\lab>java personpackage.Main Inside Person:Constructor Inside Student:Constructor
Introduction to Programming I
322
J.E.D.I
6. Modify the Student.java as following. The code fragment that needs to be added is in bold characters. package personpackage; public class Student extends Person { private String hobby; public Student(){ super("Sang", "1 Dreamland"); System.out.println("Inside Student:Constructor"); public String getHobby(){ return hobby; } public void setHobby(String s){ hobby = s; }
7. Compile and run the code using a directory structure. cd \lab javac personpackage\*.java java personpackage.Main 8. Verify the result is as following C:\lab>java personpackage.Main Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland Inside Student:Constructor
Introduction to Programming I
323
J.E.D.I
Using Netbeans: 1. Start the NetBeans IDE 4.1 (if you have not done so yet) Windows: Start > All Programs > NetBeans 4.1 > NetBeans IDE or click NetBeans IDE 4.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans
2. Create a new NetBeans project and Main.java main class Select File from the menu bar and select New Project. Under Choose Project, select General and Java Application Click Next. Under Name and Location pane, (Figure-10 below) For Project Name field, fill it with PersonPackage Click Finish
3. Replace the code in the NetBeans generated Main.java 4. Create Person.java Right personpackage package node (not PersonPackage project node) and select New->Java Class Under Name and Location pane, for Class Name field, type Person Click Finish
5. Replaced the code in the NetBeans generated Person.java 6. Create Student.java Right personpackage node (not PersonPackage project node) and select New>Java Class Under Name and Location pane, for Class Name field, type Student Click Finish 7. Replaced the code in the NetBeans generated Student.java 8. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9) 9. Right click Main select Run File 10.Modify the Student.java. 11. Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9) 12. Right click Main select Run File
Introduction to Programming I
324
J.E.D.I
Creating your own: 1. Write TuftsStudent.java as following TuftsStudent class extends Student class Write a constructor of the TuftsStudent class as following public TuftsStudent(){ System.out.println("Inside TuftsStudent:Constructor"); }
2. Modify the Main.java to create an instance of TuftsStudent class as following TuftsStudent student2 =new TuftsStudent(); Student student3 =new TuftsStudent(); 3. Compile and run the code. 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
J.E.D.I
Introduction to Programming I
326
J.E.D.I
5. Modify the Student.java as following. The code fragment that needs to be added is in bold characters. package personpackage; public class Student extends Person { private String hobby; public Student(){ System.out.println("Inside Student:Constructor"); public String getHobby(){ return hobby; } public void setHobby(String s){ hobby = s; } // Override getName() method of the parent class public String getName(){ System.out.println("Student: getName()"); return "Passionate" + super.getName(); }
6. Compile and run the code using a directory structure. cd \lab javac personpackage\*.java java personpackage.Main 7. Verify the result is as following C:\lab>java personpackage.Main Inside Person:Constructor Inside Student:Constructor Student: getName() Person: getName() Calling getName() method: name is PassionateSang
Introduction to Programming I
327
J.E.D.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. 1. Modify the Main.java. 2. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9) 3. Right click Main select Run File 4. Modify the Student.java 5. Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9) 6. Right click Main select Run File Creating your own: 1. In your TuftsStudent class, override getHobby() and setHobby() methods of the Student class as follows public String getHobby(){ System.out.println("Inside TuftsStudent:getHobby() method"); return "My hobby is " + super.getHobby(); } public void setHobby(String s){ System.out.println("Inside TuftsStudent:setHobby() method"); super.setHobby(s); } 2. Change Main.java to invoke setHobby() and getHobby() methods of the newly created TuftsStudent object instances as follows. // set hobbies of student2 and student3 student2.setHobby("swimming"); student3.setHobby("dancing"); // get hobbies of student2 and student3 String hobby2 = student2.getHobby(); System.out.println("Hobby of student2 " + hobby2); String hobby3 = student3.getHobby(); System.out.println("Hobby of student3 " + hobby3); 3. Compile and run the code. You should see the following result. Inside Inside Inside Inside Inside Inside Person:Constructor Student:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Person:Constructor
328
Introduction to Programming I
J.E.D.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
J.E.D.I
11.3 Polymorphism
1. Write Person.java. This is the same Person.java as in the previous exercise except the package name. Person class is a parent class of both Student and Employee classes, which you will write in the subsequent steps. package polypackage; public class Person { private String name; private String address; public Person(){ System.out.println("Inside Person:Constructor"); } public Person (String name, String address){ System.out.println("Inside Person:Constructor 2 receiving two parameters: " + name + ", " + address); this.name = name; this.address = address; } public String getName(){ System.out.println("Person: getName()"); return name; } public void setName(String s){ name = s; } public String getAddress(){ return address; } public void setAddress(String s){ address = s; }
Introduction to Programming I
330
J.E.D.I
2. Write Student.java. Student class is a subclass of a Person class. package polypackage; public class Student extends Person { private String hobby; public Student(){ System.out.println("Inside Student:Constructor");
public Student (String name, String address){ super(name, address); System.out.println("Inside Student:Constructor 2 receiving two parameters: " + name + ", " + address); } public String getHobby(){ return hobby; } public void setHobby(String s){ hobby = s; } // Override getName() method of the parent class public String getName(){ System.out.println("Student: getName()"); return "Passionate Student " + super.getName(); }
Introduction to Programming I
331
J.E.D.I
3. Write Employee.java. Employee class is subclass of Person class. package polypackage; public class Employee extends Person { private String hobby; public Employee(){ System.out.println("Inside Employee:Constructor");
public Employee(String name, String address){ super(name, address); System.out.println("Inside Employee:Constructor 2 receiving two parameters: " + name + ", " + address); } public String getHobby(){ return hobby; } public void setHobby(String s){ hobby = s; } // Override getName() method of the parent class public String getName(){ System.out.println("Employee: getName()"); return "Not so Passionate Employee " + super.getName }
(); }
Introduction to Programming I
332
J.E.D.I
4. Write Main.java package polypackage; public class Main { public static void main( String[] args ) { Person ref; Student studentObject = new Student("Sang", "1 Dreamland"); Employee employeeObject = new Employee("Young", "2 Dreamland"); System.out.println("\n"); object ref = studentObject; //Person ref. points to a Student //getName of Student class is called String temp1=ref.getName(); System.out.println( "temp1 -" + temp1 + "\n" ); ref = employeeObject; //Person ref. points to an Employee object //getName of Employee class is called String temp2 = ref.getName(); System.out.println( "temp2 -" + temp2 + "\n" );
5. Compile and run the code using a directory structure. cd \lab javac polypackage\*.java java polypackage.Main 6. Verify the result is as following. Note that depending on what object type the ref variable refers to, Employee type or Student type, proper method gets invoked. C:\lab>javac polypackage\*.java C:\lab>java polypackage.Main Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland Inside Student:Constructor 2 receiving two parameters: Sang, 1 Dreamland Inside Person:Constructor 2 receiving two parameters: Young, 2 Dreamland Inside Employee:Constructor 2 receiving two parameters: Young, 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
J.E.D.I
Introduction to Programming I
334
J.E.D.I
Using NetBeans: 1. Start the NetBeans IDE 4.1 (if you have not done so yet) Windows: Start > All Programs > NetBeans 4.1 > NetBeans IDE or click NetBeans IDE 4.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans
2. Create a new NetBeans project and Main.java main class Select File from the menu bar and select New Project. Under Choose Project, select General and Java Application Click Next. Under Name and Location pane, (Figure-10 below) For Project Name field, fill it with PolyPackage Click Finish
3. Replace the code in the NetBeans generated Main.java 4. Create Person.java Right polypackage package node (not PolyPackage project node) and select New->Java Class Under Name and Location pane, for Class Name field, type Person Click Finish
5. Replaced the code in the NetBeans generated Person.java 6. Create Student.java Right polypackage node (not PolyPackage project node) and select New->Java Class Under Name and Location pane, for Class Name field, type Student Click Finish
7. Replaced the code in the NetBeans generated Student.java 8. Create Employee.java Right polypackage node (not PolyPackage project node) and select New->Java Class Under Name and Location pane, for Class Name field, type Employee Click Finish
Introduction to Programming I
335
J.E.D.I
9. Replaced the code in the NetBeans generated Employee.java 10. Right click polypackage package node (not PolyPackage project node) and select Compile Package (F9) 11. Right click Main select Run File 12.Modify the Student.java 13. Right click polypackage pacakge node (not PolyPackage project node) and select Compile Package (F9) 14. Right click Main select Run File Creating your own: 1. Create another class called Teacher.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.out.println("Teacher: getName()"); return "Maybe Passionate Teacher" + super.getName(); }
2. Modify the Main.java in which, getName() method of the Teacher object gets called 3. Compile and run the code. You should see the following result. C:\lab>java polypackage.Main Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland Inside Student:Constructor 2 receiving two parameters: Sang, 1 Dreamland Inside Person:Constructor 2 receiving two parameters: Young, 2 Dreamland Inside Employee:Constructor 2 receiving two parameters: Young, 2 Dreamland Inside Person:Constructor 2 receiving two parameters: Wende, 21 New York Inside Teacher:Constructor 2 receiving two parameters: Wende, 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
J.E.D.I
} 2. Write Main.java.
package abstractexercise; public class Main { public static void main( String[] args ) { LivingThing x = new LivingThing(); } } 3. Compile Livingthing.java and Main.java. cd \lab
javac abstractexercise\LivingThing.java abstractexercise\Main.java
4. Note that you will experience a compile error since you cannot create an object instance from an abstract class. C:\lab>javac abstractexercise\LivingThing.java abstractexercise\Main.java abstractexercise\Main.java:5: abstractexercise.LivingThing is abstract; cannot be instantiated LivingThing x = new LivingThing(); ^ 1 error
Introduction to Programming I
337
J.E.D.I
5. Write a concrete class called Human.java that extends the abstract LivingThing class package abstractexercise; public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } } 6. Rewrite Main.java. package abstractexercise; public class Main { public static void main( String[] args ) { Human x = new Human(); x.walk(); LivingThing y = new Human(); y.walk();
7. Compile and run the code using a directory structure. cd \lab javac abstractexercise\*.java java abstractexercise.Main 8. Verify the result is as following. C:\lab>java abstractexercise.Main Human walks... Human walks... Creating your own: 1. Define another abstract method in the LivingThing.java as following public abstract void dance(String dancingStyle); 2. Implement a concrete method in the Human.java that implements the dance() abstract method. public void dance(String ds){ System.out.println("Human dances..." + ds); } 3. Modify the Main.java so that it calls dance(ds) method
Introduction to Programming I
338
J.E.D.I
4. Compile and run the code. You should see the following result. C:\lab>java abstractexercise.Main Human walks... Human dances in Swing Human walks... Human dances in Saturday Night Live
Introduction to Programming I
339
J.E.D.I
11.5 Interfaces 1
1. Write Relation.java which is an Interface. package interfaceexercise; public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); } 2. Write Main.java. package interfaceexercise; public class Main { public static void main( String[] args ) { Relation x = new Relation(); } } 3. Compile Relation.java and Main.java. cd \lab javac interfaceexercise\Relation.java interfaceexercise\Main.java 4. Note that you will experience a compile error since you cannot create an object instance from an Interface. C:\lab>javac interfaceexercise\Relation.java interfaceexercise\Main.java interfaceexercise\Main.java:5: interfaceexercise.Relation is abstract; cannot be instantiated Relation x = new Relation(); ^ 1 error
Introduction to Programming I
340
J.E.D.I
5. Write a concrete class that implements Relation. package interfaceexercise; public class Line implements Relation { private double x1; private double x2; private double y1; private double y2; public Line(double x1,double x2,double y1,double y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } public double getLength(){ double length = Math.sqrt( (x2-x1)*(x2-x1) + (y2-y1)* (y2-y1) ); return length; } public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen > bLen); } public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen < bLen); } public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen); }
Introduction to Programming I
341
J.E.D.I
6. Rewrite Main.java. package interfaceexercise; public class Main { public static void main( String[] args ) { Line line1 Line line2 = new Line(1.0, 2.0, 1.0, 2.0); = new Line(2.0, 3.0, 2.0, 3.0);
b1); b2);
boolean b1 = line1.isGreater(line1, line2); System.out.println("line1 is greater than line2: " + boolean b2 = line1.isEqual(line1, line2); System.out.println("line1 is equal with line2: " + Line line3 = new Line(1.0, 5.0, 1.0, 5.0); boolean b3 = line3.isEqual(line1, line3); System.out.println("line1 is equal with line3: " +
b3);
System.out.println("Length of line1 is " + line1.getLength()); System.out.println("Length of line2 is " + line2.getLength()); System.out.println("Length of line3 is " + line3.getLength()); } }
7. Compile and run the code using a directory structure. cd \lab javac interfaceexercise\*.java java interfaceexercise.Main 8. Verify the result as following: C:\lab>java interfaceexercise.Main line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1.4142135623730951 Length of line2 is 1.4142135623730951 Length of line3 is 5.656854249492381
Introduction to Programming I
342
J.E.D.I
Creating your own: 1. Create another implementation class called NumberComparison that implements Relation interface. 2. Modify Main class that compares two int type numbers. 3. You should see the following result C:\lab>java interfaceexercise.Main line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1.4142135623730951 Length of line2 is 1.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
J.E.D.I
11.6 Interfaces 2
1. Write PersonInterface.java which is an Interface. package interfaceexercise2; public interface PersonInterface { public public public public String getName(); void setName(String s); String getAddress(); void setAddress(String s);
2. Write PersonImpl.java. PersonImpl class implements PersonInterface Interface. package interfaceexercise2; public class PersonImpl implements PersonInterface { private String name; private String address; public PersonImpl(){ System.out.println("Inside PersonImpl:Constructor"); } public PersonImpl (String name, String address){ System.out.println("Inside PersonImpl:Constructor 2 receiving two parameters: " + name + ", " + address); this.name = name; this.address = address; } public String getName(){ System.out.println("PersonImpl: getName()"); return name; } public void setName(String s){ name = s; } public String getAddress(){ return address; } public void setAddress(String s){ address = s; }
Introduction to Programming I
344
J.E.D.I
3. Compile PersonInterface.java and PersonImpl.java. cd \lab javac interfaceexercise2\PersonInterface.java interfaceexercise2\PersonImpl.java 4. Write StudentInteface.java. The StudentInteface interface extends PersonInterface interface. package interfaceexercise2; public interface StudentInterface extends PersonInterface { public String getHobby(); public void setHobby(String s); } 5. Write StudentImpl.java. package interfaceexercise2; public class StudentImpl implements StudentInterface { private String hobby; public StudentImpl(){ System.out.println("Inside StudentImpl:Constructor"); } public String getHobby(){ System.out.println("StudentImpl: getHobby()"); return hobby; } public void setHobby(String s){ hobby = s; }
Introduction to Programming I
345
J.E.D.I
6. Compile Studentnterface.java and StudentImpl.java. You will experience the compile error. This is because StudentImpl.java did not implement all the abstract methods defined in both StudentInterface and PersonInteface interfaces. C:\lab>javac interfaceexercise2\StudentInterface.java interfaceexercise2\StudentImpl.java interfaceexercise2\StudentImpl.java:3: interfaceexercise2.StudentImpl is not abstract and does not override abstract method setAddress(java.lang.String) in interfaceexercise2.PersonInterface public class StudentImpl implements StudentInterface{ ^ 1 error 7. Modify StudentImpl.java. The code fragment that needs to be added is highlighted in bold font. package interfaceexercise2; public class StudentImpl extends PersonImpl implements StudentInterface { private String hobby; public StudentImpl(){ System.out.println("Inside StudentImpl:Constructor"); } public String getHobby(){ System.out.println("StudentImpl: getHobby()"); return hobby; } public void setHobby(String s){ hobby = s; }
8. Compile Studentnterface.java and StudentImpl.java. Compilation should succeed. javac interfaceexercise2\StudentInterface.java interfaceexercise2\StudentImpl.java
Introduction to Programming I
346
J.E.D.I
9. Write Main.java. package interfaceexercise2; public class Main { public static void main(String [] args ){ StudentInterface student1 = new StudentImpl(); student1.setName("Ann"); String s1 = student1.getName(); System.out.println("student1's name is " + s1); student1.setHobby("Dancing"); String s2 = student1.getHobby(); System.out.println("student1's hobby is " + s2); } } 10. Compile all the source code and run it. javac interfaceexercise2\*.java java interfaceexercise2.Main 11. Verify the result is as following C:\lab>java interfaceexercise2.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
J.E.D.I
Creating your own: 1. Write TuftsStudentInterface inteface. It should "extend" StudentInterface inteface. Define the following new methods inside the TuftsStudentInterface interface. public int add(int x, int y); public double multiply(double p, double q); 2. Write TuftsStudentImpl class. It "implements" TuftsStudentInterface. It should also "extend" StudentImpl class. 3. Modify the Main.java so TuftsStudentInterface interface. that it calls add and multiply methods of the
4. You should see the result something like following: C:\lab>java interfaceexercise2.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.2
Introduction to Programming I
348
J.E.D.I
Chapter 12 Hands-on
12.1 Exception Handling
1. Write ExceptionExample.java package exceptionexercise; public class ExceptionExample { public static void main( String[] args ){ try{ System.out.println( args[1] ); } catch( ArrayIndexOutOfBoundsException exp ){ System.out.println("Exception caught!"); }
2. Compile and run the code using a directory structure. cd \lab javac exceptionexercise\*.java java exceptionexercise.ExceptionExample 3. Verify the result C:\lab>java exceptionexercise.ExceptionExample Exception caught!
Introduction to Programming I
349
J.E.D.I
Introduction to Programming I
350
J.E.D.I
StudentRecord.java public class StudentRecord { // instance variables private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // static variables private static int studentCount = 0; /** *Returns the name of the student */ public String getName(){ return name; } /** *Changes the name of the student */ public void setName(String temp ){ name =temp; } public void setMathGrade(double grade){ mathGrade = grade; } public void setEnglishGrade(double grade){ englishGrade = grade; } public void setScienceGrade(double grade){ scienceGrade = grade; } public static void increaseStudentCount(){ studentCount++; } /** *Computes the average of the english,math and science *grades */ public double getAverage(){ double result =0; result =(mathGrade+englishGrade+scienceGrade )/3; return result; } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; }
Introduction to Programming I
351
J.E.D.I
10.2 Overloading
StudentRecord.java public class StudentRecord { // instance variables private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // static variables private static int studentCount = 0; /** *Returns the name of the student */ public String getName(){ return name; } /** *Changes the name of the student */ public void setName(String temp ){ name =temp; } public void setMathGrade(double grade){ mathGrade = grade; } public void setEnglishGrade(double grade){ englishGrade = grade; } public void setScienceGrade(double grade){ scienceGrade = grade; } public static void increaseStudentCount(){ studentCount++; } /** *Computes the average of the english,math and science *grades */ public double getAverage(){ double result =0; result =(mathGrade+englishGrade+scienceGrade )/3; return result; } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; }
Introduction to Programming I 352
J.E.D.I
public void print(String name ){ System.out.println("Name:"+name); } public void print(String name, double averageGrade){ System.out.print("Name:"+name+" "); System.out.println("Average Grade:"+averageGrade); } public void print(String name, double averageGrade, int studentCount){ System.out.print("Name:"+name+" "); System.out.println("Average Grade:"+averageGrade); System.out.println("Student count:"+studentCount); } } StudentExample2.java public class StudentRecordExample2{ public static void main(String [] args) { StudentRecord annaRecord =new StudentRecord(); annaRecord.setName("Anna"); annaRecord.setEnglishGrade(95.5); annaRecord.setScienceGrade(100); //overloaded methods annaRecord.print(annaRecord.getName()); annaRecord.print(annaRecord.getName(), annaRecord.getAverage()); annaRecord.print(annaRecord.getName(), annaRecord.getAverage(), annaRecord.getStudentCount()); } }
Introduction to Programming I
353
J.E.D.I
10.3 Packaging
1. Create Food.java under a proper directory structure cd \lab mkdir foodpackage mkdir foodpackage\fruitpackage jedit foodpackage\fruitpackage\Food.java Food.java package foodpackage.fruitpackage; public class Food { //instance variables private String color = "white"; public String getColor(){ return color; }
2. Create FoodMain.java under a proper directory structure FoodMain.java package foodpackage.fruitpackage; public class FoodMain{ public static void main(String [] args ){ Food food1 =new Food(); System.out.println("Color of the food ="+food1.getColor }
()); }
3. Compile and run the code cd \lab javac foodpackage\fruitpackage\*.java java foodpackage.fruitpackage.FoodMain 4. Verify the result C:\lab>java foodpackage.fruitpackage.FoodMain Color of the food =white
Introduction to Programming I
354
J.E.D.I
Introduction to Programming I
355
J.E.D.I
Main.java package personpackage; public class Main { public static void main(String [] args ){ Student student1 =new Student(); TuftsStudent student2 =new TuftsStudent(); Student student3 =new TuftsStudent(); // set hobbies of student2 and student3 student2.setHobby("swimming"); student3.setHobby("dancing"); // get hobbies of student2 and student3 String hobby2 = student2.getHobby(); System.out.println("Hobby of student2 " + hobby2); String hobby3 = student3.getHobby(); System.out.println("Hobby of student3 " + hobby3);
Introduction to Programming I
356
J.E.D.I
11.3 Polymorphism
Teacher.java package polypackage; public class Teacher extends Person { private String hobby; public Teacher(){ System.out.println("Inside Teacher:Constructor");
public Teacher(String name, String address){ super(name, address); System.out.println("Inside Teacher:Constructor 2 receiving two parameters: " + name + ", " + address); } public String getHobby(){ return hobby; } public void setHobby(String s){ hobby = s; } // Override getName() method of the parent class public String getName(){ System.out.println("Teacher: getName()"); return "Maybe Passionate Teacher " + super.getName(); }
} Main.java
package polypackage; public class Main { public static void main( String[] args ) { Person ref; Student studentObject = new Student("Sang", "1 Dreamland"); Employee employeeObject = new Employee("Young", "2 Dreamland"); Teacher teacherObject = new Teacher("Wende", "21 New York"); System.out.println("\n"); ref = studentObject; //Person ref. points to a // Student object //getName of Student class is called String temp1=ref.getName(); System.out.println( temp1 ); System.out.println( "temp1 -" + temp1 + "\n" ); ref = employeeObject; //Person ref. points to an // Employee object
Introduction to Programming I
357
J.E.D.I
//getName of Employee class is called String temp2 = ref.getName(); System.out.println( temp2 ); System.out.println( "temp2 -" + temp2 + "\n" ); ref = teacherObject; //Person ref. points to an // Teacher object //getName of Employee class is called String temp3 = ref.getName(); System.out.println( "temp3 -" + temp3 + "\n" ); } }
Introduction to Programming I
358
J.E.D.I
Human.java package abstractexercise; public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } public void dance(String ds){ System.out.println("Human dances in " + ds); } } Main.java package abstractexercise; public class Main { public static void main( String[] args ) { Human x = new Human(); x.walk(); x.dance("Swing"); LivingThing y = new Human(); y.walk(); y.dance("Saturday Night Live");
Introduction to Programming I
359
J.E.D.I
11.5 Interfaces 1
NumberComparion.java package interfaceexercise; public class NumberComparison implements Relation { public boolean isGreater(Object a, Object b){ Integer ai = (Integer)a; Integer bi = (Integer)b; return (ai.intValue() > bi.intValue()); } public boolean isLess(Object a, Object b){ Integer ai = (Integer)a; Integer bi = (Integer)b; return (ai.intValue() < bi.intValue()); } public boolean isEqual(Object a, Object b){ Integer ai = (Integer)a; Integer bi = (Integer)b; return (ai.intValue() == bi.intValue()); }
} Main.java
package interfaceexercise; public class Main { public static void main( String[] args ) { Line line1 Line line2 = new Line(1.0, 2.0, 1.0, 2.0); = new Line(2.0, 3.0, 2.0, 3.0);
b1);
boolean b1 = line1.isGreater(line1, line2); System.out.println("line1 is greater than line2: " + boolean b2 = line1.isEqual(line1, line2); System.out.println("line1 is equal with line2: " + b2); Line line3 = new Line(1.0, 5.0, 1.0, 5.0); boolean b3 = line3.isEqual(line1, line3); System.out.println("line1 is equal with line3: " + b3);
System.out.println("Length of line1 is " + line1.getLength()); System.out.println("Length of line2 is " + line2.getLength()); System.out.println("Length of line3 is " + line3.getLength()); System.out.println(""); Relation r1 = new NumberComparison(); Integer x = new Integer(1); Integer y = new Integer(5);
Introduction to Programming I 360
J.E.D.I
b4);
boolean b4 = r1.isGreater(x, y); System.out.println(x + " is greater than " + y boolean b5 = r1.isEqual(x, y); System.out.println(x + " is equal with " + y boolean b6 = r1.isLess(x, y); System.out.println(x + " is less than " + y
+ " " +
b5);
+ " " +
b6); }
+ " " +
Introduction to Programming I
361
J.E.D.I
11.6 Interfaces 2
TuftsStudentInterface.java package interfaceexercise2; public interface TuftsStudentInterface extends StudentInterface { public int add(int x, int y); public double multiply(double p, double q); } TuftsStudentImpl.java package interfaceexercise2; public class TuftsStudentImpl extends StudentImpl implements TuftsStudentInterface { public int add(int x, int y){ System.out.println("StudentImpl: add()"); return x+y; } public double multiply(double p, double q){ System.out.println("StudentImpl: multiply()"); return p*q; }
} Main.java
package interfaceexercise2; public class Main { public static void main(String [] args ){ StudentInterface student1 = new StudentImpl(); student1.setName("Ann"); String s1 = student1.getName(); System.out.println("student1's name is " + s1); student1.setHobby("Dancing"); String s2 = student1.getHobby(); System.out.println("student1's hobby is " + s2); System.out.println(""); TuftsStudentInterface tuftsstudent1 = new TuftsStudentImpl(); tuftsstudent1.setName("Mario"); String s3 = tuftsstudent1.getName(); System.out.println("tuftsstudent1's name is " + s3); tuftsstudent1.setHobby("Tennis");
Introduction to Programming I 362
J.E.D.I
String s4 = tuftsstudent1.getHobby(); System.out.println("tuftsstudent1's hobby is " + s4); int i1 = tuftsstudent1.add(5, 6); System.out.println("tuftsstudent1's addition is " + double d1 = tuftsstudent1.multiply(10.0, 31.12); System.out.println("tuftsstudent1's multiplication is "
i1);
+ d1); } }
Introduction to Programming I
363
J.E.D.I
References
1. Programming Language. From Wikipedia at http://en.wikipedia.org/wiki/Programming_language 2. Programming Language. From Webopedia at http://www.webopedia.com/TERM/p/programming_language.html 3. Programming Language. From Answers.com at http://www.answers.com/topic/programming-language 4. High-Level Programming Language. From Wikipedia at http://en.wikipedia.org/wiki/High-level_programming_language 5. Defining Flowchart Symbols. Available at http://www.pattonpatton.com/basic_flow_chart_symbols.htm 6. Integrated Development Environment. From Webopedia at http://www.webopedia.com/TERM/I/integrated_development_environment.html 7. Variables and Expressions. Available at http://www.geocities.com/SiliconValley/Park/3230/java/javl1002.html 8. Writing Abstract Classes and Methods. Available at http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html 9. Defining an Interface. Available at http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html 20.Inheritance and Polymorphism. Available at http://home.cogeco.ca/~ve3ll/jatutor7.htm 21.The Essence of OOP using Java, Runtime Polymorphism through Inheritance. Available at http://www.developer.com/tech/article.php/983081 22.Gary B. Shelly, Thomas J. Cashman, Joy L. Starks. Java Programming Complete Concepts and Techniques. Course Technology Thomson Learning. 2001. 23.Stephen J. Chapman. Java for Engineers and Scientists 2nd Edition. Pearson Prentice Hall. 2004 24.Deitel & Deitel. Java How to Program 5th Edition. 25.Sun Java Programming Student Guide SL-275. Sun Microsystems. February 2001. 26.Does Java pass by reference or pass by value? Why can't you swap in Java? Available at http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html 27.Java Branching Statements. Available at http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html. 28.Encapsulation. Available at http://home.cogeco.ca/~ve3ll/jatutor4.htm.
Introduction to Programming I
364