SlideShare a Scribd company logo
Computer Programming I - CSC111
Chapter 2 – Basic Computation
Dr. Mejdl Safran
mejdl@ksu.edu.sa
1
Outline
Outline
Outline
Outline
• Java program structure
• Hello program
• Saving, compiling and running Java programs
• Comments
• What is a variable?
• What is a data type?
• Basic data types
• Variables identifiers
• How to select proper types for numerical data
• Assignment statement
• Simple keyboard input/output
2
Java Program Structure
Java Program Structure
Java Program Structure
Java Program Structure
3
Java Program Structure
Java Program Structure
Java Program Structure
Java Program Structure
4
Hello Program
Hello Program
Hello Program
Hello Program
5
Saving, compiling, and running Java program
Saving, compiling, and running Java program
Saving, compiling, and running Java program
Saving, compiling, and running Java program
• Saving a Java program
‒ A file having a name same as the class name should be used to save the
program. The extension of this file is “.java”
•Compiling a Java program
‒ Call the Java compiler javac:
‒ javac HelloProgram.java
‒ generates a file called “HelloProgram.class” (the bytecode)
•Running a Java program
‒ Call JVM java:
‒ java HelloProgram
6
Comments
Comments
Comments
Comments
• The best programs are self-documenting
• Clean style
• Well-chosen names
•Comments are written into a program as needed to
explain the program
•They are useful for programmer, but they are ignored
by the compiler
7
Comments
Comments
Comments
Comments
• A comment can begin with //
• Everything after these symbols and to the end of the line is
treated as a comment
8
Comments
Comments
Comments
Comments
• A comment can begin with /* and end with */
• Everything between these symbols is treated as a comment
9
Hello Program
Hello Program
Hello Program
Hello Program
10
Comments
Comments
Comments
Comments
• A javadoc comment, begins with /** and end with */
• It can be extracted automatically from Java software
11
When to use comments
When to use comments
When to use comments
When to use comments
• Begin each program file with an explanatory comment
‒What the program does
‒The name of the author
‒Contact information for the author
‒Date of the last modification
• Provide only those comments which the expected
reader of the program file will need in order to
understand it.
12
Sum program
Sum program
Sum program
Sum program
13
Variables
Variables
Variables
Variables
•Variables are used to store (represent) data such as
numbers and letters.
• Think of them as places to store data.
• They are implemented as memory locations.
•The data stored by a variable is called its value.
• The value is stored in the memory location.
•Its value can be changed.
14
Variables and values
Variables and values
Variables and values
Variables and values
• Variables:
numberOfStudents
studentGPA
age
• Assigning values:
numberOfStudents = 100 ;
numberOfStudents = numberOfStudents - 1 ;
15
Naming and declaring variables
Naming and declaring variables
Naming and declaring variables
Naming and declaring variables
• Choose names that are helpful such as count or speed, but not c or s.
• When you declare a variable, you provide its name and type
• without initial value
int count, sum;
double avg;
• with initial value
int count = 5, sum = 200;
double avg = sum / count;
• A variable's type determines what kinds of values it can hold (int,
double, char, etc.).
• A variable must be declared before it is used.
16
Syntax and examples
Syntax and examples
Syntax and examples
Syntax and examples
• Syntax
type variable_1, variable_2, …;
•Examples
int styleChoice, numberOfChecks;
double balance, interestRate;
char jointOrIndividual;
17
Data types in Java
Data types in Java
Data types in Java
Data types in Java
• In Java, you have to specify a data type of variables that tells
what kind of data to be stored in it.
• Two kinds of data types:
1) Primitive data types: for single number or single letter, e.g. int
2) Class types: for objects of a class, e.g. class type String
18
Primitive types
Primitive types
Primitive types
Primitive types
19
• Four integer types (byte, short, int, and long)
• int is most common
• Two floating-point types (float and double)
• double is more common
• One character type (char)
• One Boolean type (Boolean)
Primitive data types
Primitive data types
Primitive data types
Primitive data types
20
Primitive data types
Primitive data types
Primitive data types
Primitive data types
21
Primitive data types never allow us to
store multiple values of same type!
(one value at a time)
int a; // valid
a = 10; // valid
a = 10, 20, 30; // invalid
Examples of primitive values
Examples of primitive values
Examples of primitive values
Examples of primitive values
22
• Integer types
0 -1 365 12000
• Floating-point types
0.99 -22.8 3.14159 5.0
• Character type
'a' 'A' '#' ' '
• Boolean type
true false
Java identifiers
Java identifiers
Java identifiers
Java identifiers
• The name of something in a java program such as a variable,
class, or method, is called an identifier.
• Identifiers may contain only
• Letters
• Digits (0 through 9)
• The underscore character (_)
• And the dollar sign symbol ($) which has a special meaning (avoid it)
• The first character cannot be a digit.
23
Java identifiers
Java identifiers
Java identifiers
Java identifiers
• Identifiers may not contain any spaces, dots (.), asterisks (*),
or other characters:
7-11 netscape.com util.* (not allowed)
• Identifiers can be arbitrarily long.
• Since Java is case sensitive, stuff, Stuff, and STUFF
are different identifiers.
24
Keyword or reserved words
Keyword or reserved words
Keyword or reserved words
Keyword or reserved words
• Words such as if are called keywords or reserved words and
have special, predefined meanings.
• Cannot be used as identifiers.
25
Constant declaration
Constant declaration
Constant declaration
Constant declaration
• A constant is a variable whose value cannot change once it has been assigned.
• Syntax
final type constIdentifer = literal | expression;
• Examples
final double PI = 3.14159;
final int MONTH_IN_YEAR = 12;
final int MAX = 1024;
final int MIN = 128;
final double AVG = (MAX + MIN)/2;
26
Naming conventions
Naming conventions
Naming conventions
Naming conventions
• Class types begin with an uppercase letter
(e.g. String).
• Primitive types begin with a lowercase letter (e.g. int).
• Variables:
• All lowercase letters, capitalizing the first letter of each word in a multiword
identifier, expect for the first word (e.g. myName, myBalance).
•Constants:
• All uppercase letters, separating words within multiword identifier with the
underscore symbol (e.g., IP, MONTH_IN_YEAR).
27
Where to declare variables
Where to declare variables
Where to declare variables
Where to declare variables
• Declare a variable
• Just before it is used or
• At the beginning of the section of your program that is
enclosed in {}.
public static void main(String[] args)
{ /* declare variables here */
. . .
}
28
Select
Select
Select
Select proper types for numerical data
proper types for numerical data
proper types for numerical data
proper types for numerical data
• Define the following variables for a phone application:
‒ Number of users
‒ Number of photos
‒ Number of comments
‒ Average number of active users in a week
‒ Is the app available?
‒ Version
‒ User’s gender
‒ Account balance
‒ Max number of photos allowed
29
• Define the following variables for a phone application:
‒ Number of users (int)
‒ Number of photos (int)
‒ Number of comments (int)
‒ Average number of active users in a week (double)
‒ Is the app available? (boolean)
‒ Version (float or double)
‒ User’s gender (char)
‒ Account balance (double)
‒ Max number of photos allowed (final int)
Assignment
Assignment
Assignment
Assignment statements
statements
statements
statements
• An assignment statement is used to assign a value to a
variable.
answer = 42;
•The "equal sign" is called the assignment operator.
•We say, "The variable named answer is assigned a
value of 42," or more simply, "answer is assigned
42."
30
Assignment
Assignment
Assignment
Assignment statements
statements
statements
statements
• Syntax
variable = expression
where expression can be another variable, a
literal or constant (such as a number), or something
more complicated which combines variables and
literals using operators
(such as + and -)
31
Assignment
Assignment
Assignment
Assignment examples
examples
examples
examples
amount = 3.99;
firstInitial = 'W';
score = numberOfCards + handicap;
eggsPerBasket = eggsPerBasket - 2;
32
Assignment
Assignment
Assignment
Assignment evaluation
evaluation
evaluation
evaluation
• The expression on the right-hand side of the
assignment operator (=) is evaluated first.
• The result is used to set the value of the variable on
the left-hand side of the assignment operator.
avg = sum / count;
counter = counter - 2;
33
Initializing v
Initializing v
Initializing v
Initializing variables
ariables
ariables
ariables
• A variable that has been declared, but no yet given a
value is said to be uninitialized.
• Uninitialized class variables have the value null.
•Uninitialized primitive variables may have a default
value.
•It's good practice not to rely on a default value.
34
Initializing v
Initializing v
Initializing v
Initializing variables
ariables
ariables
ariables
• To protect against an uninitialized variable (and to
keep the compiler happy), assign a value at the time
the variable is declared.
•Examples:
int count = 0;
char grade = 'A';
35
Initializing v
Initializing v
Initializing v
Initializing variables
ariables
ariables
ariables
• syntax
type variable_1 = expression_1,
variable_2 = expression_2, …;
36
Simple input
Simple input
Simple input
Simple input
• Sometimes the data needed
for a computation are
obtained from the user at
run time.
• Keyboard input requires:
import java.util.Scanner
at the beginning of the file
37
Simple input
Simple input
Simple input
Simple input
• Data can be entered from the keyboard using
Scanner keyboard = new Scanner(System.in);
followed by
num1 = keyboard.nextInt();
which read one int value from the keyboard and
assign it to num1
38
Simple input
Simple input
Simple input
Simple input
39
Simple screen output
Simple screen output
Simple screen output
Simple screen output
40
Common Scanner methods
Common Scanner methods
Common Scanner methods
Common Scanner methods
41
• Last two methods will be discussed and used when we study the class
String

