0% found this document useful (0 votes)
19 views52 pages

Java PPT Ch02

Uploaded by

Hol Gh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views52 pages

Java PPT Ch02

Uploaded by

Hol Gh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

Chapter 2:

Using Data
2 Objectives
 Use constants and variables
 Use integer data type
 Use the boolean data type
 Use floating-point data types
 Use the char data type

Java Programming, Sixth Edition


3 Objectives (cont'd.)

 Display data and perform arithmetic


 Understand numeric type conversion
 Use the Scanner class to accept keyboard input
 Use the JOptionPane class for GUI input

Java Programming, Sixth Edition


Using Constants and
4
Variables
 Constant
‫ال يمكن تغييره أثناء تشغيل البرنامج‬
 Cannot be changed while program is running
 Literal constant
 Value taken literally at each use
‫القيمة المأخوذة حرفيا في كل استخدام‬
 Numeric constant
 Opposed to a literal constant
‫على عكس الثابت الحرفي‬
 Unnamed constant
 No identifier is associated with it
‫ال يوجد معرف مرتبط به‬

Java Programming, Sixth Edition


Using Constants and Variables
5 (cont'd.)
 Variable
 Named memory location ‫موقع الذاكرة المسمى‬
 Use to store value ‫استخدم لتخزين القيمة‬
 Can hold only one value at a time ‫يمكن أن تحتوي على قيمة واحدة فقط في كل مرة‬

 Value can change


 Data type
 Type of data that can be stored ‫نوع البيانات التي يمكن تخزينها‬
 How much memory item occupies ‫مقدار عنصر الذاكرة الذي يشغله‬
 What types of operations can be performed on data
‫ما هي أنواع العمليات التي يمكن إجراؤها على البيانات‬
Using Constants and Variables
6
(cont'd.)

 Primitive type
 Simple data type

 Reference types
 More complex data types

Java Programming, Sixth Edition


7 Using Constants and
Variables (cont'd.)

Java Programming, Sixth Edition


8
Declaring Variables

 Name variables
 Using naming rules for legal class identifiers‫استخدام قواعد التسمية لمعرفات‬
‫الفئات القانونية‬

 Variable declaration
 Statement that reserves named memory location‫العبارة التي تحتفظ‬
‫بموقع الذاكرة المسماة‬

 Includes: ‫يتضمن‬
 Data type
 Identifier ‫المعرف‬
 Optional assignment operator and assigned value ‫عامل تشغيل التعيين االختياري‬
‫والقيمة المعينة‬

 Ending semicolon
9
Declaring Variables
 (cont'd.)
Assignment operator ‫مهمة التشغيل‬
 Equal sign (=)
 Value to right assigned to variable on left ‫القيمة إلى اليمين المعينة إلى المتغير على‬
‫اليسار‬

 Initialization‫التهيئه‬
 Assignment made when declaring variable ‫التعيين الذي تم إجراؤه عند اإلعالن عن‬
‫المتغير‬

 Assignment ‫مهمة‬
 Assignment made after variable declared ‫الذي تم إجراؤه بعد إعالن المتغير‬

 Associativity ‫االرتباط‬
 Order in which operands used with operators ‫ترتيب المعامالت المستخدمة مع‬
‫عوامل التشغيل‬
10 Declaring Variables
(cont'd.)
 Declare multiple variables of same type in
separate statements on different lines ‫اإلعالن‬
‫عن متغيرات متعددة من نفس النوع في عبارات منفصلة على أسطر مختلفة‬

int myAge = 25;


int yourAge = 19;

 Declare variables of different types


 Must use separate statement for each type
‫يجب استخدام عبارات منفصل لكل نوع‬
11 Declaring Named Constants
 Named constant
 Should not change during program execution ‫يجب‬
‫أال يتغير أثناء تنفيذ البرنامج‬

 Has data type, name, and value


 Data type preceded by keyword final ‫نوع البيانات‬
‫مسبوقا بالكلمة الرئيسية النهائية‬

 Can be assigned a value only once ‫يمكن تعيين قيمة مرة‬


‫واحدة فقط‬

 Conventionally given identifiers using all


uppercase letters ‫المعرفات المعطاة تقليديا باستخدام جميع األحرف الكبيرة‬
12 Declaring Named Constants
(cont'd.)
 Reasons for using named constants
 Make programs easier to read and
understand ‫تسهيل قراءة البرامج وفهمها‬
 Change value at one location within program
‫تغيير القيمة في موقع واحد داخل البرنامج‬
 Reduce typographical errors ‫تقليل األخطاء المطبعية‬
 Stand out as separate from variables ‫تبرز كمنفصلة‬
‫عن المتغيرات‬

Java Programming, Sixth Edition


13 The Scope of Variables and
Constants
 Scope
 Area in which it is visible to a program and in
which you can refer to it using its simple
identifier ‫المنطقة التي يكون فيها مرئيا للبرنامج ويمكنك الرجوع إليه‬
‫باستخدام معرفه البسيط‬

 A variable or constant is in scope from the


point it is declared
 Until the end of the block of code in which the
declaration lies

Java Programming, Sixth Edition


14 Pitfall: Forgetting that a
Variable Holds One Value at a
Time
 Each constant can hold only
one value
 For duration of program
 Switch values of two
variables
 Use third variable
15 Learning About Integer
Data Types
 Type int
 Stores integers, or whole numbers
 Value from –2,147,483,648 to +2,147,483,647

 Variations
‫ االختالفات‬of the integer type
 byte
 short
 Long

 Choose appropriate types for variables

Java Programming, Sixth Edition


16 Learning About Integer
Data Types (cont'd.)

Java Programming, Sixth Edition


17 Using the boolean Data
Type
 Boolean logic
‫المقارنات‬
 Based on true-or-false comparisons
 boolean variable
 Can hold only one of two values
 true or false

boolean isItPayday = false;


 Relational operator (comparison operator)
)‫عامل التشغيل العالئقي (عامل المقارنة‬
 Compares two items ‫يقارن بين عنصرين‬

Java Programming, Sixth Edition


18 Using the boolean Data
Type (cont'd.)

Java Programming, Sixth Edition


Learning About Floating-
19
Point Data Types

 Floating-point number
 Contains decimal positions
 Floating-point data types
 float
 double
 Significant digits
 Refers to mathematical accuracy
20 Learning About Floating-
Point Data Types (cont'd.)

Java Programming, Sixth Edition


21 Working with the char Data
Type
 char data type
 Holds any single character
 Place constant character values within single
quotation marks
char myMiddleInitial = 'M';
 String
 Built-in class
 Stores and manipulates character strings
 String constants written between double quotation marks

Java Programming, Sixth Edition


22 Working with the char Data
Type (cont'd.)
 Escape sequence
 Begins with backslash followed by character
 Represents single nonprinting character
char aNewLine = '\n';
 Produce console output on multiple
lines in command window
 Use newline escape sequence
 Use println() method multiple times

Java Programming, Sixth Edition


23 Working with the char Data
Type (cont'd.)

Java Programming, Sixth Edition


24 Displaying Data and
Performing Arithmetic
 print() or println() statement
 Alone or in combination with string
 Concatenated
 Numeric variable concatenated to String
using plus sign
 Entire expression becomes String
 println() method can accept number
or String

Java Programming, Sixth Edition


25 Displaying Data and
Performing Arithmetic (cont'd.)

 Use dialog box to display


values

JOptionPane.showMessageDialog(
)
 Does not accept single numeric variable

 Null String
 Empty string: “”

Java Programming, Sixth Edition


26 Displaying Data and
Performing Arithmetic (cont'd.)

Java Programming, Sixth Edition


27 Performing Arithmetic

 Arithmetic operators
 Perform calculations with values in programs
 Operand
 Value used on either side of operator
 Integer division
 Integer constants or integer variables
 Result is integer
 Fractional part of result lost

Java Programming, Sixth Edition


28 Performing Arithmetic
(cont'd.)

Java Programming, Sixth Edition


29 Performing Arithmetic
(cont'd.)
 Operator precedence
 Rules for order in which parts of mathematical
expression are evaluated
 First multiplication, division, and modulus
 Then addition or subtraction

Java Programming, Sixth Edition


30 Writing Arithmetic
Statements Efficiently
 Avoid unnecessary repetition of arithmetic statements
 Example of inefficient calculation
stateWithholding = hours * rate *
STATE_RATE;
federalWithholding = hours * rate *
FED_RATE;
 Example of efficient calculation
grossPay = hours * rate;
stateWithholding = grossPay * STATE_RATE;
federalWithholding = grossPay * FED_RATE;

Java Programming, Sixth Edition


31 Pitfall: Not Understanding
Imprecision in Floating-Point
Numbers
 Integer values are exact
 But floating-point numbers frequently are only
approximations
 Imprecision leads to several problems
 Floating-point output might not look like what you
expect or want
 Comparisons with floating-point numbers might not be
what you expect or want

Java Programming, Sixth Edition


32 Understanding Numeric-
Type Conversion
 Arithmetic with variables or constants of same type
 Result of arithmetic retains same type
 Arithmetic operations with operands of unlike types
 Java chooses unifying type for result
 Unifying type
 Type to which all operands in expression are converted
for compatibility

Java Programming, Sixth Edition


33 Understanding Numeric-
Type Conversion (cont'd.)
 Order for establishing unifying types between two
variables
 1. double
 2. float
 3. long
 4. int
 Type casting
 Forces value of one data type to be used as value of
another type

Java Programming, Sixth Edition


34 Understanding Numeric-
Type Conversion (cont'd.)
 Cast operator
 Place desired result type in parentheses
 Explicit conversion
 Do not need to perform cast when assigning value
to higher unifying type

Java Programming, Sixth Edition


35 Using the Scanner Class for
Keyboard Input
 System.in object
 Standard input device
 Normally the keyboard
 Access using Scanner class
 Scanner object
 Breaks input into units called tokens

Java Programming, Sixth Edition


36 Using the Scanner Class for
Keyboard Input (cont'd.)

Java Programming, Sixth Edition


37 Using the Scanner Class for
Keyboard Input (cont'd.)

Java Programming, Sixth Edition


38 Pitfall: Using nextLine()
Following One of the Other
Scanner Input Methods
 Problem when using one numeric Scanner class
retrieval method or next()method
 Before using nextLine()method
 Keyboard buffer
 After any numeric or next() input:
 Add extra nextLine()method call
 Will retrieve abandoned Enter key character

Java Programming, Sixth Edition


39 Using the JOptionPane
Class for GUI Input
 Dialog boxes used to accept user input
 Input dialog
 Confirm dialog

Java Programming, Sixth Edition


40 Using Input Dialog Boxes

 Input dialog box


 Asks question
 Provides text field in which user can enter response
 showInputDialog() method
 Six overloaded versions
 Returns String representing user’s response
 Prompt
 Message requesting user input

Java Programming, Sixth Edition


41 Using Input Dialog Boxes
(cont'd.)

Java Programming, Sixth Edition


42 Using Input Dialog Boxes
(cont'd.)

Java Programming, Sixth Edition


43 Using Input Dialog Boxes
(cont'd.)
 showInputDialog()
 Version requires four arguments
 Parent component
 Message
 Title
 Type of dialog box

 Convert String to int or double


 Use methods from built-in Java classes Integer and
Double

Java Programming, Sixth Edition


44 Using Input Dialog Boxes
(cont'd.)
 Type-wrapper classes
 Each primitive type has corresponding class contained
in java.lang package
 Include methods to process primitive type values
Integer.parseInt()
Double.parseDouble()

Java Programming, Sixth Edition


45 Using Confirm Dialog Boxes

 Confirm dialog box


 Displays options Yes, No, and Cancel
 showConfirmDialog() method in JOptionPane
class
 Four overloaded versions available
 Returns integer containing either:
JOptionPane.YES_OPTION
JOptionPane.NO_OPTION
JOptionPane.CANCEL_OPTION

Java Programming, Sixth Edition


46 Using Confirm Dialog Boxes
(cont'd.)
 Create confirm dialog box with five arguments
 Parent component
 Prompt message
 Title
 Integer that indicates which option button to show
 Integer that describes kind of dialog box

Java Programming, Sixth Edition


47 Using Confirm Dialog Boxes
(cont'd.)

Java Programming, Sixth Edition


48 You Do It

 Working with numeric values


 Accepting user data
 Performing arithmetic
 Experimenting with Java programs

Java Programming, Sixth Edition


49 Don’t Do It

 Don’t attempt to assign a literal constant floating-


point number
 Don’t forget precedence rules
 Don’t forget that integer division results in an
integer
 Don’t attempt to assign a constant decimal value to
an integer using a leading 0
 Don’t use a single equal sign (=) in a Boolean
comparison for equality
 Don’t try to store a string of characters in a char

Java Programming, Sixth Edition


50 Don’t Do It (cont'd.)

 Don’t forget that, when a String and a numeric


value are concatenated, the resulting expression is
a string
 Don’t forget to consume the Enter key after numeric
input using the Scanner class when a
nextLine()method call follows
 Don’t forget to use the appropriate import
statement when using the Scanner or JOptionPane
class

Java Programming, Sixth Edition


51 Summary

 Variables
 Named memory locations
 Primitive data types
 Standard arithmetic operators for integers
+, _, *, /, and %
 Boolean type
true or false value
 Relational operators
>, <, ==, >=, <=, and !=

Java Programming, Sixth Edition


52 Summary (cont'd.)

 Floating-point data types


 float
 double
 char data type
 Scanner
 Access keyboard input
 JOptionPane
 Confirm dialog
 Input dialog

Java Programming, Sixth Edition

You might also like