+ All Categories
Home > Documents > Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running...

Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running...

Date post: 11-Jan-2016
Category:
Upload: neil-newman
View: 223 times
Download: 2 times
Share this document with a friend
Popular Tags:
69
Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java Program Sect 3 - Three Types of Java Programs Sect 4 - Data Types and Basic Input and Output Sect 5 - Calling Methods Sect 6 - Syntax and Compile-Time Errors Sect 7 - Graphics and GUI Programs Go Go Go Go Go Go Go
Transcript
Page 1: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Chapter 2

Primitve Data Types, Input, Output,

and Assignment

Sect 1 - Steps for Creating and Running a Java Program

Sect 2 - Framework of a Simple Java Program

Sect 3 - Three Types of Java Programs

Sect 4 - Data Types and Basic Input and Output

Sect 5 - Calling Methods

Sect 6 - Syntax and Compile-Time Errors

Sect 7 - Graphics and GUI Programs

Go

Go

Go

Go

Go

Go

Go

Page 2: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 1

The Steps for Creating & Running a Java Program

A program is a sequence of instructions that perform a task.

2

Page 3: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Fastest Growing Programming Language

Here are some reasons that Java is the fastest growing programming language:

• It is a modern object-oriented language.

• It is secure. Viruses can’t be spread with Java programs.

• It is robust. This means that Java programs can respond efficiently to a variety of situations while a program is running if the correct precautions are taken when writing the code.

• It supports threads. This means two or more parts (threads) of a Java program can be running at the same time.

• It supports the development of programs that do not overwrite memory. In other words, if one program takes up a portion of RAM memory while it is running and a second program is started. The second program cannot be loaded into the memory taken up by the first program if there is not enough RAM memory.

3

Page 4: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Steps for Creating & Running a Program

1. Write the source code in a .java file

2. Compile the source code into byte code creating a .class file

3. JVM interprets the byte code into machine language 1s and 0s and the computer then executes the instructions

4

Page 5: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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. We will write our Java progams in the IDE

software called Eclipse. IDE stands for Integrated Development

Environment. An IDE lets you write, compile, and execute

programs.

Source code can be typed in any simple text editor, but we will use

Eclipse, which is both a text editor and a compiler.

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.

5

Page 6: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Source Code is Compiled to Byte CodeStep 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. 6

Page 7: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Byte Code is Interpreted to Machine CodeStep 3. The JVM (Java Virtual Machine) must interpret the byte code

into machine language. Interpret basically means to translate. 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 an interpreter is that it will run on any computer and there are JVMs for Apple and Windows machines. This makes the code portable from one platform to another.

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.

7

Page 8: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

What are Applets?

Applets are small Java programs that are embedded in web pages.

When you load a web page that has a game in it, the game is an

applet.

More specifically, the applet is usually a jar file that contains the byte

code for all the .java files that are needed for the game. A jar file is

like a zip file, where a number of files are compressed into one file.

An HTML web page can contain a special kind of tag called an Applet

tag. That tag tells the web page that the byte code is stored in a jar

file with a specific name.

The browser software, like FireFox, Chrome, Camino, or Safari will

then use its built-in JVM interpreter to translate the byte code into

machine language 1s and 0s.

8

Page 9: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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.

9

Page 10: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Machine Language Code is ExecutedStep 4. Finally, the machine language code (patterns of 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 ….

10

Page 11: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 2

Framework of a Simple Java Program

1. package declaration

2. import statements

3. class declaration line

4. main method

11

Page 12: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Framework of a Simple Java ProgramThe Framework (in order) of a simple console or standalone program:1. package declaration for the file listed first (where it is stored)2. followed by import statements (if any)3. class declaration line4. main method

package ch03;

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

} // 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.

Note: curly braces always appear in pairs.

Sample Skeleton Program

12

Page 13: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Classes in JavaA Java program can use more than one class file (a .java file). In fact, it may

be made up of many .java files.

And most of the time, every .java source code file in a Java program contains only one class.

However, it is possible to have more than one class in a .java file, but this is usually done in more advanced programming projects where the code is more complicated and there is a reason for doing it.

So assume that every .java file contains only one class, but a java program can use one or more .java 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 parts of 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 to direct Eclipse to where a package is located. Eclipse manages this behind the scenes automatically and lets you know if something is “unorganized”, so you can fix it.

13

Page 14: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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) or the class if necessary. You’ll learn about that

soon.

Simple Java programs can be designed so that they contain just one

