You are on page 1of 32

Introduction to Computer Science using Java

Bradley Kjell, Central Connecticut State University

This

is a course in Java programming for

For more about these notes check


the frequently asked questions. A German translation of these notes, done by Heinrich Gailer, is available at www.gailernet.de/tutorials/java/java-toc.html. A French translation of selected chapters is available at www.lifl.fr/~secq/IUT/JAVA/intro.htm l

beginners. It covers the fundamentals of programming, roughly the same material that is covered in a beginning programming course in a university or in a high school AP Computer Science course. For maximum benefit, go though these notes interactively, thinking about and answering the question at the bottom of each page. There are about 20 pages per chapter. If you spend about 3 minutes per page each chapter will take about 60 minutes, or longer if you copy and run some of the programs. If you are a beginning programmer, plan on spending more than a month with this.

Here is very nice site (unrelated to this site) that allows you to practice Java programming on line: These notes assume that you have the Java http://javabat.com. version 5.0 or later from Oracle, Inc. at Another nice site (unrelated to this http://www.oracle.com/technetwork/java/index.ht site) that allows you to run Java ml and a text editor such as Notepad. Compiling programs directly in your browser is: and running programs is done from the command http://ideone.com. line interface. You may use more sophisticated environments, as well. An alternate site, with faster response time, that contains this material is: Mirror Site Best viewed at 1024 x 768 or higher. The audio works best with Windows Media Player.

Part 1: Hardware and Software


Chapter 1
Introduction to Computer Systems

Quiz

Flash Cards.

Chapter 2 Analog and Binary Signals Chapter 3 Computer Memory Chapter 4 The Processor

Quiz Quiz Quiz

Flash Cards. Flash Cards. Flash Cards.

Part 2: Running Java Programs


Chapter 5 Introduction to Java Chapter 6 Small Java Programs Chapter 7
How to Run the Example Programs

Review Review Review

Part 3: Data
Chapter 8 Primitive Data Chapter 9A Chapter 9B Chapter 9C Chapter 10 Chapter
Variables and the Assignment Statement Expressions and Arithmetic Operators Object Data

Quiz

Exercises and Flash Cards Exercises

Quiz

Quiz

Exercises

Quiz

Exercises

Input and Output Floating Point

Review Exercises Review Exercises

11

Part 4: Branches and Loops


Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20
The if Statement The Single Branch if Statement Boolean Expressions Loops and the while statement Counting Loops

Quiz

Exercises

Quiz

Exercises

Review Exercises

Review Exercises

Quiz

Exercises

Nesting Loops and Ifs

Review Exercises

Sentinel-controlled Loops

Review Exercises

Result-controlled Loops

Quiz

Exercises Exercises and Review

Random

Quiz

Part 5: File Input and Output


Chapter 21 Chapter 22
Files and File Redirection Reading Data with File Redirection

Review Exercises

Review Exercises

Chapter 23 Chapter 24 Chapter 24B

I/O using Scanner and PrintStream File Input Techniques

Review Exercises

Review Exercises

Formatted Output

Quiz

Exercises

Part 6: Object Oriented Programming


Chapter 25 Chapter 26 Chapter 27 Chapter 28 Chapter 29 Chapter 29B Chapter 30 Chapter 31 Chapter 32 Chapter 33
Objects

Quiz

Object References

Quiz

More about Objects and Classes Review

Method Parameters

Review

Strings and Object References

Quiz

Exercises

More about Strings

Quiz Review

Exercises

Defining your own Classes Class Design Example (miles per gallon) Class Design Example (checking account) Encapsulation and Visibility Modifiers

Exercises

Review Exercises

Review

Quiz

Exercises

Chapter 34A Chapter 34B Chapter 35

Parameters, Overloading, Local Review Variables Object Parameters

Quiz

Objects that Contain Objects

Review Exercises

Part 7: Applets and Graphics


Chapter 36 Chapter 37 Chapter 38
Applets

Quiz

Exercises

Applet Examples