More Related Content

PDF
Java Basics.pdf
EdFeranil
 
PPTX
Java fundamentals
Jayfee Ramos
 
PPT
Unit 1: Primitive Types - Variables and Datatypes
agautham211
 
PDF
Control structure repetition Tito Lacbayen
LacbayenEchaviaTitoJ
 
PPSX
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
PPT
a basic java programming and data type.ppt
GevitaChinnaiah
 
PPTX
Introduction to computer science
umardanjumamaiwada
 
Java Basics.pdf
EdFeranil
 
Java fundamentals
Jayfee Ramos
 
Unit 1: Primitive Types - Variables and Datatypes
agautham211
 
Control structure repetition Tito Lacbayen
LacbayenEchaviaTitoJ
 
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
a basic java programming and data type.ppt
GevitaChinnaiah
 
Introduction to computer science
umardanjumamaiwada
 

Similar to CSC111-Chap_02.pdf (20)

PPTX
lecture 6
umardanjumamaiwada
 
PPT
Presentation on programming language on java.ppt
HimambashaShaik
 
PPT
demo1 java of demo 1 java with demo 1 java.ppt
FerdieBalang
 
PPT
Introduction to java programming with Fundamentals
rajipe1
 
PPT
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
PPT
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
PPT
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
PPT
java programming for engineering students_Ch1.ppt
RasheedaAmeen
 