class. We will now look at some examples.

14

Page 15: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 3

Three Types ofJava Programs

15

Page 16: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Three Types of Java Programs

There are basically three types of Java 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 standard window frame.

3. An applet graphics or GUI program that is embedded in a

web page.

16

Page 17: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Console Text Output ProgramsSome 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. The driver file’s job is always to initiate the program to begin the compiling and running process.

17

Page 18: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Graphics & GUI ProgramsBesides 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. A web applet program with GUI components.

2. A web applet program with graphics.

3. A standalone program with GUI components.

4. A standalone program with graphics.

5. A web applet or standalone program that has both GUI components and graphics. 18

Page 19: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Applet GUI Output ProgramsJava applets are small Java programs downloaded from web pages that run

in a Web browser. A JVM is incorporated into every browser, so the applet can be interpreted, executed and displayed inside the browser. Any game you have played online is more than likely a Java applet. Both applet and standalone programs can have GUI components.

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.

A GUI program with fields, buttons, labels, and a text area. 19

Page 20: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Applet or Standalone Graphics Output ProgramsGraphics program can contain lines, arcs, ovals, rounded-rectangles, etc. and

they can be animated. GUI or graphics programs pretty much look the same whether they are in an applet or standalone program.

20

Page 21: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 4

Data Types and the Basics

of Input and OutputIn this section, you will learn some very important information

about:

1. print and println Statements

2. Variables

3. Simple data types

4. The assignment operator =

5. How to declare and construct a Scanner object so you can read input from the keyboard

6. The new operator

21

