ebook img

Blue Pelican Java PDF

541 Pages·2013·3.054 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Blue Pelican Java

Blue Pelican Java by Charles E. Cook Version 7.0.1A Copyright © 2004 - 2013 by Charles E. Cook; Refugio, Tx (All rights reserved) 1-1 “Blue Pelican Java,” by Charles E. Cook. ISBN 1-58939-758-4. Published 2005 by Virtualbookworm.com Publishing Inc., P.O. Box 9949, College Station, Tx 77842, US. ©2005, Charles E. Cook. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, recording or otherwise, without the prior written permission of Charles E. Cook. Manufactured in the United States of America. Preface You will find this book to be somewhat unusual. Most computer science texts will begin with a section on the history of computers and then with a flurry of definitions that are just “so many words” to the average student. My approach with Blue Pelican Java is to first give the student some experience upon which to hang the definitions that come later, and consequently, make them more meaningful. This book does have a history section in Appendix S and plenty of definitions later when the student is ready for them. If you will look at Lesson 1, you will see that we go right to work and write a program the very first day. The student will not understand several things about that first program, yet he can immediately make the computer do something useful. This work ethic is typical of the remainder of the book. Rest assured that full understanding comes in time. Abraham Lincoln himself subscribed to this philosophy when he said, “Stop petting the mule, and load the wagon.” The usual practice in most Java textbooks of introducing classes and objects alongside the fundamental concepts of primitive variable types, loops, decision structures, etc. is deferred until the student has a firm grasp of the fundamentals. Thus, the student is not overwhelmed by simultaneous introduction of OOPs (Object Oriented Programming) and the fundamentals. Once introduced, (Lesson 15), OOPs is heavily emphasized for the remainder of the book. I fully realize that there are those who disagree with this idea of deferring the introduction of OOPs, and from their own point of view, they are right. In most cases they teach only the very highest achieving, mature students. In those cases, I agree that it is acceptable to begin with OOPs; however, for the average student and especially for younger high school students, I feel that they need to understand the fundamentals first. Upon first examination of this book it may not appear to be very “robust” in that there is not great depth for some of the topics. Actually the depth is there,… in the Appendix. The Appendix for this book is unusually large. Here is why the book is organized this way: • The lessons are kept purposely short so as to hold down the intimidation factor. As a result, the lessons should look “doable” to the students. • The in-depth material is placed in the Appendices, and references to the Appendices are made in the lessons. As an example, in Lesson 18 the split method is introduced. The split method uses regular expressions that are briefly discussed there; however, the in-depth presentation of regular expressions is placed in Appendix AC. Unfortunately, this book does not introduce any graphics or windows programming. The 57 lessons in this book can be covered in one school year, but just barely. To prepare students for the AP test (and contests) there is only time to cover the essentials presented in this book. Check http://www.bluepelicanjava.com for the availability of study materials for the current AP case study, updates on this book, videos for each lesson, and an inexpensive way to purchase hard-cover books. I am often asked how to use this book. “Which lessons are really important and which can be skipped?” The answer is simple: • Start on Lesson 1. • Proceed at a reasonable rate. (See Appendix P for a time-line.) • Don’t skip anything (except for, perhaps Lesson 47 and Lesson 53) • Give a simple, confidence-building quiz on each lesson. Quizzes and keys are provided in the Answer Book (available at www.bluepelicanjava.com). • Make sure the students do the provided exercises and projects. • Give tests at regular intervals. Tests and keys are provided in the Answer Book. In this book you will also notice another part of my philosophy of teaching and educational material in general…Keep it simple… I try to keep things as simple and uncluttered as possible. For example, you will find specific examples in greater numbers than long-winded explanations in this book. You won’t find many pictures and sidebars and lots of little colored side notes scattered about. Some of that type format does contain some useful information; however, I feel that it is largely distracting. Apparently more and more people are coming around to my way of thinking on this, and here is why I think so. Recall that just a few years ago that nearly all web pages looked like cobbled together ransom notes with just a profusion of colors, links, and tidbits scattered all over the page. Take a look at professional web pages today. They typically have a very neat, clean appearance…often with just a plain white background and with plenty of space between the various elements. This is good. Simple is better. Since this textbook has a strong emphasis on preparation for the AP test and competition (computer science contests), special “contest type” problems are provided at the end of most lessons. I realize that most students will not compete and some may not even take the AP exam; however, the material is not wasted on them. Those “contest type” problems are good for the average student too, as long as they are not overwhelmed with too many problems at one sitting. Hopefully, I have just the optimum number of these type problems on each lesson and students won’t be burned-out by too much of a good thing. Finally, we come to the reason for the choice of Blue Pelican Java as a name for this book. One of the early (and free) java IDE’s available for students was BlueJ and it was the first my students used. I always thought BlueJ was an elegant name and had expressed a desire to a colleague to continue the tradition by naming the book after some other blue-colored bird. He jokingly suggested Blue Pelican, not really being serious about naming a book after this rather ungainly, clunky bird. For the lack of an existing name for the book during development, it continued to be called Blue Pelican. If you call something by a particular name long enough, that’s its name, and so the name stuck. I truly hope Blue Pelican Java is useful to you and that you find the experience of learning to program a rewarding one. Just remember, few things worthwhile are acquired without some sacrifice. The “sacrifice” here will be the time you invest in creating programs and trying the code suggested in these pages. Charles E. Cook Table of Contents - 1 Table of Contents Some of the numbered lessons below are marked with an asterisk (*). This indicates they are subjects not covered by the AP A test. All other lessons have at least “potential relevance”. Lesson Title Description Page 1 Hello World Simple use of println, rems, remarks, comments, 1-1 block rems. Project… From Me to You 2 Variable Types String, int, double, legal names, illegal names, 2-1 declaring, initializing 3 Simple String Operations Concatenation, length, substring, toLowerCase, 3-1 toUpperCase, escape sequences, backslash Project… Name That Celebrity 4 Using Numeric variables Assignment, ++, --, modulus, +=, -=, /=, *=, 4-1 PEMDAS, increment, decrement, multiple declarations, remainder, compound operator, round- off. Project…Cheating on Your Arithmetic Assignment 5 Mixed Data Types, Casting, and final, mixed arithmetic, casting. Project… Mixed 5-1 Constants Results 6 Math Class Methods abs, pow, sqrt, ceil, floor, log, min, max, round, PI, 6-1 sin, cos, tan, asin, acos, atan, toDegrees, toRadians. Project… Compute This 7 *Input from the Keyboard Scanner class, nextInt, nextDouble, next, nextLine, 7-1 Project… Going in Circles, Project… What’s My Name? 8 boolean Type and Operators AND, OR, NOT, precedence 8-1 9 “if” statement equals, equalsIgnoreCase. Project…Even or Odd? 9-1 10 The “switch” Statement and char switch, default, break, char. Project… Weight on 10-1 Other Planets 11 The “for” Loop Initializing, control, and step expressions. break, 11-1 infinite loops, scope, for-loop project, Project… Name Reversal 12 while and do-while loops Testing at top and bottom of loop, break, continue 12-1 13 ASCII and more on char ASCII codes for numbers and letters, conversion 13-1 from String to char, conversion from char to String, isDigit, is Letter, isLetterOrDigit, isLowerCase, isUpperCase 14 Binary, Hex, and Octal Conversion between number systems, binary 14-1 addition. Project… Basically Speaking 15 Classes and Objects Instantiate, methods, state variables, constructor, 15-1 signature, public, void, Project… What’s That Diameter? Project… Overdrawn at the Bank 16 More on Classes & Objects Private methods and state variables, different lines to 16-1 declare and instantiate, setting objects equal, equality of objects, reassignment of objects, Project… Gas Mileage 17 Advanced String Methods compareTo, indexOf( ), lastIndexOf( ), charAt( ), 17-1 replace( ), trim, Scanner, reg expr. Project… Add ‘em Up, Project… Encryption / Decryption Table of Contents - 2 18 Arrays Declaring and initializing, length, parallel arrays, 18-1 Out-of-bounds exception, passing an array to a method, automatic initialization, split, reg expr. Project… Array of Hope 19 Advanced Array Concepts Arrays of objects, comparison of array values, null 19-1 pointer exception, different reference to same array, arraycopy, toCharArray, logical vs physical size, Arrays class, sort, binarySearch, equals, fill, importing, command line arguments, enhanced for- loop. Project… Sorting a String Array. Project… Two Orders for the Price of One 20 Static Methods and State Class methods and variables, static constants static 20-1 Variables imports. Project… How Far To The Line? 21 Wrapper Classes Converting primitives to objects and vice versa 21-1 22 More on Wrapper Classes parseInt, parseDouble, toHexString, toOctalString, 22-1 toBinaryString, toString, valueOf 23 *Input from a Disk File Scanner, File, throws IOException, readLine, Project 23-1 for Reading Files, close, Project… Reading Files 24 *Processing File Input with Processing text coded numbers, using parseInt and 24-1 Scanner parseDouble, parsing and manipulating text, Project… Get Rid of That Plus Sign!, Project… Student Averages 25 *Writing to a Text File FileWriter, PrintWriter, print, println, appending to 25-1 the end of a file, close, Project… Write Student Averages 26 *Formatting (rounding off) NumberFormat, formatting numbers, currency, and 26-1 percent, Formatter class, printf. Project… BaseClass. Project… Gymnastics 27 *Bitwise operators Bitwise-AND, OR, exclusive-OR, and NOT. 27-1 Negative numbers, sign bit, msb, most significant bit 28 *Advanced Bitwise Operations Shift left and right, <<, >>, >>>, preservation of 28-1 sign, short-circuit, precedence. Negative numbers, sign bit, msb, most significant bit. Project… Tweaking for Speed 29 *Random Numbers nextDouble, nextInt, Monte Carlo, simulations, 29-1 Project… Monte Carlo Technique 30 *StringBuffer Class append, toString, substring, length, setCharAt, 30-1 delete, deleteCharAt, insert, charAt. Project… Concatenations Gone Wild 31 *Boolean Algebra and OR, AND, truth table 31-1 DeMorgan’s Theorem 32 *Selection Operator ?: syntax 32-1 33 Passing by Value and by Arrays, primitives, objects, references. Project… 33-1 Reference Pass the Gravy, Please 34 Two-Dimensional Arrays Subscripted variables, matrix, initializing, Arrays 34-1 class. Project… Matrix Multiplication, Project… Matrix Multiplication with File Input 35 Inheritance Superclass, subclass, base class, derived class, 35-1 abstract, final, overriding, shadowing, cosmic superclass, instanceof, Object, this, super Table of Contents - 3 36 Exceptions Checked, unchecked, try, catch, finally, throw, 36-1 throws, Project… Keep Trying 37 Interfaces Implementation perspective,objective perspective, 37-1 instanceof, polymorphism, realizes, implements.,Project… Linear Function 38 *Complexity Analysis (Big O) sequential search, binary search 38-1 39 Recursion Factorial, Fibonacci series, Project… Fibonacci 39-1 40 Sorting Routines selection, insertion, quick, & merge sorts, partition, 40-1 big O chart, Project… Multiple Key Sorting 41 List Interface ArrayList, LinkedList, Vector 41-1 42 ArrayList advantages, disadvantages, Project… Big Bucks in 42-1 the Bank 43 *Iterator/ListIterator stepping through a list, Project… Big Bucks 43-1 Revisited 44 Comparable/Comparator compare objects, compare, compareTo, Project… 44-1 Sorting BankAccount Objects, Project…Sorting BankAccount Objects Alphabetically, Project… Sorting BankAccount Objects using a Comprator 45 *HashSet/TreeSet Set interface, Iterators, Project… HashSet/ 45-1 Intersection, Project… HashSet/Union 46 *HashMap/TreeMap Keys, values, Map interface, iterator, Project… 46-1 Mapping Bank Accounts, Project…Code Talker, Project…Histogram, Project…Student Classification 47 *Flow Charts & Optimizing for Writing code for a flow chart. Project… Divisors of 47-1 Speed a Number, Project… Optimized Code for Divisors, Project… Super Optimized Code for Divisors, Speed tricks 48 *Singly Linked List Example list of pipeline nodes. Project… insert 48-1 Method for Singly Linked List 49 *The LinkedList Class (doubly Methods of the LinkedList class used to implement a 49-1 linked) and Stacks Stack class (push, pop, etc). Queues. Project… StackLL Class. Project… Stack Calculator 50 Binary Search Binary search of primitive arrays & object arrays, 50-1 recursive search . Arrays.sort, Arrays.binarySearch. Project…Binary Search, Reverse Order; Project… Binary Search with Objects 51 *Binary Search Trees Binary search trees. Preorder, inorder, postorder, and 51-1 in level traversals. Expression trees. Project… BST find Method 52 *Queues LinkedListQueue, ArrayListQueue. Project… 52-1 Who’s Next?, Project.… Shifting Marquee 53 *Inner Classes Project… Inner Class inside Outer Class, 53-1 Project… Inner Class Inside Method 54 *Heaps Complete and full trees, adding and deleting nodes. 54-1 Project… Printing a Heap, …A Heap of Trouble 55 *Priority Queues Heap based priority queue, array implementation. 55-1 Project… Who Has Highest Priority?, Project… Smile for the Camera Table of Contents - 4 56 *Lookup Tables and Hashing Lookup tables, hashing techniques, collisions, 56-1 chaining, probing load factor, and Object class methods. Project… A Taste of Hash; Project… Hashing Abraham Lincoln Case Study… A major project… Distance to a Meandering Trail CS1-1 Golden Nuggets of Wisdom are short learning/review activities. In the six weeks preceding an AP exam, contest, or other major evaluation, study one of these each day. Follow up with a quiz (provided in the Teacher’s Test/Answer Book) on that topic the next day. #1 Golden Nugget of Wisdom #1 loop variable after exiting loop Ng1 #2 Golden Nugget of Wisdom #2 overriding, overloading, polymorphism Ng2 #3 Golden Nugget of Wisdom #3 implements, realizes, log, exclusive or Ng3 #4 Golden Nugget of Wisdom #4 charAt, special feature of substring Ng4 #5 Golden Nugget of Wisdom #5 masking Ng5 #6 Golden Nugget of Wisdom #6 implementing an interface, converting decimal Ng6 number to binary, hex, an octal #7 Golden Nugget of Wisdom #7 StringBuffer insert,alph order, simultaneously adding Ng7 and concatenating #8 Golden Nugget of Wisdom #8 escape characters, null, continue, break, selection Ng8 #9 Golden Nugget of Wisdom #9 operator (?:), bitwise not, modulus with fractions Ng9 #10 Golden Nugget of Wisdom #10 final, arraycopy, calling a different constructor Ng10 #11 Golden Nugget of Wisdom #11 LIFO, FIFO, bitwise ANDing and ORing of Ng11 booleans, modulus with negative numbers #12 Golden Nugget of Wisdom #12 casting, incompatible object comparison, access Ng12 control modifier #13 Golden Nugget of Wisdom #13 mixed arithmetic, declaring an array of objects Ng13 #14 Golden Nugget of Wisdom #14 equality between Wrapper class objects, hex, binary, Ng14 octal, exclusive or #15 Golden Nugget of Wisdom #15 short circuiting, valueOf, converting numerics to Ng15 Strings #16 Golden Nugget of Wisdom #16 Order within method signature, String replace, Ng16 nextToken delimiter #17 Golden Nugget of Wisdom #17 indexOf, different references to same array, setting Ng17 arrays and other objects equal to null #18 Golden Nugget of Wisdom #18 subclass method overriding superclass method, Ng18 equivalence of methods and function, equivalence of signatures and headers #19 Golden Nugget of Wisdom #19 multiple constructors Ng19 #20 Golden Nugget of Wisdom #20 initialization blocks Ng20 #21 Golden Nugget of Wisdom #21 initializing numeric state and method variables Ng21 #22 Golden Nugget of Wisdom #22 prototype, short-circuiting, isLetter (etc) Ng22 #23 Golden Nugget of Wisdom #23 char & int, ASCII, casting, XOR Ng23 #24 Golden Nugget of Wisdom #24 boolean simplification, law of absorption, printing 2- Ng24 D arrays. #25 Golden Nugget of Wisdom #25 random numbers, maps, sets, keyset Ng25 Table of Contents - 5 #26 Golden Nugget of Wisdom #26 recursion Ng26 #27 Golden Nugget of Wisdom #27 Big O, floor, ceil, round Ng27 #28 Golden Nugget of Wisdom #28 split method Ng28 #29 Golden Nugget of Wisdom #29 Iterator, ListIterator, exceptions, abstract, final Ng29 #30 Golden Nugget of Wisdom #30 Static methods and variables, NumberFormat, Ng30 ListIterator interface Appendix Key Words Reserved words that are part of Java A-1 A Appendix Escape Sequences \b \t \n \” \’ \\ A-1 B Appendix Primitive Data Types byte, short, int, long, float, double, char, boolean C-1 C Appendix ASCII Codes Decimal, hex, octal, and html equivalents D-1 D Appendix Saving Text Files Windows settings, Notepad, WordPad E-1 E Appendix Text and Binary Files Explained Storage methods F-1 F Appendix Two’s Complement Notation Negative numbers, invert, ones’ compliment, ten’s G-1 G complement, odometer, msb, sign bit Appendix Operator Precedence Order of operations H-1 H Appendix Creating Packages and Importing, package, wildcard, 6steps to create a I-1 I Importing Classes package, classpath variable Appendix Typical Contest Classes and Scope of UIL contest J-1 J Interfaces Appendix Exception Classes A list of some checked and unchecked exceptions K-1 K Appendix An Essay on Interfaces Down to earth explanation of Interfaces L-1 L Appendix Input from the Keyboard BufferedReader, InputStreamReader. M-1 M Appendix Using the BlueJ Programming Creation of projects and classes N-1 N Environment Appendix Using the JCreator Programming Creation of projects and classes O-1 O Environment Appendix Time Allocation for Lessons Time allocation for each lesson P-1 P Appendix AP(A) Correlation Page number correlation Q-1 Q Appendix Texas TEKS/TAKS Correlation Page number correlation to TEKS R-1 R Appendix History of Computers Pascal, Babbage, ENIAC, operating systems, MITS S-1 S Altair, TRS 80, Apple, IBM pc, disk storage, key punch cards Appendix Viruses What a virus is, how they are spread, types, T-1 T protection, ethics, and etiquette Table of Contents - 6 Appendix Enrichment Activities Use of LANs and WANs, Using a scanner and OCR U-1 U software, Software specifications, Publish Information, Electronic communities Appendix Computer Languages Java, Visual Basic, Java Script, Assembly language, V-1 V Machine code, Compiled vs Interpreted languages Appendix Binary Tree Terms Definitions of terms related to binary trees. W-1 W Appendix Compiling and Executing Using javac.exe, java.exe, and javaw.exe. X-1 X without and IDE Compiling and executing, DOS prompt, Path Variable Appendix Kilobytes, Megabytes, Tables with exact values “power of two” equivalents Y-1 Y Gigabytes Appendix The DecimalFormat Class Formatting numbers, currency, and percents with Z-1 Z patterns Appendix Matrix Multiplication Matrix multiplication explained in detail AA-1 AA Appendix Monospaced Fonts Vertical alignment of printout AB-1 AB Appendix Regular Expressions A discussion on how to build and interpret regular AC-1 AC expressions. Additional methods of the String class; split, replaceAll, replaceFirst Appendix Formatter class specifiers and Format specifiers, format flags AD-1 AD flags Appendix javaDoc The javDoc technique for generating web based AE-1 AE documentation. Appendix Generic Classes Creation of generic classes AF-1 AF Appendix Pattern and Matcher classes Discussion and examples of the methods of the AG-1 AG Pattern and Matcher classes. Index Indx- 1

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.