Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Expressions ► An expression can be a single variable, or can include a series of variables. If an expression includes multiple variables they are combined.
Chapter 2: Basic Elements of C++
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++
Chapter 2: Introduction to C++.
JavaScript, Third Edition
Chapter 2: Basic Elements of C++
Basic Elements of C++ Chapter 2.
Chapter 2-3: Basic Elements of Java. Chapter Objectives Discover how to use arithmetic operators. Examine how a program evaluates arithmetic expressions.
CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will:  Become familiar with the basic components of a C++ program, including functions, special.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Chapter 2: Basic Elements of Java
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2: Using Data.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Chapter 2: Java Fundamentals Type conversion,String.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Basic Elements of C++. Introduction Computer program – Sequence of statements whose objective is to accomplish a task Programming – Process.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++. Objectives In this chapter, you will: – Become familiar with the basic components of a C++ program, including functions,
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2: Basic Elements of C++
Chapter 2: Basic Elements of Java
Chapter 2: Basic Elements of C++
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2: Basic Elements of Java
Computer Programming BCT 1113
BASIC ELEMENTS OF A COMPUTER PROGRAM
Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2: Basic Elements of C++
Basic Elements of C++ Chapter 2.
OPERATORS (2) CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Basic Elements of Java
Chapter 2: Java Fundamentals
elementary programming
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition

Java Programming: From Problem Analysis to Program Design, Second Edition 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: From Problem Analysis to Program Design, Second Edition 3 Chapter Objectives  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: From Problem Analysis to Program Design, Second Edition 4 Chapter Objectives  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: From Problem Analysis to Program Design, Second Edition 5 Introduction  Computer program: A sequence of statements designed to accomplish a task.  Programming: The process of planning and creating a program.

Java Programming: From Problem Analysis to Program Design, Second Edition 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: From Problem Analysis to Program Design, Second Edition 7 Special Symbols

Java Programming: From Problem Analysis to Program Design, Second Edition 8 Word Symbols  int  float  double  char  void  public  static  throws  return

Java Programming: From Problem Analysis to Program Design, Second Edition 9 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 is case sensitive.

Java Programming: From Problem Analysis to Program Design, Second Edition 10 Illegal Identifiers

Java Programming: From Problem Analysis to Program Design, Second Edition 11 Data Types  The objective of a Java program is to manipulate data.  Different programs manipulate different data.  A Data type is a set of values together with a set of operations.  Only certain operations can be performed on a particular type of data.

Java Programming: From Problem Analysis to Program Design, Second Edition 12 Primitive Data Types (fundamental DT) integers Decimal numbers Logical values

Java Programming: From Problem Analysis to Program Design, Second Edition 13 Primitive Data Types  Floating-point data types:  Represent real numbers in scientific notation. Ex:  E1 in java  Has two types :  Float: Precision = 6 or 7 (4bytes)  Double: Precision = 15 (8 bytes )  The default type of floating-point numbers is double.

Java Programming: From Problem Analysis to Program Design, Second Edition 14 Primitive Data Types  Boolean:  Has Two values:  True  False  These are called the logical (Boolean) values.  The central purpose of this data type is to manipulate logical (Boolean) expressions. Reserved words

Java Programming: From Problem Analysis to Program Design, Second Edition 15 Integral Data Types

Java Programming: From Problem Analysis to Program Design, Second Edition 16 Integral Data Types  deals with integers, or numbers without a decimal part.  The type depends on how big the number is.  The char data type is used to represent single characters such It can represent any key on your keyboard. Ex : ‘a’, ‘+’,‘7’  Java uses the Unicode character set, which contains values numbered 0 to  ASCII is a subset of Unicode.

Java Programming: From Problem Analysis to Program Design, Second Edition 17 Values and Memory Allocation for Integral Data Types