Page 22: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Java Is Hot Source Codepackage ch01;public class JavaIsHot{

public static void main(String args[ ]){

System.out.println( " d ");System.out.println( " o l ");System.out.println( " l r ");System.out.println( " l o ");System.out.println( " e w ");System.out.println( " H ");System.out.println( " xxxxxxxxxxxxxxxxx ");System.out.println( " x x x ");System.out.println( " x Java x x ");System.out.println( " x xxxx ");System.out.println( " x is Hot! x ");System.out.println( " x x ");System.out.println( " xxxxxxxxxxxxxx ");

} // end of main method} // end of JavaIsHot class

System.out.println statements are used to print text to the console output window. 22

Page 23: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

print and println Statements

Output to a console text window in Java is accomplished through 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.

23

Page 24: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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!

24

Page 25: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

print and println StatementsYou 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 for anything else that will be printed by the next

print or println statement. println will display everything on one line

and then start a new line of output for the output of 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.25

Page 26: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

print and println StatementsAgain … 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.

26

Page 27: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

print Statements and Syntax ErrorsSo 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!27

Page 28: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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.

28

Page 29: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Using Variables to Store ValuesA variable names a memory address (location) in RAM memory where

a value can be stored.

The variable is considered to be a nickname for the memory address.

The memory address of a variable may be some unusual combination

of 1s or 0s or a hexadecimal number, so its great that we can

decide on the name of variables. We do this when we declare

them.

We can think of a variable as a small box that holds a value.

X Y name

an int variable a double variable a string variable 29

Page 30: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Simple Java Data TypesIn 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. int variables that can hold integers (type int)

2. double variables that can hold real numbers or what we refer to also as

floating-point numbers (type double)

3. String 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.

30

Page 31: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

The Assignment OperatorThe assignment operator is the = character and you can initialize

variables to literal numeric or string values in one line of code.

So to store a value in a variable, we use the assignment operator.

Here is how to declare the different kinds of variables and store values in them or as we like to say initialize 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”;

In the last line of code, name is the String variable and the word “Java” is being stored. Notice the double quotes around Java since we are storing a literal String value Don’t place double quotes when you store numbers. 31

Page 32: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Visualizing Simple and Object Variables

simple variables

object variables

object variables, like String or Scanner variables, can send messages to objects, but simple variables can’t.

32

Page 33: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Numeric Variables

A numeric variable names a memory address (location) in RAM

memory where a number can be stored. It is considered to be a

nickname for the memory address. Numeric variables are of type int

or double.

When we use the line of code:

double celsius;

then enough RAM memory is allocated so that a floating-point value

can be stored in celsius. Java does this automatically for you! A

double variable gets twice as much memory as an int variable.

Thus, the data type was named double.

33

Page 34: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Important Facts About Variables

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, boolean, String, or other data types.

34

Page 35: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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. (You’ll be amazed at how much you will use mod)

In the Convert.java program, the line of code:

celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0;

uses three of the above mathematical operators.

You’ll see the code for the program in a few of slides. 35

Page 36: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Declaring and Using Scanner ObjectsWe 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; // goes above the class declaration line

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. 36

Page 37: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

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:

<Name of Class> <variable> = new <Name of Class> (<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”.

37

Page 38: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Constructing a Scanner Object with newIn 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.

38

Page 39: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

More About Reading Input from the KeyboardAssume 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: ”);

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();

Notice when we prompt the user, we use a print statement NOT a println

statement. 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.

Note: the print statements “prompt” the user to enter data, otherwise he or she wouldn’t know the computer is waiting for input!

39

Page 40: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Echoing the Input from the Keyboard

We can now “echo the input” (print the information back to the screen

that was entered) by using some println statements. In each line,

we will print a literal string (something in double quotes) and the

value contained in a 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.

40

Page 41: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Algorithm for Converting Temperatures

If we wanted to write the code for a program that would convert

Fahrenheit temperatures to Celsius, it would be good to stop and

develop an algorithm. An algorithm is a step by step procedure

for solving a problem. This helps our code to be more efficient

and we save a lot of time, because we consider all that needs to

be done … NOT just the mathematical formula needed to

convert the temperature.

Any suggestions?

41

Page 42: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Algorithm for Converting Temperatures

Consider this algorithm:

1. Prompt the user to enter a Fahrenheit temperature.

2. Read the value from the keyboard and store it in a variable.

3. Use the value stored in the variable in an assignment statement

that applies the correct mathematical formula in code form.

4. Store the value calculated in a second variable.

5. Output the converted value to the screen.

42

Page 43: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

The Convert.java Programpackage ch02;import java.util.Scanner;

public class Convert{

public static void main(String args[]){

Scanner reader = new Scanner(System.in);

double fahrenheit;double celsius;

// prompt the user to enter a value from the keyboard when the program runs.System.out.print("Enter degrees Fahrenheit and press return: ");

// read the value from the keybaord and store it in the variable fahrenheit.fahrenheit = reader.nextDouble();

// calculate the equivalent celsius value and store it in the variable celsiuscelsius = (fahrenheit - 32.0) * 5.0 / 9.0;

// print out the following string of characters to the terminal window.System.out.print("The equivalent in Celsius is ");

// print out the value stored in the variable celsius to the terminal window.System.out.println(celsius);

}}

Note the key Scanner lines identified by the red arrows. 43

Page 44: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

More about Import Statements

In the Convert.java code you saw that the first line after the package

declaration 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 import statement tells us that the Scanner class is found in a

sub-package folder named util that is in the java package folder.

Now you know enough that you can finish the second half of the

Convert.java program!

44

Page 45: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 5

Calling Methods

In this section, you will learn some very important information about:

1. Method Calls and Parameters

2. Concatenation

3. Readability of Code

45

Page 46: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Method Calls with ParametersConsider the following 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 name of the method (operation) being

executed. (Another way to say it is we are “sending the message println to the object represented by System.out”.)

– The item inside the parentheses “Hello World” is the parameter of what needs to be printed. Here the parameter is a string (string of characters) that make up the words “Hello World”. Notice they appear in quotation marks. This tells Java to print to the screen the literal string value “Hello World”. The parameter could be a variable that contains a value instead of a literal string value in double quotes.

46

Page 47: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

General Rule of Method CallsThe general form for calling methods is:

<name of object> . <name of method> (<parameters>)

A message may require zero, one, or multiple parameters. Here

are some examples:• To print a blank line, we can use System.out.println(); without

any parameters in the ( ). • To print “Hello World”, we need only one parameter the literal

string value “Hello World” in the parenthesis … System.out.println(“Hello World!”);

• To print “Hello World. Java Rules”, we still need only one parameter but the parameter may be the concatenation of two literal string values as in …System.out.println(“Hello World!” + “Java Rules!”); Notice that we

concatenate two literal strings together using a + symbol. • To call a method named calculateArea with two parameters

length and width, we use the code ...calculateArea(length, width);Notice the two parameters are separated by a comma. 47

Page 48: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

The Method Selector is the PeriodThe Method selector operator is the period . and is always placed between

the object’s name and the method’s name. It is also placed between the name of a class and the name of an object when needed as in System.out.

Scanner reader = new Scanner(System.in);

System.out.println(“Enter an integer: ”);

int num1 = reader.nextInt();

System.out.println(“Enter an integer: ”);

int num2 = reader.nextInt();

System.out.println(“Enter a floating-point number: ”);

double num3 = reader.nextDouble();

Above, reader has been declared to be a Scanner class variable that represents a new Scanner object. That Scanner object can read data from the input of the keyboard. Reader can call either of the methods nextInt() or nextDouble() to read integers or floating-point numbers from the keyboard. The variable reader is also referred to specifically as an object variable. 48

Page 49: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Declaring int and double VariablesTIME OUT!!! What are we doing with the lines?

int num1 = reader.nextInt();

double num3 = reader.nextDouble();

In the first line, we declare a variable named num1, but we have to tell what type of data we intend for it to hold. Since we want it to hold an integer (whole number), we use Java’s int data type. The type of data must be listed before the name of the variable!

The assignment operator = means we want to store something in num1. What we want to store is what is on the right side of the = sign. It could be an arithmetic expression or a reader line.

When a program runs and it encounters a line like reader.nextInt(), the program will pause and wait for something to be entered from the keyboard. Once the user enters an integer and presses return, then the number is read by reader’s nextInt() method, and then the value is stored in num1.

With the second line of code, we declare a variable num3 that can hold a floating-point number (one that contains a decimal point like 4.237). The method nextDouble() is used to read the value from the keyboard and store it in the double (floating-point) variable num3. 49

Page 50: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Concatenating Output ItemsConsider this segment of code:

System.out.println(“Enter an integer: ”);

int num1 = reader.nextInt(); // a whole number is stored in num1

System.out.println(“Enter an integer: ”);

int num2 = reader.nextInt(); // a whole number is stored in num2

int sum = num1 + num2; // a whole number is stored in sum

System.out.println(“The sum of ” + num1 + “ and ” + num2 + “

is ” + sum);

In the last output line, we concatenate 6 things together to be written to output. Three

of the items are literal strings and three are variables of type int that hold integers.

Notice there are NO double quotes around the variables. You never place double

quotes around any variable … only literal string values. Also, notice the blank

spaces at the beginning and end of some literal string values. This keeps the

numbers from being jammed up against the words.

50

Page 51: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Review of Simple and Object VariablesIn 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.

In summary, to write effective Java programs, a programmer does not

need to have detailed knowledge of the inner workings of any

object, he or she just needs to know how to construct objects and

how to send messages to the object by calling methods.

51

Page 52: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

The Readability of CodeIt 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 everyone must be able to read your code! Programmers have developed a standard for how code should be formatted.

• 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 Windows machine or Apple “a” on a Mac, then type either Control “i” for Windows or Apple “i” for a Mac and everything will get indented properly.

52

Page 53: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 6

Syntax and Compile-TimeErrors

53

Page 54: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Syntax ErrorsSyntax errors keep a program from compiling and running until the

errors are corrected. Examples are:

• forgetting to place a semicolon after Java lines that need it

• forgetting one of the two ( ) when calling a method like println.

• forgetting to place double quotes where they are needed.

• misspelling Java key words like print, println, System, public, and

class.

Syntax errors are a form of compile-time errors.

54

Page 55: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Compile-Time ErrorsSome errors are not syntax errors. They are just compile-time errors.

Here are some examples:

• not storing the class in a file with the same name.

• trying to store a data value of one type in a variable of another type.

• leaving out the opening or ending curly brace for a method.

If you try to run a program that has syntax or compile-time errors, a

compiler like Eclipse will halt the process and display error

messages in the console window that …

• indicates the type of error detected

• indicates the file and line number where the error was detected55

Page 56: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

How Eclipse Points Out Errors• Eclipse will …

1. describe the error in the source code window

2. tell the line of code where the error is

3. 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.

56

Page 57: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Computer HackingOriginally, a hacker was a programmer who exhibited

rare problem solving ability. This person was an

asset to any company. Especially, when there

were difficult problems to solve. In fact, a “hack”

refers to a programming solution to a difficult

problem that some might think is unsolvable.

Currently, hacker has a negative connotation, referring

to someone who breaks into computer systems or

circumvents a system that is intended to be used.

They may do this just to impress their peers or to

cause actual harm.

In addition, anyone who lacks a disciplined approach

to programming is many times called a hacker.57

Page 58: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Section 7

Graphics and GUI Programs

• 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.

58

Page 59: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

JApplet WindowsWindows have numerous properties.

• Width and height

• Ability to be dragged or resized by the user

• Ability to be painted or drawn on.

The code for applet windows is located in the class JApplet, which is

imported from the package javax.swing. To use this class you

need to import it with the statement:

import javax.swing.JApplet; or

import javax.swing.*;

The last import statement that uses the * imports all the classes in

the swing package not just JApplet.

59

Page 60: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

AppletWindow1.java CodeThis code produces an empty applet window.

public class AppletWindow1 extends JApplet{ // applet programs like to have this line of code, but the applet will still // run without it. However, it will show a warning. This warning is NOT an error! private static final long serialVersionUID = 1L;

// This method initializes the applet and loads it. It creates an applet // window that is 300 pixels wide and 200 pixels high. public void init () { resize(300, 200); }

// This method is needed to paint things in the applet window. However, // nothing is painted because we have no drawing or painting commands in it. // The line of code super.paint(g); serves to erase the applet window before // anything is painted. public void paint(Graphics g) { super.paint(g);

// missing painting and drawing code would go below.

}

} 60

