Download presentation
Presentation is loading. Please wait.
1
Chapter 2: Basic Elements of Java
Java Programming: Program Design Including Data Structures
2
Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols, and identifiers 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: Program Design Including Data Structures
3
Chapter Objectives (continued)
Learn about type casting Become familiar with the String type Learn what an assignment statement is and what it does Discover how to input data into memory by using input statements Become familiar with the use of increment and decrement operators Java Programming: Program Design Including Data Structures
4
Chapter Objectives (continued)
Examine ways to output results using output statements Learn how to import packages and why they are necessary Discover how to create a Java application program Explore how to properly structure a program, including using comments to document a program Java Programming: Program Design Including Data Structures
5
Introduction Computer program: A sequence of statements designed to accomplish a task Programming: The process of planning and creating a program Java Programming: Program Design Including Data Structures
6
The Basics of a Java Program
Java program: A collection of classes There is a main method in every Java application program Java Programming: Program Design Including Data Structures
7
The Basics of a Java Program
public class TheClass { . . . } public static void main(String[] argv) { … } Java Programming: Program Design Including Data Structures
8
Special Symbols Java Programming: Program Design Including Data Structures
9
Word Symbols void int public float static double throws char return
Java Programming: Program Design Including Data Structures
10
Java Identifiers Names of things Consists of:
Letters Digits The underscore character (_) The dollar sign ($) Must begin with a letter, underscore, or the dollar sign Java Programming: Program Design Including Data Structures
11
Illegal Identifiers Java Programming: Program Design Including Data Structures
12
Data Types A set of values together with a set of operations
Java Programming: Program Design Including Data Structures
13
Primitive Data Types Java Programming: Program Design Including Data Structures
14
Primitive Data Types (continued)
Floating-point data types: Float: Precision = 6 or 7 I owe the bank $12, on my car loan Double: Precision = 15 The Outstanding Public Debt as of 05 Sep 2007 at 01:44:50 AM GMT is: $ 8,997,049,881, Java Programming: Program Design Including Data Structures
15
Primitive Data Types (continued)
Boolean: True False Java Programming: Program Design Including Data Structures
16
Integral Data Types Java Programming: Program Design Including Data Structures
17
Values and Memory Allocation for Integral Data Types
Java Programming: Program Design Including Data Structures
18
Arithmetic Operators and Operator Precedence
Five arithmetic operators: + addition - subtraction * multiplication / division % mod (modulus) Unary operator: An operator that has one operand (negation, absolute value, …) Binary operator: An operator that has two operands (addition, subtraction, …) Java Programming: Program Design Including Data Structures
19
Order of Precedence 1: * / % (same precedence)
Operators in group 1 have a higher precedence than operators in group 2 When operators have same level of precedence, operations are performed from left to right (lexicographical order) Use parenthesis to break any ambiguities. Java Programming: Program Design Including Data Structures
20
Expressions Integral expressions Floating-point or decimal expressions
Mixed expressions Java Programming: Program Design Including Data Structures
21
Integral Expressions All operands are integers Examples: 2 + 3 * 5
3 + x – y / 7 x + 2 * (y – z) + 18 Java Programming: Program Design Including Data Structures
22
Integral Expressions Pierre de Fermat (France, 1601-1665)
Fermat is considered to be one of the 'fathers' of analytic geometry. (Along with Rene' Descartes.) Fermat along with Blaise Pascal is also considered to be one of the founders of probability theory. Fermat also made contributions in the field of optics and provided a law on light travel and made wrote a few papers about calculus well before Isaac Newton and Gottfried Leibniz were actually born. Fermat's most important work was done in the development of modern number theory which was one of his favorite areas in math. He is best remembered for his number theory, in particular for Fermat's Last Theorem. This theorem states that: xn + yn = zn has no non-zero integer solutions for x, y and z when n is greater than 2. This theorem remained without a proof for about 350 years until 1993 when Andrew J. Wiles provided the first proof. Java Programming: Program Design Including Data Structures
23
Floating-Point Expressions
All operands are floating-point numbers Examples: 12.8 * 17.5 – 34.50 x * y – 16.2 Java Programming: Program Design Including Data Structures
24
Mixed Expressions Operands of different types Examples: 2 + 3.5
6 / Integer operands yield an integer result; floating-point numbers yield floating-point results If both types of operands are present, the result is a floating-point number Precedence rules are followed Java Programming: Program Design Including Data Structures
25
Type Conversion (Casting)
Used to avoid implicit type coercion Syntax: (dataTypeName) expression Expression evaluated first, then type converted to: dataTypeName Examples: (int)( ) = 14 (int)(7.9) + (int)(6.7) = 13 Java Programming: Program Design Including Data Structures
26
The class String Used to manipulate strings String:
Sequence of zero or more characters Enclosed in double quotation marks (“Hola”) Null or empty strings have no characters (“”) Numeric strings consist of integers or decimal numbers ( ,456.78) Length is the number of characters in a string Java Programming: Program Design Including Data Structures
27
Input Named constant Cannot be changed during program execution
Declared by using the reserved word final Initialized when it is declared Example 2-11 final double PI = ; final double CENTIMETERS_PER_INCH = 2.54; final int NO_OF_STUDENTS = 20; final char BLANK = ' '; final char USD = '$'; final double PAY_RATE = 15.75; Java Programming: Program Design Including Data Structures
28
Input (continued) Variable (name, value, data type, size)
Content may change during program execution Must be declared before it can be used May not be automatically initialized If new value is assigned, old one is destroyed Value can only be changed by an assignment statement or an input (read) statement Example 2-12 double amountDue; int counter; char ch; int x, y; Java Programming: Program Design Including Data Structures
29
Input (continued) Variable (name, value, data type, size)
double amountDue = ; Name: amountDue Value: Type: double Size: 6 Java Programming: Program Design Including Data Structures
30
Input (continued) The Assignment Statement variable = expression;
Example 2-13 int i, j; double sale; char first; String str; i = 4; j = 4 * ; sale = 0.02 * 100.0; first = 'D'; str = "It is a sunny day"; Java Programming: Program Design Including Data Structures
31
Input (continued) Standard input stream object is System.in
Input numeric data to program Separate by blanks, lines, or tabs To read data: Create an input stream object of the class Scanner Use the methods such as next, nextLine, nextInt, nextLong, nextFloat, nextDouble, and hasNext Java Programming: Program Design Including Data Structures
32
Input (continued) import java.util.*;
// public class HolaAmigo { /* my second JAVA program - making friends */ static Scanner Console = new Scanner(System.in); public static void main(String[] argv) { String myLine; System.out.println ("Enter your name"); myLine = Console.nextLine(); System.out.println("Hola amigo " + myLine + ", como estas?"); } } Java Programming: Program Design Including Data Structures
33
Input (continued) Example 2-16
static Scanner console = new Scanner(System.in); Example 2-16 int feet; int inches; Suppose the input is 23 7 feet = console.nextInt(); //Line 1 inches = console.nextInt(); //Line 2 Java Programming: Program Design Including Data Structures
34
Increment and Decrement Operators
++ increments the value of its operand by 1 -- decrements the value of its operand by 1 Syntax: Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-- Java Programming: Program Design Including Data Structures
35
Increment and Decrement Operators
import java.util.*; public class PlusPlus { /* quick demo PRE/POST incrementation ++ operator */ static Scanner Console = new Scanner(System.in); public static void main(String[] argv) { //PRE incrementation int n = 10; System.out.println ("n is: " + n); System.out.println ("++n is: " + (++n)); System.out.println ("n is: " + n); //POST incrementation n = 20; System.out.println ("n is: " + n); System.out.println ("n++ is: " + (n++)); System.out.println ("n is: " + n); } } n is: 10 ++n is: 11 n is: 11 n is: 20 n++ is: 20 n is: 21 Java Programming: Program Design Including Data Structures
36
Strings and the Operator +
Operator + can be used to concatenate two strings, or a string and a numeric value or character Example 2-20 String str; int num1, num2; num1 = 12; num2 = 26; str = "The sum = " + num1 + num2; After this statement executes, the string assigned to str is: "The sum = 1226"; Java Programming: Program Design Including Data Structures
37
Strings and the Operator + (continued)
Consider the following statement: str = "The sum = " + (num1 + num2); Because of parentheses, first evaluate num1+num2 Because num1 and num2 are both int variables, (num1 + num2) = ( ) = 38 After this statement executes, the string assigned to str is: "The sum = 38"; Java Programming: Program Design Including Data Structures
38
Output Standard output object is System.out Methods: Syntax:
print println Syntax: System.out.print(stringExp); System.out.println(stringExp); System.out.println(); Java Programming: Program Design Including Data Structures
39
Commonly Used Escape Sequences
Java Programming: Program Design Including Data Structures
40
Packages, Classes, Methods, and the import Statement
Package: A collection of related classes Class: Consists of methods Method: Designed to accomplish a specific task Java Programming: Program Design Including Data Structures
41
import Statement Import the components of a package into a program
Reserved word import java.io.*; Imports the (components of the) package java.io into the program Primitive data types and the class String: Part of the Java language Don’t need to be imported Java Programming: Program Design Including Data Structures
42
Creating a Java Application Program
Syntax of a class: Syntax of the main method: Java Programming: Program Design Including Data Structures
43
Programming Style and Form
Know common syntax errors and rules Use blanks appropriately Use a semicolon as a statement terminator Important to have well-documented code Good practice to follow traditional rules for naming identifiers Java Programming: Program Design Including Data Structures
44
More on Assignment Statements
Expression variable = variable * (expression); is equivalent to: variable *= expression; Similarly, variable = variable + (expression); variable += expression; Java Programming: Program Design Including Data Structures
45
Programming Examples Convert Length program: Make Change program:
Input: Length in feet and inches Output: Equivalent length in centimeters Make Change program: Input: Change in cents Output: Equivalent change in half-dollars, quarters, dimes, nickels, and pennies Java Programming: Program Design Including Data Structures
46
Programming Examples import java.util.*; // // Convert Length program: // public class EnglishDistance { // converting from metric to English dist. static Scanner Console = new Scanner(System.in); public static void main(String[] argv) { final double INC2CM = 2.54; double meters = 1.90; //TODO: try to enter the meters value via keyboard int feet; int inches; inches = (int) ((100*meters) / 2.54); feet = (int) (inches / 12); inches = inches - (12*feet); System.out.println("meters " + meters ); System.out.println("feet " + feet); System.out.println("inches " + inches); } } Java Programming: Program Design Including Data Structures
47
Chapter Summary Basic elements of a Java program include:
The main method Reserved words Special symbols Identifiers Data types Expressions Input Output Statements Java Programming: Program Design Including Data Structures
48
Chapter Summary (continued)
To create a Java application, you must understand: Syntax rules Semantic rules How to manipulate strings and numbers How to declare variables and named constants How to receive input and display output Good programming style and form Java Programming: Program Design Including Data Structures
49
Homework Page 109. Problem 9. Due on Wed. Sep. 12.
Exam 1. Mon. Sept 10. Chapters 1, 2. Java Programming: Program Design Including Data Structures
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.