Quiz

Exercises

More Applet Examples

Quiz

Exercises

Part 8: More Java Features


Chapter 39 Chapter 40 Chapter 40B Chapter 41 Chapter 42 Chapter
Increment, Decrement, and Assignment Operators

Quiz

Boolean Expressions and ShortQuiz circuit Operators Truth Tables and De Morgan's Laws The for Statement

Review

Quiz

Exercises

More about the for Statement Quiz

Exercises Exercises

The Conditional Operator and

Quiz

43 Chapter 44

the switch Statement The do Statement

Quiz

Exercises

Part 9: Arrays
Chapter 46 Chapter 47 Chapter 48 Chapter 49A Chapter 49B Chapter 49C Chapter 49D
Introduction to Arrays

Quiz

Exercises

Common Array Algorithms

Quiz Review

Exercises

Arrays as Parameters

Exercises

Methods that Change Arrays Arrays of Objects and Linear Search Two-dimensional Arrays

Quiz

Quiz

Exercises

Quiz

Exercises

StringBuffers

Quiz

Exercises

Part 10: Advanced Object Oriented Programming


Chapter 50 Chapter 51 Chapter 52
Introduction to Inheritance Abstract Classes and Polymorphism More about Polymorphism

Quiz

Quiz

Quiz

Chapter 53 Chapter 53B Chapter 54

Interfaces

Quiz

Exercises

The Comparable Interface

Quiz

Exercises

ArrayLists and Iterators

Quiz

Part 11: Graphical User Interface Programming


Chapter 55 Chapter 56 Chapter 57 Chapter 59 Chapter 60 Chapter 61 Chapter 62 Chapter 63 Chapter 64
Introduction to GUI Programming JFrames

Quiz

Quiz

Adding Buttons to a Frame

Quiz

Buttons and Action Events

Quiz

Exercises

JTextFields and JLabels

Quiz

Exercises

GUI Applications

Quiz

Exercises

JPanel and BoxLayout

Quiz

Radio Buttons and BorderLayout

Exercises

JSliders and Change Events

Exercises

Part 12: Recursion


Chapter 70 Chapter 71 Chapter 72 Chapter 73 Chapter 74 Chapter 75
Introduction to Recursion

Quiz

Exercises

Recursion in Java

Quiz

Exercises

Examples of Recursion

Quiz

Exercises

More Recursion

Quiz

Exercises

Recursion with Graphics

Exercises

Recursion with Strings

Exercises

Part 13: Exceptions and IO Streams


Chapter 80 Chapter 81 Chapter 82 Chapter 83 Chapter 84 Chapter 85
Exceptions

Quiz

Exercises

More about Exceptions

Quiz

Exercises

Input and Output Streams

Quiz

Writing Text Files

Quiz

Exercises

Reading Text Files

Quiz

Exercises

Writing Binary Files

Quiz

Exercises

Chapter 86 Chapter 87

Reading Binary Files

Quiz

Exercises

The File Class

Quiz

Exercises

Appendix

Appendix A Introduction to HTML

Part 1 Pages, Paragraphs, and Fonts. Part 2 Lists, Links, and URLs. Part 3 Applets, Images, and Tables. Appendix B Installing Java Appendix C Editing the PATH variable
o o o

Computer Systems
A computer is a complex system consisting of both hardware and software components. This chapter discusses these components. Chapter Topics:

Hardware and Software Components of a Computer System Networks World-Wide Web

..

CHAPTER 2 Analog and Binary Signals

Everyone knows that computers are "digital" and that they use "binary" numbers. You probably have some idea of what these terms mean. But we need to be clear about their precise meaning and to be clear about why computers are digital. Chapter Topics:

Binary signals Analog signals Advantages of Binary Bits Noisy signals

Study these topics carefully if you want to know what is really going on with computers.

QUESTION 1:
Why is a digital wristwatch called "digital"?

CHAPTER 3 Computer Memory


Chapter Topics:

Bits and Bytes Kilobytes, megabytes, gigabytes Main memory and addresses Secondary memory Files

Recall from chapter one that the major hardware components of a computer system are:

Processor Main memory Secondary memory devices Input/output devices

This chapter looks at main and secondary memory.

QUESTION 1:
(Educated Guess: ) If you bought a new computer, about how much main memory would you expect it to have: 200 bytes, 2 kilobytes, 2 megabytes, or 2 gigabytes?

CHAPTER 4 The Processor

Chapter Topics:

Machine operations and machine language Example of machine language Different types of processor chips High level programming languages Language translators (compilers) Language interpreters

From previous chapters you know that the major hardware components of a computer system are:

Processor Main memory Secondary memory devices Input/output devices

This chapter examines the "brain" of the computer system the processor. Then it shows how the programs you write are translated into instructions for the processor.

QUESTION 1:
What component of a computer system is directly responsible for running a program?

CHAPTER 5 Introduction to Java


Chapter Topics:

Hello World program Java Bytecodes Java compiler and Java virtual machine Using Notepad to create a source program Running a Java program

The previous chapters have discussed computer hardware, computer software, bits and bytes, machine language, language translation, language interpretation, and virtual machines. This chapter assumes that you know all that and are ready to look at Java.

These notes are written for Java 2 Standard Edition version 5.0 or higher. Many features were added to this edition and previous versions will not work as well with these notes. If you are installing Java for the first time on your computer, install Java 2 Standard Edition version 6.0 or higher. See Appendix B for information on how to do this.

QUESTION 1:
Can the processor of a computer system directly execute source programs written in Java?

CHAPTER 6 Small Java Programs


Chapter Topics:

Small example programs Names for source files and class files Syntax errors Bugs The Edit, Compile, and Run cycle Matching braces Neat indenting

The previous chapter discussed the mechanics of creating and running a Java program. This chapter is an overview of Java using the example program from that chapter.

QUESTION 1:
(Review:) What role in Java programming does each of the following files play?

Source code file Bytecode file

CHAPTER 7 Running Example Programs


Chapter Topics:

How to copy, paste, compile, and run programs Starting Notepad and the command prompt Copying text to the clipboard Pasting text from the clipboard to Notepad Saving the text as a source file Running a program

These notes show many example programs. You need to run them and play with them. The most effective way to learn programming is to fiddle around with example programs. You don't have to type in the programs to run them. If you can see the program in a browser window, then you can easily copy it to Notepad (or other editor) and then save the text to a file. Once that is done, you can compile and run the program as described in the previous chapter. If this is perfectly clear skip this chapter. If not, this chapter walks you through these steps. Super Easy Way to Run Java: The web site http://ideone.com/ lets you copy-andpaste Java code into a web page text box, then compile and run it completly within your browser. This is ideal for playing with the example programs in many of these chapters.

QUESTION 1:

Is it sometimes beneficial to type in a program rather than just copying it?

CHAPTER 7 Running Example Programs


Chapter Topics:

How to copy, paste, compile, and run programs Starting Notepad and the command prompt Copying text to the clipboard Pasting text from the clipboard to Notepad Saving the text as a source file Running a program

These notes show many example programs. You need to run them and play with them. The most effective way to learn programming is to fiddle around with example programs. You don't have to type in the programs to run them. If you can see the program in a browser window, then you can easily copy it to Notepad (or other editor) and then save the text to a file. Once that is done, you can compile and run the program as described in the previous chapter. If this is perfectly clear skip this chapter. If not, this chapter walks you through these steps. Super Easy Way to Run Java: The web site http://ideone.com/ lets you copy-andpaste Java code into a web page text box, then compile and run it completly within your browser. This is ideal for playing with the example programs in many of these chapters.

QUESTION 1:
Is it sometimes beneficial to type in a program rather than just copying it?

CHAPTER 9 Variables and Assignment Statements

In all but the smallest programs, an executing program is constantly working with values. These values are kept in little sections of main memory called variables. Chapter Topics:

Variables Assignment Statements Expressions Arithmetic Operators

QUESTION 1:
Do you imagine that a variable can change its value?

CHAPTER 9B Expressions and Arithmetic Operators


This chapter continues the discussion of arithmetic expressions, integer operators, and floating point operators.

Chapter Topics:

Review of Expressions Arithmetic Operators Integer operators Floating point operators Mixed Floating point and Integer Expressions Constants

QUESTION 1:
(Review: ) Is the following correct?
13 * 6 -

CHAPTER 9C Object Data


This chapter briefly discusses objects and how to use them. The objects discussed here are defined in the standard software packages that come with Java. Later chapters discuss how you can define your own objects. Chapter Topics:

Classes Objects Reference variables String objects Running methods of objects Methods that create String objects Type wrappers Packages

Chapter 25 and following discuss objects in greater detail than this chapter.

QUESTION 1:
(Review: ) What are the two divisions of data in Java?

CHAPTER 10 Input and Output


This chapter discusses input and output for Java 5.0 and above. Most programs input data, process it, and then output the results. This chapter discusses ways to input data from the keyboard and output results to the monitor. Later chapters will discuss input and output from disk files and other media. Chapter Topics:

Input and Output Streams The standard I/O streams Scanner class Exceptions Converting character data to type int

Note: Some books show input done using classes written by the book's author. To use them, you must install a package from a CD or from a web site. This is OK. You can use these notes (with standard Java methods) along with your text without any interference.

QUESTION 1:
When a computer program does an input operation, in which direction does the data flow?

From an outside device into the program? From the program out to some device?

CHAPTER 11 Floating Point

Java includes the primitive types float and double, which hold floating point numbers. When converted to characters, floating point numbers include a decimal point followed by a decimal fraction. For example, 3.14159 and -0.718802. Chapter Topics:

Converting strings to double Keyboard input of floating point numbers The Math class Square root Trig functions PI Not a Number (NaN)

All of the familiar mathematical functions such as sine, log, and square root are available to your program in the Java Math class. These functions usually use arguments of type double, and usually return values of type double.

QUESTION 1:
Which uses more bits: a Java float or a a Java double ?
9/26/98, 08/01/99, 12/09/99, 01/12/06, 07/09/08

CHAPTER 12 Decision Making

This chapter looks at how computer programs make decisions using the if statement. This statement is one of the fundamental building blocks of programming. Chapter Topics:

Two-way Decisions The if statement Outline of a two-way decision Blocks of statements Boolean Expressions Relational Operators Example Programs

QUESTION 1:
You are driving in your car and it starts to rain. The rain falls on your windshield and makes it hard to see. Should your windshield wipers be on or off?

CHAPTER 13 Single-branch if Statements

This chapter looks at more ways to make decisions. Chapter Topics:


Single-branch if statements Boolean expressions that use arithmetic Picking the right relational symbol Several if statements in a program

QUESTION 1:
You are walking through the shopping mall and are a little bit hungry. Pleasant aromas tempt you as you pass by a cookie store. What will you do?

revised: 10/01/98, 12/09/99, 01/20/00, 01/14/06, 06/04/06, 10/08/08

CHAPTER 14 Boolean Expressions


if statements of the previous chapters ask simple questions such as count<10. Often simple questions are not enough. This chapter discusses ways to
The ask more complicated questions. Chapter Topics:

Relational Operators (review)

Logical Operators AND Operator How to check that a number is in range Boolean Expressions OR Operator Comparison between AND and OR NOT Operator

Questions involving boolean expressions have been prominent on past AP Computer Science Tests.

QUESTION 1:
You have decided to bake some cookies (much cheaper than buying them at the Mall). An interesting cookie recipe calls for 4 cups of flour and 2 cups of sugar. You look in your pantry and find 3 cups of flour and 2 cups of sugar. Can you bake cookies with what you have?

CHAPTER 15 Loops
Chapter Topics:

The while statement Syntax and semantics of the while statement The loop body Three parts of a loop that must be coordinated Counting loops and the loop control variable

Most modern machines work by endlessly repeating the same motions. The engine in your car cycles through the same motions over and over as it burns gasoline to provide power. Electric motors are similar. They convert electric power into circular motion. Because of their circular motions, these machines keep going as long as you want. Computer programs use cycles, also. In programming, a cycle is called a loop. When a program has a loop in it, some statements are done over and over as long as is needed to get the work done. Most computer programs execute many millions of program statements each time they are used. Usually the same statements are executed many times. This chapter discusses several kinds of programming loops.

QUESTION 1:
Think of some machines (mechanical or other) that use cycles.

CHAPTER 16 More about Counting Loops


Chapter Topics:

Counting upward by two's The while condition as a gatekeeper Iteration Decrementing the loop control variable Infinite loops Basing a value on the loop control variable

This chapter gives you more practice with counting loops. There are other types of loops, but counting loops are by far the most common and well worth further study.

QUESTION 1:
(Review) What three parts of a loop must be coordinated for it to work properly?

CHAPTER 17 Nesting Loops and Ifs


Chapter Topics:

Adding up even and odd integers Computing N factorial Dropping a brick Making a rectangle of stars

This chapter shows how counting loops and if statements are used together to implement the logic of a program. These examples give you practice in building programs out of fundamental pieces.

QUESTION 1:
With only paper and pencil, would you like to add up all the integers from one to one thousand?

CHAPTER 18 Sentinel Controlled Loops


Chapter Topics:

Sentinel-controlled loops Example programs: o Adding up a list of integers o evaluating polynomials Using an if-else statement inside the loop body Matching up if's with else's Using a String value as a sentinel

The previous chapters have discussed loops in general, and counting loops in particular. The same statements that are used to build counting loops are used to build other kinds of loops. This chapter looks at a kind of loop called a sentinel controlled loop.

QUESTION 1:
Say that you want a program that adds up any number of integers entered from the keyboard. Will a loop be used in this program?

CHAPTER 19 Resultcontrolled Loops


A third kind of loop can be built from the fundamental control statements in Java. This is the result-controlled loop. (Other names for it are free loop and general loop). A result-controlled loop keeps looping until the computation has reached a particular goal, without knowing exactly how long that might take. It is like the instruction in a cookie recipe that says "keep stirring until the ingredients are thoroughly blended." You quit stirring only when the desired goal has been achieved. Chapter Topics:

Result controlled loops Example programs: o Savings account interest o Newton's method Nested Loops Improving an estimate by iteration Precision of double precision variables

QUESTION 1:
You put $1000 in the bank at 5% annual compound interest. How much will you have at the end of one year?

CHAPTER 20 The Random Class

Programs frequently need random numbers. A card game uses random numbers to create a shuffled deck of cards. A dice game uses random numbers to simulate a throw. Many activities in the real world (such as traffic on a highway system) appear to be random, and a program that models them must use random numbers. This chapter discusses the Random class that comes with Java. Random numbers, probability, and statistics are important for testing, for modeling the world, and for general understanding of the universe. Computer science degree programs usually require a course in these subjects. The chapter discusses:

Random numbers Random number generators Uniform and non-uniform distributions The Random class Seeds for Random() Tossing dice Picking passwords

QUESTION 1:
What number is most likely outcome for a throw of a fair die?

CHAPTER 21 Files and File Output


Files are extremely useful because often the data for a program comes from a file and often the results are stored in a file. You already know about files. You have been creating and using files in following these notes (and probably in your other work, as well). This chapter discusses how to send the output of a program to a file. The next chapter discusses how to read data from a file. For a full discussion of file I/O you will have to wait until much later in these notes. Chapter Topics:

Idea of a file Text files Redirecting output to a text file

QUESTION 1:
What is a file? (Try to think of a one sentence definition.)

CHAPTER 22 Reading Data from a File


Chapter Topics:

Input file redirection Problems with blank lines Redirecting both input and output Numeric input from a text file Problems with illegal characters in a number The trim() method

The previous chapter discussed text files and writing to text files. This chapter discusses reading from text files.

QUESTION 1:
Where has the data for our previous programs come from?
Created: 03/19/2006

CHAPTER 23 File I/O with Scanner and

PrintStream
This chapter discusses how to use the

Scanner class for input from files and how to

use the PrintStream class for output to files. This chapter is optional. Except for chapter 24, disk I/O is not much used again until it is taken up in more detail in chapter 80. However, most interesting programs do some disk I/O, and reading this chapter may enable you to write some of them. Chapter Topics:

Using Scanner with disk files. I/O Exceptions hasNext Methods of Scanner Class PrintStream print() and println() Methods of PrintStream

QUESTION 1:
In our past programs, what input stream has been used with

Scanner ?

CHAPTER 24 File Input Techniques


Most programs read their data from one or more files and write their results to one or more files. Usually interaction with the user is done only to specify details of the processing, such as the names of the files. This chapter discusses some useful techniques for processing data from an input file. Chapter Topics:

Three types of input loops Counting input loops

Several groups of data in one file Sentinel controlled input loops

The programs in this chapter read and write disk files using

Scanner and

PrintStream as described in Chapter 23.

QUESTION 1:
(Not again!) What are the three types of loops?
created 07/10/2006, revised 04/17/2010

CHAPTER 24B Formatted Output


This chapter discusses how to control the apperance of a number when it is converted into characters. This is usually done when a number is output to the monitor or to a file. For example, instead of
value = 13.333333333333334

you can ask for only two places right of the decimal point:
value = 13.34

This chapter is optional. Future chapters do not depend on it, so you can safely skip it. However, your programs will produce better looking output if you use number formatting. Chapter Topics:

Default Locale Formatting numeric output DecimalFormat Changing the Locale Format patterns o 0 format character o . format character o , format character o # format character Formats for positive and negative numbers

There is much more to formatting numbers than this chapter discusses. Sometime in the future you may wish to study the detailed documentation available on line. Depending on their location and language, people use different formats for numbers, dates, times, and currency. How to customize a program for the location and language where it will be used is called internationalization. This chapter only briefly discusses this.

QUESTION 1:
How would you prefer to see this number displayed:
123456789

CHAPTER 25 Objects
Chapter Topics:

What is an Object? What is a Class? Characteristics of Objects Static Methods Constructors Cookie Cutters Dot Notation

Until now, we have not been doing much with objects. This chapter discusses objects and classes. Forget programming for a while. Think about the Real World and the things that are in it. What things are objects? What things are not objects? This is actually a difficult problem which has occupied philosophers for thousands of years. Don't be too worried if it is not immediately clear to you.

QUESTION 1:
Look around you. List four objects and list four non-objects.

Objects

Non-objects

10/09/98, 09/01/99, 01/20/00, 07/14/02, 03/01/04, 01/17/06, 05/29/08

CHAPTER 26 Object References


This chapter discusses two things: object reference variables and the objects they refer to. These are crucial concepts in programming, and can be confusing. It demands careful study. This chapter was written as my best effort to answer the questions of confused students. Chapter Topics:

Primitive data types, and objects Object references and object reference variables Copying object references The == operator and object references The equals() method for strings String literals

You might wish to study this carefully, as a pre-emptive strike against confusion.

QUESTION 1:

(Review:) In Java, a piece of data either is of a _________________ data type or is an ________________ data type.

CHAPTER 27 Using Objects and Classes


This chapter reinforces the topics introduced in the last two chapters, and discusses several new topics. The Point class class is used as an example. Chapter Topics:

The Point class Class descriptions The toString() method Changing the data in an object vs constructing a new object The equals() method The == operator (again) Aliases

You have seen some of the material in this chapter before. But, don't rush through it. The purpose of this chapter is to review topics that you may still be somewhat unclear about.

QUESTION 1:
In geometry, what is a two dimensional point

You might also like