Page 61: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

AppletWindow1.java Output

The output will look something like this.

An applet window is really just an empty container called a pane that we can fill with other objects. One object we can place in the window is a panel.

61

Page 62: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Panels and ColorsA 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 (an object) and setColor (a method) and in

parenthesis since red is a color constant of the Color class we must

use Color with a capital C dot red.62

Page 63: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

2.7 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. 63

Color Constant RGB Value Construction

Color.red new Color (255, 0, 0)

Color.green new Color (0, 255, 0)

Color.blue new Color (0, 0, 255)

Color.yellow new Color (255, 255, 0)

Color.cyan new Color (0, 255, 255)

Color.magenta new Color (255, 0, 255)

Color.orange new Color (255, 200, 0)

Color.pink new Color (255, 175, 175)

Color.black new Color (0, 0, 0)

Color.white new Color (255, 255, 255)

Color.gray new Color (128, 128, 128)

Color.lightGray new Color (192, 192, 192)

Color.darkGray new Color (64, 64, 64)

Page 64: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Customized ColorsYou 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 in

() )

Here is an actual example:

Color brown = new Color(164, 84, 30);g.setColor(brown ); (don’t use Color.brown in () )

64

Page 65: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

AppletWindow2.java Code// This code produces an empty, pink panel.// Note if you try to add a second panel to this JApplet, then you won't see them both unless you// specify what region of the default BorderLayout you are adding the panel to.

