Lecture 2

advertisement
COP 2551
Introduction to Object Oriented Programming with Java
Lecture 2
Topics
–
–
–
–
–
–
–
–
Introduction to the Java language
Code Commenting
Java Program Structure
Identifiers
Data Types
Variables
Constants
Text Input and Output
Introduction to Programming
• A program is a set of instructions
– It instructs the computer
• What resources it needs
• How to use the resources
• How to handle the results
– Real-life analogy examples:
• A recipe for baking cookies
• Instructions for assembling a table
• Computers can only perform simple instructions
– Our program instructions must be simple
• We need to break a problem into simple steps
• Computers can perform instructions very fast
Executing Programs
• 3 types of executable programs
– Compiled (C, C++)
• The source code must be compiled to machine language
– Translation
» Convert source code into symbolic language
– Compilation
» Convert source code into machine language
• The program is ready to run without additional resources
– Interpreted (JavaScript, PHP, Python)
• The source code is “interpreted” by the computer
– Each line of source code is compiled and executed
» Occurs in real time
– The interpreter must be running to run the program
– Hybrid (Java, Visual Basic))
• Mix between interpreted and compiled programs
– Source code is translated into symbolic language
– A real-time compiler compiles each symbolic line individually
» The real-time compiler must be running to run the program
Introduction to Java
• Java is a hybrid language
– Source code is translated into symbolic language
• Referred to as Java bytecode
– Bytecode is compiled into machine language
• Performed using a real-time compiler
– Referred to as the Just-In-Time compiler (JIT)
– A Java virtual machine (JVM) is required to run a
Java program
Commenting
• Comments are notes to the programmers
– Similar to college students’ note taking
• Highlighting important words or phrases
• Underlining passages
• Writing notes in the margins
– Java supports 3 forms of commenting
• Line or statement comments
– // This is a line comment
• Block comment
– /* This is a
block comment
*/
• JavaDoc comment
– /** This is a
javadoc
*/
JavaDoc
Structure of Java Program (section 1.4)
• A Java program has 3 primary sections
– Import Statements
• Add additional methods and operations to the program
import java.util.Scanner;
– Class Declarations
• Provides the name of the class
• Contains all of the program code
– Global Declarations
• Declare items that are accessible anywhere in the program
– Global variables
– Global constants
– Methods
• 1 or more methods that contain all the program’s statements
– Every Java program must contain a main() method
public static void main(String[] args)
Identifiers (section 1.4)
• Used to refer to items created by the programmer
– Variables
– Constants
– Methods
• 4 rules for creating identifiers
– Consist of letters, numbers and underscore characters only
• A-Z, a-z, 0-9, _
– 1st character must be a letter or underscore
• firstGrade and _1stGrade = OK
• 1stGrade, first-grade and first grade = Not OK
– Cannot duplicate a keyword or existing identifier (of same scope)
• Keyword is also referred to as Reserved Word
– Identifiers are case-sensitive
• age, Age, aGe, agE, AGe, AgE, aGE and AGE are considered unique
Identifiers (section 1.4)
• Additional identifier naming guidelines
– Identifiers should be self-explanatory
• Avoid single-letter identifiers
• a = Not self-explanatory (Bad)
• age = Self-explanatory (Good)
– Single-word identifiers
• Use all lowercase letters
– age, count, cost, salary, status, etc.
– Multi-word identifiers
• Use all lowercase letters
• Capitalize first letter of each subsequent word
– userAge, itemCount, totalCost, empSalary, errorStatus, etc.
Data Types (section 2.3)
• A data type defines
– A set of values
– The operations performed on those values
• Valid data types in Java
– Many more exist, but only these will be used in class
– Integral
• Boolean (referred to as “boolean”)
– Represents an true/false condition
• Character (referred to as “char”)
– Represents a displayable characters (65 = ‘A’)
• Integer (referred to as “int”)
– Represents all integer values (i.e., -3, -2, -1, 0, 1, 2, 3, etc.)
– Floating-point
• Double (referred to as “double”)
– Represents all numeric values containing a decimal point (i.e., -2.0, -1.0, 0.0, 1.0, 2.0, etc.)
– String
• Represents a collection of characters
Data Types (chapter 2)
Category
Integral
Data Type
# Bytes
Min Value
Max Value
boolean
2
False
True
char
2
0
65535
int
4
-2,147,483,648
2,147,483,647
FloatingPoint
double
8
-1.7x10-308
1.7x10308
String
String
2n
2*0 Characters
2*n Characters
Variables (section 2.2)
• Variables
– Store data values during runtime
• Referred to as “assigning a value”
– Refer to locations in memory
– Must be declared before using
• Specify the identifier name and data type
• Using the following form
DataType Identifier;
• Value can be assigned when declared (“initializing”)
DataType Identifier = Value;
– Values can be changed during runtime
Variables (section 2.2)
• When a variable is declared
– The program requests memory from the OS
• The amount of memory depends on the data type
– The OS locates the required memory
• The memory address is returned to the program
– The program references the memory address
• Using the specified identifier
– If the variable is initialized with a value
• The value is assigned to the memory address
Variables (section 2.2)
• Important issue with variable declaration
– A variable must be initialized before it is accessed
• If a variable is accessed before it is initialized
– The compiler will display an error
• Always initialize variables before using them
Variables (section 2.2)
• Variable declaration and assignment examples
Declared w/o Value
Declared w/ Value
int age; // Not initialized
int age = 0; // Initialized
age = 29; // Assign value
// More lines of code
age = 21; // Assign new value
age = 29; // Assign value
// More lines of code
age = 21; // Assign new value
Example Declarations w/o Value
Example Declarations w/ Value
boolean valid;
char initial;
int count;
double salary;
String name;
boolean valid = true;
char initial = ‘A’; Both mean
the same
char initial = 65;
int count = 0;
double salary = 9.5;
String name = “Jim”;
Variables (section 2.2)
• 3 ways to declare/initialize variables
Note: Ordering variables names alphabetically improves readability
– One variable per line int age;
int count;
char initial;
double ratio;
double salary;
– Multiple variables per line
• Declare variables of different data types on separate lines
Dim age, count As Integer
Dim initial As Char
Dim ratio, salary As Double
– Variables can be initialized or not
int age;
int count = 0;
char initial = ‘A’;
double ratio = 0.5;
double salary;
int age, count = 0;
char initial = ‘A’;
double ratio = 0.5, salary;
Constants (section 2.2)
• A constant is a value that cannot be changed
– Only the programmer can change the value
• Java supports 2 types of constants
– Literal constant (no memory required)
int a = 0;
• In the above example, 0 is a literal example
– Only the programmer can change the value
– Memory constant (memory required)
final double PI = 3.14;
• Used similar to a variable, but value cannot be changed
Input/Output
• Java has access to 3 data streams
– Input
• i.e., keyboard
• The characters typed on the keyboard
– Output
• i.e., monitor
• The characters displayed on the monitor
– Input/Output
• i.e., file (discussed later in the course)
• The characters read to/written from a file
Input/Output (section 2.1)
• The print() and println() output functions
– Displays data on the monitor
String name = “Kelly”;
int salary = 45000;
System.out.print(name + “ has an annual salary of $” + salary + “\n”;
System.out.println(name + “ has an annual salary of $” + salary;
Output:
Kelly has an annual salary of $45000
– System.out.print
• Displays the contents between the parentheses
• Leaves the cursor at the end of the line
– System.out.println
• Displays the contents between the parentheses
• Moves the cursor to the beginning of the next line
– Data Values can be “concatenated” into the display string
• Variables
• Constants
• Method return values
Input/Output (section 2.1)
• The Scanner class
– Reads data from the monitor
Scanner input = new Scanner(System.in);
int salary;
System.out.print(“Enter your annual salary (in $): ”;
salary = input.nextInt(); // User enters 45000
System.out.println(“You entered an annual salary of $” + salary);
Output:
You entered an annual salary of $45000
– Common Scanner class methods
• nextInt() – reads an integer value from the keyboard
• nextDouble() – reads a double value from the keyboard
• next() – reads a string from the keyboard
Non-numeric
input will cause
error
– If the user can enter non-numeric values
» Use the next() method
» Then use the appropriate “parse” method for the expected data type
Download