Java Programming: From Problem Analysis to Program Design, Second Edition 18 Arithmetic Operators and Operator Precedence  Five arithmetic operators:  + addition  - subtraction  * multiplication  / division  % mod (modulus)  / with integral data types  integer results.  Unary operator: An operator that has one operand.  Binary operator: An operator that has two operands.

Java Programming: From Problem Analysis to Program Design, Second Edition 19 Order of Precedence * /% (same precedence) +- (same precedence)  Operators in 1 have a higher precedence than operators in 2.  When operators have the same level of precedence, operations are performed from left to right.(i.e associativity of arithmetic operators from left to right )  Arithmetic operations ca be performed on char data. The integer value is the Unicode collating sequence.

Java Programming: From Problem Analysis to Program Design, Second Edition 20  34 % 5  4  -34 % 5  -4  34 % -5  4  -34 % -5  -4

Java Programming: From Problem Analysis to Program Design, Second Edition 21 Expressions  Integral expressions  Floating-point or decimal expressions  Mixed expressions

Java Programming: From Problem Analysis to Program Design, Second Edition 22 Integral Expressions  All operands are integers.  Examples: * x – y / 7 x + 2 * (y – z) + 18

Java Programming: From Problem Analysis to Program Design, Second Edition 23 Floating-Point Expressions  All operands are floating-point numbers.  Examples: 12.8 * 17.5 – x * y

Java Programming: From Problem Analysis to Program Design, Second Edition 24 Mixed Expressions  Operands of different types.  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.  Examples:  /2.0  /  6.0 4*3+7/  -12.5

Java Programming: From Problem Analysis to Program Design, Second Edition 25  Character Arithmetic:  char data type is an integer  Hence integer arithmetic is allowed on char data: ‘8’  integer 56 ‘8’ + 1  57

Java Programming: From Problem Analysis to Program Design, Second Edition 26 Type Conversion (Casting)  Used :  to change one data type to another.  to avoid implicit type coercion.  Syntax: (dataTypeName) expression  Expression evaluated first, then the value is converted to dataTypeName

Java Programming: From Problem Analysis to Program Design, Second Edition 27 Type Conversion (Casting)  Examples: 1.(int)( ) = 14 2.(int)(7.9) + (int)(6.7) = 13 3.(double)(17) = (double)(8+3) = (double)11 = (double)(7) /2 = 7.0/2 = (double)(7/2) = (int)(7.8+(double)(15)/2) = (int)15.3 =15

Java Programming: From Problem Analysis to Program Design, Second Edition 28 Type Conversion (Casting) (int)(7.8+(double)(15/2))=(int)14.8 =14 x=15,y = 23, z= ( double) (y/x)+ z = (double)(1)+3.75= (double) (y) /x + z = = (int)(‘A’) = (int)(‘8’) = (char) (65) = ‘A’ 14.(char) (56) = ‘8’

Java Programming: From Problem Analysis to Program Design, Second Edition 29 The class String  Contains operations to manipulate strings.  String:  Sequence of zero or more characters.  Enclosed in double quotation marks.  Is processed as a single unit.  Null or empty strings have no characters. “ “  Every character has a relative position, the first character is in position 0.

Java Programming: From Problem Analysis to Program Design, Second Edition 30 The class String  Numeric strings consist of integers or decimal numbers.  Length of the string is the number of characters in it.  When determining the length of a string, blanks count.  Example :  “ “  has length = 0  “abc”  has length = 3, position of a = 0,b= 1, c= 2  “a boy”  has length = 5

Java Programming: From Problem Analysis to Program Design, Second Edition 31 Input Allocating Memory  Memory can be allocated to store constants and variables. Named constant  A memory location whose content cannot be changed during program execution.  Declared by using the reserved word final.  Initialized when it is declared.

Java Programming: From Problem Analysis to Program Design, Second Edition 32 Input  To declare a named constant : static final datatype Identifier = value ;  Example 2-11 final double CENTIMETERS_PER_INCH =2.54; final int NO_OF_STUDENTS = 20; final char BLANK = ' '; final double PAY_RATE = ;  The default type of floating point numbers is double.  The declaration : final float rate = 15.5f ; without the f, the compiler will generate an error.

