Download CSC 141 Introduction to Computers

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
2-1
Chapter 2 Java Fundamentals and Program Development Process
2.1 Program Development Process – Editing, Compiling, and Executing a Program
Q: What do we mean by editing a program?
A: When a program is coded using Java, we say that we finished coding. The next step is to enter the program
into a computer. The process of entering the program and modifying the content is called editing. There are
many editing programs (tools) that provide various capabilities for us to use. In this course, we will be using
jGRASP. You can download this Integrated Development Environment (IDE) tool from www.jgrasp.com. You
also need to download Java 2 Standard Edition (J2SE) release 5.0 (without netBeans) at http://java.sun.com/j2se
and click on the Download J2SE link on the right of the screen. You only need to download JDK 5.0 Update
without netBeans. After you install the version, change you PATH to add two folders c:\Progarm
Files\Java\j2se1.5.0_03\bin and c:\Program Files\Java\j2se1.5.0_03\jre\bin.
2.2 The Elements of Java Programs
-
-
We can almost say that program = data + methods(operations).
Hence a computer program must consist of language constructs(features) which describe data and
operations. In Java, the concept of object-oriented programming has been applied to write a program. The
concept of data + operations is realized by using a class. A class is a program entity for representing a
problem entity.
In Java, a program is also considered a class. This concept is explained later.
The rules and symbols that make up the Java programs are collectively called the syntax of a programming
language.
Syntax rules govern how valid instructions are written in a programming language.
The meaning of rules or symbols used in a programming language is called the semantics of these symbols
or instructions.
For Example:
mathematical expression: 3 + 2 = 5
Java program:
int a = 3;
int b = 2;
int c;
c = a + b;
To learn how to write a Java program, we need to learn the syntax and the semantics of Java. Also, we need to
learn how to develop algorithms. Using the analogy of playing chess, you need to learn more than just the
2-2
pieces and how they move. You need to learn some strategies. How to develop algorithm is probably the most
important part of this course in addition to syntax and semantics.
Let us take a look at the components in a program using a simple program.
import java.io.*;
public class TwoLines
{
public static void main(String[] args)
{
int a = 3;
int b = 2;
int c;
String a_string = “This is a testing”;
c= a + b;
System.out.print(“Programming is fun!\t”);
System.out.println(“I can’t get enough of it!” + “ “ + a_string);
System.out.println(“The sum of a and b = “ + c);
}
}
We will use this program as a sample program for getting familiar with the development environment at West
Chester. In other words, we will go to the Lab and enter this program into a computer, compile it, and execute it
later.
2.2.1 The import Statement
The import statement is needed whenever you use some input/output statements. You don’t need it for print or
println method. So you can add “//” in front of the import statement and “tell” the compiler that this line is a
comment line. We sometimes say that this line is commented out.
2.2.2 Output Statements: print vs. println
The print method prints out what the content inside of the parentheses, whereas the println method also moves
the cursor to the beginning of next line. The same effect can also be achieved by using a “\n”. A “\t” is
equivalent to pressing a tab key once. What will you see on the screen if the program is executed?
2-3
Syntax : System.out.print( expression );
Syetem.out.println ( expression );
Semantics:
- if the expression is a literal, the exact value will be displayed on the monitor.
- if the expression is a variable, the value of the variable will be displayed on the monitor.
Ex:
ch = ‘a’;
System.out.println(ch);
System.out.println( a + “+” + b ); // Why so many “+” signs?
System.out.println( “a + b “);
2.2.3 Data Declaration Statement
String a_string = “This is a test.”;
- Any statement must be ended with a semi-colon.
- A data declaration statement declares the data type, variable name, and optionally, the initial data.
- In the above case, String is the data type, a_string is the variable name, and the initial value is “this is a
test.”.
- When a variable is declared, Java reserves a space in memory for storing the value of the variable at compile
time.
2.3 Data Types
Java supports many data types and various instructions, called statements. This textbook uses an approach
similar to peeling an onion to introduce Java language constructs. It introduces a few data types and executable
statements at a time in each chapter before it moves on and introduces more data types. In the sample program,
we’ve seen the data type called String.
2.3.1 Identifiers
In any program, there are two types of data: constant and variable. The value of a constant remains unchanged
throughout the whole program while a variable can be assigned different values. In order to refer to a variable,
we need to give each variable a name, called an identifier. In our sample example, the name a_string is an
identifier.
2-4
In Java, there is a set of rules for determining whether or not an identifier is valid (legal).
-
an identifier must begin with a letter a, b, c,..., x, y, z, A, B, C, ..., X, Y, Z, _ and then followed by up to 255
numbers or letters including underscore.
NOTE: The first character can be an underscore, or any letter. The dash cannot be used anywhere in an
identifier, i.e., the name of a variable, named constant, a method, or a program.
2.3.2 Meta Language
- a language that is used to write the syntax rule for another language.
- The rules for an identifier, i.e., the name of a variable, or function.
identifier = {letter or _} + { letter or digit or _ }
Some names are reserved by Java so a user cannot use them as identifier. For example, int, const, this, etc. are
all reserved words.
Java Key Words
abstract
continue
boolean
default
break
do
byte
double
case
else
catch
enum
char
extends
class
false
const
final
Valid Identifiers
sum_of_59
_sum
J9
Int
Invalid Identifier
40Hours
Get Data
box-22
int
finally
float
dor
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
2-5
2.4 Primitive Data Types
- byte: used to represent integers in the range of –128 to +127
- short: (2 bytes) integers in the range of –32768 to +32767
- int : (4 bytes) used to represent integer variables, i.e., a number without a decimal point.
- long: (8 bytes) integers of 8 bytes long
- float : floating point number, i.e., a number with a decimal point.
- double: (8 bytes)
- char: a single character
The initial value of a char variable must be enclosed with single quotes. (The initial value of a String variable
must be enclosed with double quotes.)
We will explain how to use integer/float variables here.
Data : constant and variable
Ex: String a_var = “this is a test.”;
Null Statement
A semi-colon (;) by itself is a valid statement. It soes nothing.
2.5 Arithmetic Operators
To perform an arithmetic or logic operation, we use arithmetic operators or logic operators to associate constant
data or variable data together. For example, the arithmetic addition is achieved by using the “+” operator. Java
supports a rich of operators. In here, only a few of them are introduced as examples. More will be introduced
later in this course.
Addition
+
Subtraction Multiplication *
Division
/
Modulus
% (can only be applied to integer operations)
Some attention must be given to the way these operations are used in Java.
1. Addition is the same as what we know about addition as long as the sum falls within the range the data
type represents.
2. Integer division is tricky!!! For example 7/2=3 (not 3.5) since the result becomes a “floating-point” type.
3. Modulus is the remainder of the division. For example 17%3=2 (not 5).
2-6
In Class Exercises:
Find the results of the following operations, if a = 17, b = 3, c = 7:
1. a + b / c
2. a % b + c
3. a – b % c
4. a * b % c
5. a / b % c
Here you can see that there is a question on Operator Precedence. Which operator must be done first?
The rules are illustrated below:
High Precedence
- (unary negation)
* / %
Low Precedence
+ -
2.6 Assignment Statement
Syntax: variable = expression;
Note:
- The semicolon is required.
- To the left of the equal sign, only one non-constant variable name is allowed.
- To the right of the equal sign, an expression is allowed.
Semantics: The expression is evaluated and the value is stored into the memory address reserved for
the variable.
Q: What is an expression?
A: An expression is the arrangement of identifiers, literals, and operators that can be evaluated to compute a
value of a given type.
Literals: “abc”, ‘a’, 123, etc.
Operators: +, -, *, /, !(not), ||, &&, |, &
2-7
Examples of Invalid Assignment Statements (String Type)
Invalid assignments:
middle = ‘A.’; //Why?
middle = “A”;
first = thomas;
“Edison” = title;
first = ;
Examples:string expressions:
String bookTitle;
String phrase1;
String phrase2;
phrase1 = “Programming and “;
phrase2 = “Problem Solving”;
bookTitle = phrase1 + phrase2;
2.7 Conversion Between Primitive Data Types
2.8 Creating Name Constants
In Java, an identifier can be used to name a constant, i.e., a “final” named constant variable.
Ex: final String a_const_str = “this is a constant.”;
Incorrect: a_const_str = “a different value”; // You are not allowed to change the value of a constant
2.9 The String Class
The data type String is actually NOT a primitive type. It is a class. An instance of a class is called an object.
For example,
String name;
This is a data declaration statement that declares the name, type, and the characteristic (variable or constant) of
the variable “name”. The name object is an instance of a String class.
An object is associated with a number of methods. For example, a String class provides some methods. Refer to
the Java documentation on the Internet at the URL http://java.sun.com/j2se/1.5.0/docs/api/. For example,
charAt(), length(), toLowerCase(), and toUpperCase().
2-8
2.10 Scope
All data used must be defined first except the literal constants.
2.11 Comments
Various Styles:
(1) // this is comment
(2) char a = ‘a’; // this is a comment
(3) /* this is a comment */
2.12 Program Styles
Make your life and others’ easier! Indentation is importation.
2.13 Input Statement: Scanner
You need to install j2se 5.0 prior to using this feature.
See Payroll.java example.
Learn nextInt, nextLine, nextLong, nextShort.
2.14 Some GUI for fun!! – Dialog Boxes
See NamesDialog.java program example in Chapter02.
SUMMARY
Data Declaration
Null Statements
Assignment
Output
Input