Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java
Java Programming: Guided Learning with Early Objects2 Objectives Become familiar with the basic components of a Java program Explore primitive data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Explore how mixed expressions are evaluated
Java Programming: Guided Learning with Early Objects3 Objectives (continued) Learn about type casting Become familiar with the String type Learn what an assignment statement is and what it does Become familiar with the use of increment and decrement operators
Java Programming: Guided Learning with Early Objects4 Objectives (continued) Discover how to create a Java application program Explore how to structure a program properly Learn how to avoid bugs by using consistent and proper formatting Learn how to do a code walk-through
Java Programming: Guided Learning with Early Objects5 A Java Program Basic unit of a Java program is a class Class: consists of one or more methods Method: a sequence of statements –Objective is to accomplish something Braces mark beginning and end of class Execution always begins with main method –Every application must have a main method –Class can have at most one main method
Java Programming: Guided Learning with Early Objects6 Basics of a Java Program Two types of Java programs: –Applets –Applications Syntax rules tell you which statements are legal Semantic rules determine meaning of instructions Programming language: –Set of rules, symbols, special words used to construct programs
Java Programming: Guided Learning with Early Objects7 Comments Comments used to identify: –Program authors –Date when the program written or modified –Brief explanation of the program –Meaning of key statements Single-line comments begin with // –Can be placed anywhere in the line Multiple-line comments inside /* and */
Java Programming: Guided Learning with Early Objects8 Special Symbols Token: smallest individual unit of a program Java tokens are divided into special symbols, reserved words, and identifiers Special symbols: + - * /, ; ?. = Also include blanks
Java Programming: Guided Learning with Early Objects9 Reserved Words Reserved words also called keywords Examples of reserved words: int, float, double, char, void, public, static, throws, return Reserved words always lowercase Each word considered a single symbol Cannot be used for any other purpose
Java Programming: Guided Learning with Early Objects10 Identifiers Names of things –Variables, constants, methods, classes –Predefined or user-defined Letters, digits, underscore, dollar sign –May not begin with a digit Any length Predefined identifiers may be redefined by the user
Java Programming: Guided Learning with Early Objects11 White Spaces Include blanks, tabs, newline characters Separate special symbols, reserved words, identifiers Nonprinted characters Format the program –Make it readable
Java Programming: Guided Learning with Early Objects12 Data Types Java programs manipulate data Java categorizes data into different types Certain operations performed only on certain types of data Data type: set of values together with a set of operations
Java Programming: Guided Learning with Early Objects13 Primitive Data Types Fundamental data types in Java Integral –Integers, characters Floating-point –Decimal numbers Boolean –Logical values: true or false Integral types: –char, byte, short, int, long
Java Programming: Guided Learning with Early Objects14 Table 1-2 Values and Memory Allocation for Integral Data Types
Java Programming: Guided Learning with Early Objects15 int Data Type Examples of integers: -6728, -67, 0, 78, 36782, +763 Positive integers do not require a + sign in front No commas are used in an integer –Commas only used to separate list items
Java Programming: Guided Learning with Early Objects16 char Data Type values, numbered from 0 to Represents single characters –Letters, digits, special symbols Enclose character represented in single quotes –Blank character written as ‘ ’ Special symbols: –Newline: ‘\n’ –Tab: ‘\t’ –Null: ‘\0’
Java Programming: Guided Learning with Early Objects17 boolean Data Type Two values: true and false –Also called logical values Primary purpose to manipulate logical expression boolean, true, false are reserved words boolean data type allocated one bit in memory
Java Programming: Guided Learning with Early Objects18 Floating-Point Data Types Recall scientific notation: = x = 2.65 x float –Real numbers between -3.4E+38 and 3.4E+38 –Single precision double –Real number between -1.7E+308 and 17E+308 –Double precision
Java Programming: Guided Learning with Early Objects19 Literals (Constants) Values such as 23 and -67 are integer literals –Also called integer constants or integers Values such as and are floating- point literals –Also called floating-point constants or floating-point numbers Values such as ‘a’ and ‘5’ are character literals –Also called character constants or characters
Java Programming: Guided Learning with Early Objects20 Arithmetic Operators and Operator Precedence Arithmetic operators: –Addition + –Subtraction (negation) – –Multiplication * –Division / –Mod (modulus or remainder) % Operands: constants and variables Unary operator: one operand Binary operator: two operands
Java Programming: Guided Learning with Early Objects21 Order of Precedence Determines the order in which operations performed Multiplication, division, modulus have higher precedence than addition, subtraction Same level of precedence, operations performed left to right Parentheses override precedence Associativity of arithmetic operators said to be from left to right
Java Programming: Guided Learning with Early Objects22 Expressions Integral expression: all numeric operands are integers –Yields an integral result Floating-point (decimal) expression: all numeric operands are floating-point –Yields a floating-point result
Java Programming: Guided Learning with Early Objects23 Mixed Expressions Expression with operands of different data types When evaluating operator –If operands same type, operator evaluated according to type of operand –If operands of different types, integer treated as floating point Entire expression evaluated according to precedence rules
Java Programming: Guided Learning with Early Objects24 Type Conversion (Casting) Implicit type coercion: value of one data type automatically treated as another data type Cast operator (type conversion or type casting): explicit type conversion (dataTypeName) expression First expression evaluated, then treated as if the value of type dataTypeName Floating-points cast as integer are truncated To cast char as int, use collating sequence (int)‘A’ is 65
Java Programming: Guided Learning with Early Objects25 class String String: sequence of zero or more characters –Enclosed in double quotations Java class String contains operations to process strings Null (empty) string: contains no characters Each character has a specific position –First character is position 0 Length of a string is the number of characters
Java Programming: Guided Learning with Early Objects26 Strings and the Operator + Concatenation appends a string at the end of another string Operator + concatenates: –Two strings –String and a numeric value –String and a character Examples: “Sunny” + “ Day” is “Sunny Day” “Due = $” is “Due = $57.25”
Java Programming: Guided Learning with Early Objects27 Named Constants, Variables, and Assignment Statements Main objective of Java programs is to perform calculations and manipulate data Data must be loaded into main memory before it can be manipulated Storing data in memory is two-step process: –Instruct computer to allocate named memory space –Include statement in the program to put data in allocated memory
Java Programming: Guided Learning with Early Objects28 Allocating Memory with Named Constants and Variables Instruct the computer to allocate memory –Name to use for each memory location –Type of data to store in each location Computer system chooses the memory location –Location may change from one execution to the next Named constant: memory location whose content does not change during execution static final dataType IDENTIFIER = value;
Java Programming: Guided Learning with Early Objects29 Allocating Memory with Named Constants and Variables (continued) Reserved word static is optional Identifier for constants uppercase –Words separated by underscores Variable: memory location whose content may change during program execution dataType identifier1, …, identifierN;
Java Programming: Guided Learning with Early Objects30 Putting Data into Variables Two ways to put data into variables: –Use an assignment statement –Use an input (read) statement
Java Programming: Guided Learning with Early Objects31 Assignment Statement Assignment statement: variable = expression; Value of expression same data type as variable Right side evaluated, assigned to left side Variable initialized the first time a value stored Assignment operator: =
Java Programming: Guided Learning with Early Objects32 Table 1-2 Values of the Variables num1, num2, and num3
Java Programming: Guided Learning with Early Objects33 Declaring and Initializing Variables Java does not automatically initialize variables Variables must be initialized before they are used int first; first = 12; Can initialize variables when they are declared int first = 12; char ch = ‘ ’;
Java Programming: Guided Learning with Early Objects34 Increment and Decrement Operators Incrementing a variable increases value by one count = count + 1; Increment operator increases value by one –Pre-increment: count++; –Post-increment: ++count; Decrement operator decreases value by one –Pre-decrement: count--; –Post-decrement: --count;
Java Programming: Guided Learning with Early Objects35 Creating a Java Application Program Basic unit of a Java program is a class –Java application program a collection of classes Class a collection of methods, data members Method is a set of instructions to accomplish a specific task –Predefined methods –User-defined methods One class in application must contain main method
Java Programming: Guided Learning with Early Objects36 Creating a Java Application Program (continued) Syntax for a class: public class ClassName { classMembers } Syntax for main method: public static void main (String[] args) { statement1 … statementN }
Java Programming: Guided Learning with Early Objects37 Syntax, Semantics, and Errors Using proper structure makes program easier to understand and modify Program that is syntactically correct but has no structure is difficult to follow Every program must satisfy syntax rules Semantic rules give meaning to the program
Java Programming: Guided Learning with Early Objects38 Syntax Syntax rules determine what is legal If program violates syntax rules, will not compile –Compiler generates error message One syntax error may generate multiple compiler errors Correct syntax errors in order in which compiler lists them Compilers also provide hints –Sometimes tell you the location and how to fix the error
Java Programming: Guided Learning with Early Objects39 Use of Semicolons, Braces, and Commas Semicolon is the statement terminator Braces delimit the body of a class or body of a method Commas separate items in a list –Use commas to declare more than one variable of a given data type
Java Programming: Guided Learning with Early Objects40 Semantics Semantics: rules that give meaning to a language –Example: order-of-precedence rules Possible to eliminate syntax errors and still have semantic errors Example: * 5 substituted for ( 2 + 3) * 5
Java Programming: Guided Learning with Early Objects41 Form and Style Rules give Java a great degree of freedom –Many ways to do the same task Use formatting to make program readable –Programs should be indented and formatted properly –Align associated left and right braces –Indent for a new set of braces –Blank lines to separate portions of a program –Declare one variable per line –Space before and after operator
Java Programming: Guided Learning with Early Objects42 Avoiding Bugs: Consistent, Proper Formatting Consistent, proper formatting makes it easier to debug and maintain programs Consistent use of white space Consistent and predictable use of upper and lowercase
Java Programming: Guided Learning with Early Objects43 Debugging: Code Walk-Throughs Syntactically correct programs may produce incorrect results or crash Programmers walk through their own programs Can be advantageous to invite another programmer to review the code –Must format and comment the code first –Must explain the code to the other person Presentation to larger group is also a walk- through
Java Programming: Guided Learning with Early Objects44 Summary Basic unit of a Java program is a class Class consists of one or more methods Method is a sequence of statements to accomplish a specific task Execution always begins with main method Every application must have a main method
Java Programming: Guided Learning with Early Objects45 Summary (continued) Syntax rules tell you which statements are legal Semantic rules determine meaning of instructions Java tokens are divided into special symbols, reserved words, and identifiers Data type: set of values together with a set of operations
Java Programming: Guided Learning with Early Objects46 Summary (continued) Fundamental data types in Java: –Integral –Floating-point –Boolean Integral types: –char, byte, short, int, long Floating-point types: –float, double
Java Programming: Guided Learning with Early Objects47 Summary (continued) Multiplication, division, modulus have higher precedence than addition, subtraction –Operations performed left to right Implicit type coercion: value of one data type automatically treated as another data type Explicit type casting: cast operator (dataTypeName) expression String: sequence of zero or more characters –Enclosed in double quotations
Java Programming: Guided Learning with Early Objects48 Summary (continued) Storing data in memory is two-step process: –Instruct computer to allocate named memory space –Include statement in the program to put data in allocated memory Instruct the computer to allocate memory –Name to use for each memory location –Type of data to store in each location
Java Programming: Guided Learning with Early Objects49 Summary (continued) Named constant: memory location whose content does not change during execution Variable: memory location whose content may change during program execution Increment operator increases value by one Decrement operator decreases value by one
Java Programming: Guided Learning with Early Objects50 Summary (continued) Using proper structure makes program easier to understand and modify Correct syntax errors in order in which compiler lists them Possible to eliminate syntax errors and still have semantic errors Use formatting to make program readable Code walk-throughs help debugging