Java Programming: From Problem Analysis to Program Design, Second Edition 33 Input Variable (name, value, data type, size )  A memory location whose 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.  can obtain values with :  an assignment statement  an input (read) statement. Example 2-12 double amountDue; int counter; char ch; int x, y;

Java Programming: From Problem Analysis to Program Design, Second Edition 34 Input The Assignment Statement  variable = expression;  Value of expression should match the data type of the variable.  Expression on right is evaluated, value is assigned to variable on the left.  Java is strongly typed; you cannot assign a value to a variable that is not compatible with its data type.  Associativity of assignment operator is from right to left. x = y = z ;

Java Programming: From Problem Analysis to Program Design, Second Edition 35 Input Example 2-13 int i, j; double sale; char first; String str; i = 4; j = 4 * ; sale = 0.02 * 1000; first = 'D'; str = "It is a sunny day.";

Java Programming: From Problem Analysis to Program Design, Second Edition 36 Input Input (read) statement  To read data into variables : 1.Create an input stream object of the class Scanner. 2.Associate it with the standard input device. The following statement accomplishes this: static Scanner console=new Scanner(System.in);  System.in. = Standard input stream object and is designed to input data from standard input device.  Console is the created input stream object.

Java Programming: From Problem Analysis to Program Design, Second Edition 37 Input  The object console reads input using the following methods A.console.nextInt(): to read integer. B.console.nextDouble(): to read floating-point numbers. (double & float) C.console.next(): to read a string. D.console.nextLine(): to read a string until the end of the line.

Java Programming: From Problem Analysis to Program Design, Second Edition 38 Input Example 2-16 static Scanner console = new Scanner(System.in); int feet; int inches; Suppose the input is 23 7 feet = console.nextInt(); //23 is stored in feet inches = console.nextInt();//7is stored in inches

Java Programming: From Problem Analysis to Program Design, Second Edition 39 Example 2-16 import java.util.*; public class Example2_16 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int feet; int inches; System.out.println("Enter two integers separated by spaces."); feet = console.nextInt(); inches = console.nextInt(); System.out.println("Feet = " + feet); System.out.println("Inches = " + inches); }

Java Programming: From Problem Analysis to Program Design, Second Edition 40 Variable Initialization  When a variable is declared, Java might not automatically put a meaningful value into it.  If you declare a variable and then use it in an expression without first initializing it, when you compile the program you are likely to get an error. Therefore Java allows you to initialize variables while they are being declared.  Consider the following declaration: int feet; You can initialize the variable feet to a value of 35 either by using the assignment statement: feet = 35; or by executing the following statement and entering 35 during program execution: feet = console.nextInt();

Java Programming: From Problem Analysis to Program Design, Second Edition 41 Example 2-17 import java.util.*; public class Example2_17 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { String firstName; String lastName; int age; double weight; System.out.println("Enter first name, last name, "+ "age, and weight separated " + "by spaces."); firstName = console.next(); lastName = console.next(); age = console.nextInt(); weight = console.nextDouble(); } System.out.println("Name: " + firstName + " " + lastName); System.out.println("Age: " + age); System.out.println("Weight: " + weight); }

Java Programming: From Problem Analysis to Program Design, Second Edition 42 Input  Reading a Single Character if ch is a char variable. To input A into ch, you can use the following statement: ch = console.next().charAt(0);

