Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 2
An Intro to Java and
Your First Program
What is Java?
Advantages of Java
Four Steps for Creating and Running a Java Program
Framework of a Simple Java Program
What is a Java class?
Three Types of Java Output Programs
The Methods print and prinln
Syntax and Compile-Time Errors
What is Java?
A simple,
object-oriented,
network-savvy,
interpreted,
robust,
secure,
architecture neutral,
portable,
high-performance,
multithreaded,
dynamic language.
What is Java?
•
•
•
•
•
Java is Object-Oriented. It is the world’s fastest growing
programming language for building software components that
can be maintained and re-used.
Java is network-savvy. It has extensive library routines for
coping easily with TCP/IP protocols like HTTP and FTP so it
runs more efficiently over a network than other languages.
Java is interpreted. Java bytecodes are translated on the fly
to native machine instructions (interpreted) and not stored
anywhere.
Java is robust. That means that Java puts a lot of emphasis
on checking for possible problems and trying to eliminate
situations that are error prone. This helps programs run
efficiently and smoothly.
Java is secure. It provides for the creation of virtually virusfree systems that are hard to break into.
What is Java?
•
•
•
•
•
•
Java is architecture neutral. Java was designed to support
applications on networks not a particular computer platform. So it
doesn’t matter what your platform is.
Java is portable. Programs can be run on different types of
computers without having to change any of the code in a program.
Java is high-performance. The performance of bytecodes
converted to machine code is almost indistinguishable from native
C or C++.
Java supports threads. Instead of performing only one operation at
a time and not starting another operation until one is completed,
Java can run numerous operations at the same time if each
operation is a thread.
Java is dynamic. Java avoids the problems other languages have
and makes use of the object-oriented paradigm in a much more
straightforward manner. Libraries can freely add new methods and
instance variables without any effect on their clients.
To learn more about Java’s Features in detail
Click here
The Three Steps for
Creating & Running a
Java Program
Three Steps for Creating & Running a Program
1. Edit (write) the source code in a .java file
2. Compile the source code into byte code for a .class file
3. JVM interprets the byte code into machine language 1s
and 0s and the computer then executes the instructions
Source Code is Written in a .java File
Step1. When a programmer writes Java code, it is
stored in a source code file that has a .java
extension like RobotMan.java.
The source code file is what the programmer compiles
and runs to see the output of a program.
Source code can be typed in any simple text editor, but
we will use Eclipse, which is both a text editor and a
compiler. A compiler lets you run the program.
Eclipse is a nice Java editor and compiler because it
will point out syntax errors when java code is typed
incorrectly. A program will not run until all syntax
errors are removed.
Source Code is Compiled to Byte Code
Step 2. An IDE (Integrated Development Environment) like
Eclipse, has a built in compiler that translates the Java
source code into Java byte code.
When source code is compiled into byte code, the byte
code is stored in a file that has the same name as the
source code file but with a .class extension. It is not a
text file and you cannot open it! For example, the
source code file RobotMan.java will be compiled into a
byte code file named RobotMan.class.
The file is created during the compiling process, however,
Eclipse sometimes translates .java files into .class files
behind the scenes before you ever compile them. You
can see these files in your package folders if you open
your workspace folder on your hard drive.
Byte Code is Interpreted to Machine Code
Step 3. Before a program can be displayed, the JVM (Java
Virtual Machine) must interpret the byte code into machine
language. The JVM is software that acts like hardware. That
is why it is called a virtual machine. Java bytecodes are
translated on the fly to 1s and 0s instead of being stored in an
executable file, which some languages do. The main
advantage of Java is that there are JVMs for every kind of
computer and this makes the code portable from one platform
to another. (You’ll understand this more as we go.)
Interpreting can be slow, but software improvements are always
being made to speed up this process.
Every kind of computer, whether it is an Apple, Windows, or
Unix machine, has an operating system that contains a JVM
software component. The JVM was automatically installed
when your computer’s system software was installed and
updates to the JVM may be contained in any system software
updates you install now or in the future.
Just-in-Time Compilation by the JVM
Some JVMs support just-in-time compilation (JIT).
JITs will translate byte code instructions the first
time they are encountered into machine language
code and that code is saved so that the next time
that code is encountered it can be executed
without being re-interpreted. This can speed up
the interpreting of the byte code of a program so it
will run faster.
Machine Language Code is Executed
Step 4. Finally, the machine language code (1s and 0s), those
instructions that the computer understands at the lowest
level, are executed. This allows the program to appear in its
runnable form, either in a console window, an applet window,
or a GUI (Graphical User Interface) window. Again the overall
process is ….
Framework of a Simple Java Program
1.
2.
3.
4.
package declaration
import statements
class declaration line
main method
Framework of a Simple Java Program
The Framework of a simple console or standalone program:
1.
package declaration for the file
2.
import statements (if any)
3.
class declaration line
4.
main method
package unit1;
import java.util.Scanner;
public class DistanceCalculator
{ // opening curly brace for the DistanceCalculator class
public static void main(String args[ ])
{ // opening curly brace for main method
// code for program goes inside these curly braces
} // ending curly brace for main method
Note: curly braces
always appear in
pairs.
} // ending curly brace for the DistanceCalculator class
All Java console and JFrame (standalone) programs have this framework. The
framework for applets is different and you will become familiar with it later.
Classes in Java
Most of the time, every .java source code file contains 1 class.
It is possible to have more than one class in a .java file, but this is
usually only done in advanced programming projects where the
code is more complicated and there is a reason for doing it. So
don’t worry about that for now.
So assume that every .java file contains only one class.
However, any Java program can contain more than one class file. In
fact, it can contain many class files.
A class is a module of code that can stand alone by itself and if made
“public” other files can “see it” and “access it”. Eclipse is a nice
IDE for organizing Java files so that classes are accessible to
each other if they are in the same package folder or if an
appropriate import statement is used. Eclipse manages this
behind the scenes automatically and lets you know if something is
“unorganized” so you can fix it.
Declaring Classes in a File
A class is declared with a line like:
public class RobotMan
and has a set of curly braces that go with it { and }.
In Java, a class like RobotMan must be stored in a file
named RobotMan.java. If they don’t match, then
Eclipse or any other IDE will flag it with an error and it
must be corrected before the file is used in a program.
Eclipse has short cuts to renaming the file (compilation
unit). You’ll learn about that soon.
Java programs can be designed so that they contain just
one class. We will now look at some examples.
Three Types of
Java Output Programs
Three Types of Java Output Programs
There are basically three types of Java output programs that
a programmer can make:
1.
A console text output program.
2.
A standalone graphics or GUI program that can be
displayed in a normal window frame.
3.
An applet graphics or GUI program that can be displayed
in a browser window.
Console Text Output Programs
Some Java programs, like RobotMan, are displayed only in a console
window, because they show only text output. You will learn how to do
more than draw things with text characters in a console window. Some
programs may make mathematical calculations and display them.
When there is only one file in
a Java Program, we
sometimes refer to that file as
a “Driver file”, because it is
the file that makes the
program run. If a program
has more than one file, then
one of the files is a driver file.
Graphics & GUI Programs
Besides console text programs, you can have applet or
standalone programs that contain graphics or GUI
components:
1. GUI components are elements in a program like text
fields, buttons, labels, text areas, or menus.
2. Graphics are lines, and curves, and pretty much anything
that can be drawn.
So you can have:
1. An applet program with GUI components.
2. An applet program with graphics.
3. A standalone program with GUI components.
4. A standalone program with graphics.
5. An applet or standalone program that has both GUI
components and graphics.
Applet GUI Output Programs
Java applets are Java programs that run in a Web browser. A JVM is
incorporated into every browser, so the program can be interpreted,
executed and displayed inside the browser. Any game you have played
online is more than likely a Java applet program. Both applet and
standalone programs can have GUI components as seen here.
A GUI program with fields, buttons, labels, and a text area.
Because Java programs run
inside a Virtual Machine, it is
possible to limit their
capabilities. What this
means is that some other
programmer can’t inject a
virus into the code you have
written for an applet
program. Therefore,
everybody doesn’t have to
worry about a Java applet
infecting their computers
with a virus that will erase
files on their hard drive or
steal sensitive information.
Applet or Standalone Graphics Output Programs
Applet Graphics program can contain lines, arcs, ovals, rounded-rectangles,
etc. GUI or graphics programs pretty much look the same whether they
are in an applet or standalone program.
Source Code
The code a programmer writes!
A Program has Source Code
•
A program is a sequence of instructions that
perform a task.
•
Source code: The code written by a programmer
in a programming language and stored in a text
file with a .java extension. Each line of code is
an instruction written by the programmer that tells
the computer what to do. Java programs may
have more than one file, but one of the files is
always a “Driver File” that is the one that you run
to get the program running.
Java Is Hot Source Code
Mr. Conrey changed the class name of this file to JavaIsHot, even though the authors
originally called it HelloWorld. In this case, the name of the class doesn’t matter.
Method Calls with Parameters
In the line of code:
System.out.println(“Hello World!”);
•
System is a class and out is an object of that
class that knows how to display or print characters
in a console or terminal window.
–
–
println is the message (operation) being sent to the
System.out object. It is the name of a method.
(Another way to say it is we are “calling the method
println”.)
The item inside the parentheses is the parameter.
Here the parameter is a string (string of characters that
make up the words “Hello World”) that appear in
quotation marks and contains characters to be printed
to the screen. However, the parameter could be a
variable instead of a string. More on that later.
General Rule of Method Calls
A message may require zero, one, or multiple
parameters:
•
•
•
•
System.out.println(); // calling println with no parameters
System.out.println(“Hello World!”); // one parameter
calculateArea(length, width);
// calling some method
named calculateArea with two parameters length and width
The general form for sending messages to objects:
•
<name of object> . <name of message> (<parameters>)
OR
<name of object> . <name of method> (<parameters>)
The Method Selector is the Period
•
•
•
•
The Method selector operator is the period . and is
always placed between the object’s name and the method’s
name
System.out.println(“Hello World!”);
num2 = reader.nextInt();
num4 = reader.nextDouble();
In the last two examples, reader is the variable that represents
the object and nextInt and nextDouble are the names of the
messages or methods. The variable reader is also referred
to specifically as an object variable much of the time.
Semicolons End Most Java Statements
•
A Semicolon (;) marks the end of most Java
statements. A statement is a “sentence” in a
program. Examples:
–
–
–
System.out.println(“Hello World!”);
num1 = reader.nextInt();
sum = num1 + num2;
Some Java lines do not end in a semicolon. You will
learn which ones don’t as you are introduced to
other coding structures.
print and println Statements
This section discusses the use of print and println
(pronounced print-line) statements.
print and println are two operations (or as we say in
Java) … methods that can be called. These
operations output text information to the console
window in Eclipse.
We call methods when we want to accomplish some
operation or task.
print and println Statements
Here are lines of code that call the two methods
print and println:
1. System.out.print(“Hello World”);
2. System.out.println(“Hello World”);
Think of methods as operations, but we always
refer to them as methods in Java. Some other
languages refer to them as functions or
procedures.
When we say we are “calling a method”, what we
mean is that we are executing an operation!
print and println Statements
You may be wondering what the difference between the two
methods print and println are. print will display everything
on one line but not start a new line of output for anything
else that is printed. println will display everything on one
line and then start a new line of output for any other print or
println statement. Here is an example:
System.out.print(“Hello World! ”);
System.out.print(“How are you doing? ”);
System.out.print(“I am doing fine.”);
(Note the extra spaces at the end of the first two print statements
or the sentences would jam up together in output)
The output in the console window is all on one line:
Hello World! How are you doing? I am doing fine.
print and println Statements
Again … print will display everything on one line but not start
a new line of output. println will display everything on one
line and then start a new line of output.
Consider these three lines of code:
System.out. print(“Hello World! ”);
System.out. println(“How are you doing?”);
System.out. println(“I am doing fine.”);
The output is on two lines in the console window:
Hello World! How are you doing?
I am doing fine.
print Statements and Syntax Errors
So when we use the line of code:
System.out.print(“Hello World”);
We are calling the print method. Printing to a console window
requires that we place System.out. prior to the word print.
Please notice the periods “.” (method selector operators) that
separate the words System, out, and print.
Also, notice that the first S of System is capitalized (upper
case). The reason is System is the name of a class.
Also, notice that after the word print there are parentheses that
include in double quotes the information that we want to
display to the screen and the entire line of code ends in a
semicolon.
All of this is required and must be typed correctly or you will
get a syntax error. Programs with syntax errors won’t run!
Compile-Time Errors
Syntax errors are also called compile-time errors. These errors
keep a program from compiling and running until the errors
are corrected. Examples are:
• misspelling key Java words like print, println, System, public,
and class or leaving out curly braces where they are needed.
(This kind of error is a syntax error.)
• forgetting to place a semicolon after Java lines that need it
• not storing the class in a file with the same name. (These last
two kinds of errors are not syntax errors, but just compile-time
errors.)
A compiler like Eclipse displays errors in the console window
and …
•
•
indicates the type of error detected
indicates the file and line number where the error was detected
How Eclipse Points Out Errors
•
Eclipse will …
1.
2.
3.
•
describe the error in the source code window
tell the line of code where the error is
suggest a solution to the error when you mouse over the bad code.
Eclipse displays a red circle with an X in it to the left of any line that
has a syntax error.
•
Eclipse will display a red box with an X in it for any line that has a
compile-time error.
•
You can …
–
–
mouse over the red circle or red box and a message will pop-up
that describes the error.
click on the red circle or red box and then choose an option of
how to correct it. This saves time if you choose the correct fix,
then the error will be corrected automatically for you.
The Readability of Code
It is important for your code to be readable by others. In the real world,
programmers are on software teams as they develop and maintain
software. So all code must be readable! Programmers have
developed a standard for how code should be indented.
•
The main factors that determine whether code is readable or not are
– Spacing (referring to extra blank lines that space things out)
– Indentation (referring to tabs or indentions on a specific line)
•
Spacing and Indentation are just for programmer readability. The
compiler ignores any kind of spacing and indentation. It just checks to
make sure that everything is syntactically correct (spelled correctly)!
•
Eclipse assists you with indenting segments of code as you type by
automatically properly indenting your next line depending on the kind of
Java code you are writing. But if you mess up the indenting then all
you have to do is select all code by typing Control “a” on a PC or Apple
“a” on a Mac, then type either Control “i” on a PC or Apple “i” on a Mac.
Chapter 2 Section 6
In this section, you will learn some very
important information about:
1.
2.
3.
4.
5.
6.
Simple data types
Numeric variables
String variables
The assignment operator =
How to declare and construct a Scanner
object so you can read input from the
keyboard
The new operator
Simple Java Data Types
In Java, we have different kinds of data types. Here you will learn
three of them. We can store each of the three types of data
values in different kinds of variables.
We can have …
1.
variables that can hold integers (type int)
2.
variables that can hold real numbers or what we refer to also as
floating-point numbers (type double)
3.
variables that refer to an object that can hold a string of
characters, in other words, a bunch of characters that make up a
word (type String)
The data types int and double are simple numeric data types and we
store those kind of values in simple variables that are not
considered object variables.
However, Strings are objects and a String value must be stored in an
object variable. Let’s look at how we do that with the assignment
operator.
The Assignment Operator
The assignment operator is the = character.
We use the assignment operator when we want to store a value
in a variable.
Here is how to declare the different kinds of variables and store
values in them:
int x = 129;
// x is the int variable and 129 is being stored.
double y = 3.14159; // y is the double variable and π is stored.
String name = “Java”; /* name is the String variable and the
word “Java” is being stored. (Notice the double quotes
around Java since we are storing a String) Don’t place
double quotes when you store numbers. */
Declaring and Using Scanner Objects
We also use the assignment operator when creating objects
(constructing objects) so an object variable can refer to them.
If we want to receive input from the keyboard during a program,
then we need to construct a Scanner object first. This allows
the user to enter numbers or string values into a program.
To do this we need to import Java’s Scanner class with the line:
import java.util.Scanner;
Next, inside the main method, we need to construct the Scanner
object with the line:
Scanner reader = new Scanner(System.in);
We need to use System.in as the parameter because this
indicates the keyboard, which is the default input device for
Java. Note: Scanner is a class so the S is capitalized.
Explanation of Constructing a Scanner Object
In the line of code :
Scanner reader = new Scanner(System.in);
the name of the class Scanner is used twice.
The first part of the line:
Scanner reader
declares reader to be an object variable of type Scanner. We need
to do this or reader can’t refer to the Scanner object we construct.
The second part of the line:
new Scanner(System.in);
constructs the Scanner object and “attaches it” to the keyboard. The
word new is the new operator that we use to construct things. The
assignment operator makes reader refer to the Scanner object.
General Form for Constructing Objects
•
•
In programming, the process of constructing an object is
called instantiation.
In general, constructing or instantiating and object takes the
general form:
SomeClass someVariable = new SomeClass(some parameters);
You can see that the line of code below follows this form:
Scanner reader = new Scanner (System.in);
You can think of reader as something that is “scanning the
keyboard waiting for input”.
Reading Input from the Keyboard
Assume the following lines of code appear in the main method of a program.
Scanner reader = new Scanner (System.in);
System.out.print(“Enter your name and press return: ”); Note: the print
String name = reader.nextLine();
System.out.print(“Enter your age and press return: ”);
int age = reader.nextInt();
System.out.print(“Enter your gpa and press return: ”);
double gpa = reader.nextDouble();
statements
“prompt” the
user to enter
data, otherwise
he or she
wouldn’t know
the computer is
waiting for
input!
Notice we can receive different kinds of input using reader. We use
the object variable reader to “call the method nextLine() to receive a
String value from the keyboard. We use reader to “call the method
nextInt() to receive an integer and we use reader to “call the method
nextDouble() to receive a floating-point value from the keyboard.
Reading Input from the Keyboard
We can now “echo the input” (print the information back to the
screen) by using some println statements. In each line, we will
print a literal string (something in double quotes) and the value
contained a the variable. We use a plus sign to concatenate the
literal string value and the value stored in the variable together to
make a larger string that is then printed.
System.out.println(“Your name is: ” + name);
System.out.println(“Your age is: ” + age);
System.out.println(“Your gpa is: ” + gpa);
Notice that there are no double quotes around the variables name,
age, and gpa.
Now you know enough that you can understand the Convert.java program!
The Convert.java Program
Note the key Scanner lines identified by the red arrows.
More about Import Statements
In the Convert.java code you saw that the first line of code was
an import statement: import java.util.Scanner;
This tells the compiler where to find a class that will be used
during the program. The class may be either in a Java
library file or another file you have in a folder. The import
statement contains the path name of where to find the class.
The Scanner class is found in a sub-package folder named util
that is in the java package folder. so we import it using:
(Sometimes the first line of code is a package statement,
depending on how you have Eclipse organized. More on
that later.)
More about Numeric Variables
A numeric variable names a location in RAM memory where a
number can be stored.
When we use the line of code:
double celsius;
then enough RAM memory is allocated so that a floating-point value
can be stored. Java does this automatically for you!
Important points to remember about variables:
•
A variable’s value may change during a program, but its name
remains constant.
•
A variable’s type defines what kind of values can be stored in RAM.
The type of the variable cannot be changed while a program is
running. Remember when we say type we are referring to int,
double, String, or other data types.
Java’s Mathematical Operators
Java basically has 5 mathematical operators.
Addition is represented by the + sign.
Subtraction is represented by the - sign.
Multiplication is represented by the * sign.
Division is represented by the / sign.
Mod is represented by the % sign. Mod gives the remainder of
int division.
In the Convert.java program, the line of code:
celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0;
use three of the above mathematical operators.
Review of Simple and Object Variables
In the Convert.java program, simple variables like fahrenheit
and celsius each hold a single floating-point number.
Object variables like reader and System.out hold references
to objects.
Object variables are used to send messages to objects.
reader.nextDouble() sends the message “get me the next
floating point number” from the keyboard.
Visualizing Simple and Object Variables
simple variables
object variables
object variables
can send
messages to
objects
Chapter 2 Section 7: Graphics and GUIs
•
Graphics and GUI programs in Java can run either
as a stand-alone application or as an applet.
•
We will study how to use applets in upcoming
chapters.
•
Standalone GUI applications run in windows.
•
A window is a container for graphical components
to be displayed to the user.
JFrame Windows
Windows have numerous properties.
• Width and height
• Title bar
• Ability to be dragged or resized by the user
The code for application windows is located in the class
JFrame, which is imported from the package
javax.swing. To use this class you need to import it with
the statement:
import javax.swing.JFrame;
or
import javax.swing.*;
The last import statement imports all the classes in the
swing package not just JFrame.
GUIWindow1.java Code
This code is from Example 2-3 in the text and all
it does is produce an empty window frame. I will
send it to you as GUIWindow1.java
GUIWindow1.java Output
Figure 2-12 from the text: GUI program with an empty window
An application window is really just an empty container that we
can fill with other objects. One object we can place in the
window is a panel.
Listing of JFrame Methods
This is Table 2-1 from the text that lists some commonly used
JFrame methods. Note: The method setDefaultCloseIndicator(int i)
above should be setDefaultCloseOperation().
Panels and Colors
A panel is a flat, rectangular area suitable for displaying other objects.
It may contain geometric shapes and images.
To use a panel you must import the JPanel class with:
import javax.swing.JPanel;
You can use Java’s default colors or create your own RGB colors by
importing the Color class with:
import java.awt.Color;
To change the current drawing and painting color to red, use the paint
brush g to call the setColor() method as follows:
g.setColor(Color.red);
Note the dot “.” between g and setColor and in parenthesis since red
is a color constant of the Color class we must use Color with a
capital C dot red.
Java’s Default Color Constants
If you were going to construct these colors by yourself, you
would use the 3 integer values in the parenthesis.
Customized Colors
You can construct a customized color if the color you need is not
one of the Color constants seen on the previous slide.
You can construct a new Color object by using three int values
between 0 and 255 with:
Color aColor = new Color(redValue, greenValue, blueValue);
In this code, redValue, greenValue, blueValue must be integer values.
You would then use the code:
g.setColor(aColor);
(don’t use Color.aColor)
Here is an actual example:
Color brown = new Color(164, 84, 30);
g.setColor(brown );
(don’t use Color.brown)
GUIWindow2.java Code
This code is from Example 2-4 in the text and it produces an
empty, pink panel. I will send it to you as GUIWindow2.java
Layout Managers and Multiple Panels
Every container object (frame or panel) uses a layout manager
object to organize and lay out the graphical components
contained in it.
The default layout manager for frames is an object of the class
BorderLayout.
You can arrange up to five graphical objects in a container in
the following positions:
NORTH, SOUTH, EAST, WEST, and CENTER
If we add fewer than 5 objects to a BorderLayout, the layout
manager stretches some of them to fill the unoccupied areas.
An object of the GridLayout class divides a container into
rows and columns.
BorderLayout with GUIWindow3.java
If you look at the code in GUIWindow3.java you can
see how to set up a BorderLayout GUI Window. The
code is too lengthy to show here.
GUIWindow4.java Code
This is
Example 2-6
in the text that
produces a
Frame with a
grid containing
2 rows and 2
columns of
colored
panels. See
next slide.
GUIWindow4.java Output
Figure 2-14 from the text showing the 2-by-2 grid
layout with four panels of different colors.