PPT
Programming with Java - Essentials to program
leaderHilali1
 
PPT
Java Concepts with object oriented programming
KalpeshM7
 
PPTX
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
rishiskj
 
PDF
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
RahulKumar342376
 
PPTX
Object oriented programming1 Week 1.pptx
MirHazarKhan1
 
PPTX
Class 8 - Java.pptx
sreedevi143432
 
PPT
Basic elements of java
Ahmad Idrees
 
PPT
Introduction to-programming
BG Java EE Course
 
PPTX
Modern_2.pptx for java
MayaTofik
 
PPTX
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
PDF
Programming in Java: Storing Data
Martin Chapman
 
PPTX
Introduction to Java Programming
One97 Communications Limited
 
lecture 6
umardanjumamaiwada
 
Presentation on programming language on java.ppt
HimambashaShaik
 
demo1 java of demo 1 java with demo 1 java.ppt
FerdieBalang
 
Introduction to java programming with Fundamentals
rajipe1
 
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
java programming for engineering students_Ch1.ppt
RasheedaAmeen
 
Programming with Java - Essentials to program
leaderHilali1
 
Java Concepts with object oriented programming
KalpeshM7
 
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
rishiskj
 
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
RahulKumar342376
 
Object oriented programming1 Week 1.pptx
MirHazarKhan1
 
Class 8 - Java.pptx
sreedevi143432
 
Basic elements of java
Ahmad Idrees
 
Introduction to-programming
BG Java EE Course
 
Modern_2.pptx for java
MayaTofik
 
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
Programming in Java: Storing Data
Martin Chapman
 
Introduction to Java Programming
One97 Communications Limited
 
Ad

Recently uploaded (20)

PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
CDH. pptx
AneetaSharma15
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
CDH. pptx
AneetaSharma15
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Ad