Java Programming: From Problem Analysis to Program Design, Second Edition 43 Example2_18 import java.util.*; public class Example2_18{ static Scanner console = new Scanner(System.in); public static void main(String[] args) { int firstNum, secondNum; char ch; double z; firstNum = 4; System.out.println("Line 2: firstNum = “ + firstNum); secondNum = 2 * firstNum + 6; System.out.println("Line 4: firstNum = " + firstNum + ", secondNum = " + secondNum); z = (firstNum + 1) / 2.0; System.out.println("Line 6: firstNum = " + firstNum + ", secondNum = “ + secondNum + ", z = " + z); ch = 'A'; System.out.println("Line 8: firstNum = " + firstNum + ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); secondNum = console.nextInt(); System.out.println("Line 10: firstNum = " + firstNum + ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); z = console.nextDouble();

Java Programming: From Problem Analysis to Program Design, Second Edition 44 Example2_18 System.out.println("Line 12: firstNum = " + firstNum + ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); firstNum = 2 * secondNum + (int)(z); System.out.println("Line 14: firstNum = " + firstNum + ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); secondNum = secondNum + 1; System.out.println("Line 16: firstNum = " + firstNum+ ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); ch = console.next().charAt(0); System.out.println("Line 18: firstNum =" + firstNum + ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); firstNum = firstNum +(int)(ch); System.out.println("Line 20: firstNum = " + firstNum + ", secondNum = " + secondNum + ", ch = " + ch + ", z = " + z); z = firstNum - z; System.out.println("Line 22: firstNum = " + firstNum + ", secondNum = “ + secondNum + ", ch = " + ch + ", z = " + z); } }

Java Programming: From Problem Analysis to Program Design, Second Edition 45 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: From Problem Analysis to Program Design, Second Edition 46 Increment and Decrement Operators  Example : int count =1 ; count ++ ; or ++ count ; // same as count =count+1  The meaning of pre and post differ when the variable using these operators is used in an expression.  The pre-increment adds 1 to the variable before the expression is evaluated. Similarly, the pre-decrement subtracts 1 from the variable before it is evaluated in an expression while.  The post-increment adds 1 to the variable after the expression is evaluated. Similarly, post-decrement subtracts the value 1 from the variable after the expression is evaluated.

Java Programming: From Problem Analysis to Program Design, Second Edition 47 Increment and Decrement Operators Example : int x, y ; 1. x= 5 ; y = ++x ; //the value of x is incremented first then it is assigned to y.( x =6,y =6 ) 2.X= 5 ; y = x++ ; // the current value of x (5) is used to evaluate the exp. then the value of x is incremented., y =5

Java Programming: From Problem Analysis to Program Design, Second Edition 48 Increment and Decrement Operators Example : int a,b ; 3. a = 5 ; b = 2+ (++a) ; // a= 6, b = 8 4.a = 5 ; b = 2+ (a++) ; // a = 5 during the exp. Evaluation then its incremented to 6 // b = 7

Java Programming: From Problem Analysis to Program Design, Second Edition 49 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: From Problem Analysis to Program Design, Second Edition 50  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";  Consider the following statement: str = "The sum = " + (num1 + num2);  In this statement, because of the parentheses, you 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"; Strings and the Operator +

Java Programming: From Problem Analysis to Program Design, Second Edition 51 Output  Standard output object is System.out.  Methods: print println  Syntax: System.out.print(stringExp); System.out.println(stringExp); System.out.println();

Java Programming: From Problem Analysis to Program Design, Second Edition 52 Commonly Used Escape Sequences

Java Programming: From Problem Analysis to Program Design, Second Edition 53 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: From Problem Analysis to Program Design, Second Edition 54 import Statement  Used to 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: From Problem Analysis to Program Design, Second Edition 55 Creating a Java Application Program  Syntax of a class:  Syntax of the main method:

Java Programming: From Problem Analysis to Program Design, Second Edition 56 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: From Problem Analysis to Program Design, Second Edition 57 More on Assignment Statements variable = variable * (expression); is equivalent to: variable *= expression; Similarly, variable = variable + (expression); is equivalent to: variable += expression;

Java Programming: From Problem Analysis to Program Design, Second Edition 58 Programming Examples  Convert Length 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: From Problem Analysis to Program Design, Second Edition 59 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: From Problem Analysis to Program Design, Second Edition 60 Chapter Summary  To create a Java application, it is important to 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.