public class AppletWindow2 extends JApplet{ // other code …

public void init() { resize(300, 200);

JPanel panel = new JPanel();

// The following line of code sets the background color of the panel panel.setBackground(Color.pink);

Container pane = getContentPane();

pane.add(panel);

} // end of init method

// other code …

65

Page 66: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

AppletWindow2.java Code ModifiedNow let’s create a customized color to set the background to. Let’s say with a dark blue.

public class AppletWindow2 extends JApplet{ // other code …

public void init() { resize(300, 200);

JPanel panel = new JPanel();

Color myColor = new Color (51, 0, 153); // define the color midnight blue panel.setBackground(myColor);

Container pane = getContentPane();

pane.add(panel);

} // end of init method

// other code …

66

Page 67: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

Layout Managers and Multiple PanelsEvery 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 with equal size cells.

67

Page 68: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

BorderLayout on AppletWindow3.java Output

If you look at the code in AppletWindow3.java you can see how to set

up a BorderLayout Applet Window. The code is too lengthy to

show here. We will go over it in class. Here is the output of

AppletWindow3.java

north region

south region

east regionwest region

center region

68

Page 69: Chapter 2 Primitve Data Types, Input, Output, and Assignment Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java.

AppletWindow4.java Code and OutputThis code produces an applet window with a grid containing 2 rows and 2 columns of colored panels.

public class AppletWindow4{ public void init() { resize(300, 200);

JPanel panel1 = new JPanel(); panel1.setBackground(Color.white);

JPanel panel2 = new JPanel(); panel2.setBackground(Color.black);

JPanel panel3 = new JPanel(); panel3.setBackground(Color.gray);

JPanel panel4 = new JPanel(); panel4.setBackground(Color.white);

Container pane = getContentPane();

pane.setLayout(new GridLayout(2, 2)); // (rows, columns)

pane.add(panel1); pane.add(panel2); pane.add(panel3); pane.add(panel4);

} // end of init method

}69


Recommended