CSC111-Chap_02.pdf

  • 1. Computer Programming I - CSC111 Chapter 2 – Basic Computation Dr. Mejdl Safran [email protected] 1
  • 2. Outline Outline Outline Outline • Java program structure • Hello program • Saving, compiling and running Java programs • Comments • What is a variable? • What is a data type? • Basic data types • Variables identifiers • How to select proper types for numerical data • Assignment statement • Simple keyboard input/output 2
  • 3. Java Program Structure Java Program Structure Java Program Structure Java Program Structure 3
  • 4. Java Program Structure Java Program Structure Java Program Structure Java Program Structure 4
  • 5. Hello Program Hello Program Hello Program Hello Program 5
  • 6. Saving, compiling, and running Java program Saving, compiling, and running Java program Saving, compiling, and running Java program Saving, compiling, and running Java program • Saving a Java program ‒ A file having a name same as the class name should be used to save the program. The extension of this file is “.java” •Compiling a Java program ‒ Call the Java compiler javac: ‒ javac HelloProgram.java ‒ generates a file called “HelloProgram.class” (the bytecode) •Running a Java program ‒ Call JVM java: ‒ java HelloProgram 6
  • 7. Comments Comments Comments Comments • The best programs are self-documenting • Clean style • Well-chosen names •Comments are written into a program as needed to explain the program •They are useful for programmer, but they are ignored by the compiler 7
  • 8. Comments Comments Comments Comments • A comment can begin with // • Everything after these symbols and to the end of the line is treated as a comment 8
  • 9. Comments Comments Comments Comments • A comment can begin with /* and end with */ • Everything between these symbols is treated as a comment 9
  • 10. Hello Program Hello Program Hello Program Hello Program 10
  • 11. Comments Comments Comments Comments • A javadoc comment, begins with /** and end with */ • It can be extracted automatically from Java software 11
  • 12. When to use comments When to use comments When to use comments When to use comments • Begin each program file with an explanatory comment ‒What the program does ‒The name of the author ‒Contact information for the author ‒Date of the last modification • Provide only those comments which the expected reader of the program file will need in order to understand it. 12
  • 13. Sum program Sum program Sum program Sum program 13
  • 14. Variables Variables Variables Variables •Variables are used to store (represent) data such as numbers and letters. • Think of them as places to store data. • They are implemented as memory locations. •The data stored by a variable is called its value. • The value is stored in the memory location. •Its value can be changed. 14
  • 15. Variables and values Variables and values Variables and values Variables and values • Variables: numberOfStudents studentGPA age • Assigning values: numberOfStudents = 100 ; numberOfStudents = numberOfStudents - 1 ; 15
  • 16. Naming and declaring variables Naming and declaring variables Naming and declaring variables Naming and declaring variables • Choose names that are helpful such as count or speed, but not c or s. • When you declare a variable, you provide its name and type • without initial value int count, sum; double avg; • with initial value int count = 5, sum = 200; double avg = sum / count; • A variable's type determines what kinds of values it can hold (int, double, char, etc.). • A variable must be declared before it is used. 16
  • 17. Syntax and examples Syntax and examples Syntax and examples Syntax and examples • Syntax type variable_1, variable_2, …; •Examples int styleChoice, numberOfChecks; double balance, interestRate; char jointOrIndividual; 17
  • 18. Data types in Java Data types in Java Data types in Java Data types in Java • In Java, you have to specify a data type of variables that tells what kind of data to be stored in it. • Two kinds of data types: 1) Primitive data types: for single number or single letter, e.g. int 2) Class types: for objects of a class, e.g. class type String 18
  • 19. Primitive types Primitive types Primitive types Primitive types 19 • Four integer types (byte, short, int, and long) • int is most common • Two floating-point types (float and double) • double is more common • One character type (char) • One Boolean type (Boolean)
  • 20. Primitive data types Primitive data types Primitive data types Primitive data types 20
  • 21. Primitive data types Primitive data types Primitive data types Primitive data types 21 Primitive data types never allow us to store multiple values of same type! (one value at a time) int a; // valid a = 10; // valid a = 10, 20, 30; // invalid
  • 22. Examples of primitive values Examples of primitive values Examples of primitive values Examples of primitive values 22 • Integer types 0 -1 365 12000 • Floating-point types 0.99 -22.8 3.14159 5.0 • Character type 'a' 'A' '#' ' ' • Boolean type true false
  • 23. Java identifiers Java identifiers Java identifiers Java identifiers • The name of something in a java program such as a variable, class, or method, is called an identifier. • Identifiers may contain only • Letters • Digits (0 through 9) • The underscore character (_) • And the dollar sign symbol ($) which has a special meaning (avoid it) • The first character cannot be a digit. 23
  • 24. Java identifiers Java identifiers Java identifiers Java identifiers • Identifiers may not contain any spaces, dots (.), asterisks (*), or other characters: 7-11 netscape.com util.* (not allowed) • Identifiers can be arbitrarily long. • Since Java is case sensitive, stuff, Stuff, and STUFF are different identifiers. 24
  • 25. Keyword or reserved words Keyword or reserved words Keyword or reserved words Keyword or reserved words • Words such as if are called keywords or reserved words and have special, predefined meanings. • Cannot be used as identifiers. 25
  • 26. Constant declaration Constant declaration Constant declaration Constant declaration • A constant is a variable whose value cannot change once it has been assigned. • Syntax final type constIdentifer = literal | expression; • Examples final double PI = 3.14159; final int MONTH_IN_YEAR = 12; final int MAX = 1024; final int MIN = 128; final double AVG = (MAX + MIN)/2; 26
  • 27. Naming conventions Naming conventions Naming conventions Naming conventions • Class types begin with an uppercase letter (e.g. String). • Primitive types begin with a lowercase letter (e.g. int). • Variables: • All lowercase letters, capitalizing the first letter of each word in a multiword identifier, expect for the first word (e.g. myName, myBalance). •Constants: • All uppercase letters, separating words within multiword identifier with the underscore symbol (e.g., IP, MONTH_IN_YEAR). 27
  • 28. Where to declare variables Where to declare variables Where to declare variables Where to declare variables • Declare a variable • Just before it is used or • At the beginning of the section of your program that is enclosed in {}. public static void main(String[] args) { /* declare variables here */ . . . } 28
  • 29. Select Select Select Select proper types for numerical data proper types for numerical data proper types for numerical data proper types for numerical data • Define the following variables for a phone application: ‒ Number of users ‒ Number of photos ‒ Number of comments ‒ Average number of active users in a week ‒ Is the app available? ‒ Version ‒ User’s gender ‒ Account balance ‒ Max number of photos allowed 29 • Define the following variables for a phone application: ‒ Number of users (int) ‒ Number of photos (int) ‒ Number of comments (int) ‒ Average number of active users in a week (double) ‒ Is the app available? (boolean) ‒ Version (float or double) ‒ User’s gender (char) ‒ Account balance (double) ‒ Max number of photos allowed (final int)
  • 30. Assignment Assignment Assignment Assignment statements statements statements statements • An assignment statement is used to assign a value to a variable. answer = 42; •The "equal sign" is called the assignment operator. •We say, "The variable named answer is assigned a value of 42," or more simply, "answer is assigned 42." 30
  • 31. Assignment Assignment Assignment Assignment statements statements statements statements • Syntax variable = expression where expression can be another variable, a literal or constant (such as a number), or something more complicated which combines variables and literals using operators (such as + and -) 31
  • 32. Assignment Assignment Assignment Assignment examples examples examples examples amount = 3.99; firstInitial = 'W'; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; 32
  • 33. Assignment Assignment Assignment Assignment evaluation evaluation evaluation evaluation • The expression on the right-hand side of the assignment operator (=) is evaluated first. • The result is used to set the value of the variable on the left-hand side of the assignment operator. avg = sum / count; counter = counter - 2; 33
  • 34. Initializing v Initializing v Initializing v Initializing variables ariables ariables ariables • A variable that has been declared, but no yet given a value is said to be uninitialized. • Uninitialized class variables have the value null. •Uninitialized primitive variables may have a default value. •It's good practice not to rely on a default value. 34
  • 35. Initializing v Initializing v Initializing v Initializing variables ariables ariables ariables • To protect against an uninitialized variable (and to keep the compiler happy), assign a value at the time the variable is declared. •Examples: int count = 0; char grade = 'A'; 35
  • 36. Initializing v Initializing v Initializing v Initializing variables ariables ariables ariables • syntax type variable_1 = expression_1, variable_2 = expression_2, …; 36
  • 37. Simple input Simple input Simple input Simple input • Sometimes the data needed for a computation are obtained from the user at run time. • Keyboard input requires: import java.util.Scanner at the beginning of the file 37
  • 38. Simple input Simple input Simple input Simple input • Data can be entered from the keyboard using Scanner keyboard = new Scanner(System.in); followed by num1 = keyboard.nextInt(); which read one int value from the keyboard and assign it to num1 38
  • 39. Simple input Simple input Simple input Simple input 39
  • 40. Simple screen output Simple screen output Simple screen output Simple screen output 40
  • 41. Common Scanner methods Common Scanner methods Common Scanner methods Common Scanner methods 41 • Last two methods will be discussed and used when we study the class String