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
PROGRAMMING IN C UNIT II.pdfFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
PDF
THE C++ LECTURE 2 ON DATA STRUCTURES OF C++
PPTX
Java fundamentals
PPTX
Full CSE 310 Unit 1 PPT.pptx for java language
PPTX
arrays and pointers
PPTX
C++ Basics introduction to typecasting Webinar Slides 1
PPTX
Learning core java
PPT
demo1 java of demo 1 java with demo 1 java.ppt
PROGRAMMING IN C UNIT II.pdfFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
THE C++ LECTURE 2 ON DATA STRUCTURES OF C++
Java fundamentals
Full CSE 310 Unit 1 PPT.pptx for java language
arrays and pointers
C++ Basics introduction to typecasting Webinar Slides 1
Learning core java
demo1 java of demo 1 java with demo 1 java.ppt

Similar to CSC111-Chap_02.pdf (20)

PPTX
Lecture 2
PPT
Chapter 2 java
PPTX
Introduction to Java Programming
PPT
lecture2 (1).ppt variable s and operators
PPT
Data structure
PPTX
Csc240 -lecture_4
PDF
C++ PPT IN NUMERICAL METHOD FOR M.Sc PHYSICS
PDF
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
PPSX
Java session3
PPT
chapter 5.ppt
PPSX
Esoft Metro Campus - Certificate in c / c++ programming
PPTX
Visual Basic Fundamentals
PPTX
Best_of_438343817-A-PPT-on-C-language.pptx
PPTX
2. Introduction to 'C' Language (1).pptx
PPT
Md03 - part3
PPTX
Basic of Structered Programming in C psd
PPT
C the basic concepts
PPSX
Esoft Metro Campus - Programming with C++
PPT
Data Handling
PPTX
Object oriented programming1 Week 1.pptx
Lecture 2
Chapter 2 java
Introduction to Java Programming
lecture2 (1).ppt variable s and operators
Data structure
Csc240 -lecture_4
C++ PPT IN NUMERICAL METHOD FOR M.Sc PHYSICS
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
Java session3
chapter 5.ppt
Esoft Metro Campus - Certificate in c / c++ programming
Visual Basic Fundamentals
Best_of_438343817-A-PPT-on-C-language.pptx
2. Introduction to 'C' Language (1).pptx
Md03 - part3
Basic of Structered Programming in C psd
C the basic concepts
Esoft Metro Campus - Programming with C++
Data Handling
Object oriented programming1 Week 1.pptx
Ad

Recently uploaded (20)

PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
My India Quiz Book_20210205121199924.pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PPTX
Computer Architecture Input Output Memory.pptx
PDF
HVAC Specification 2024 according to central public works department
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PDF
advance database management system book.pdf
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
B.Sc. DS Unit 2 Software Engineering.pptx
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
My India Quiz Book_20210205121199924.pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Paper A Mock Exam 9_ Attempt review.pdf.
What if we spent less time fighting change, and more time building what’s rig...
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
Computer Architecture Input Output Memory.pptx
HVAC Specification 2024 according to central public works department
FORM 1 BIOLOGY MIND MAPS and their schemes
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Introduction to pro and eukaryotes and differences.pptx
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
TNA_Presentation-1-Final(SAVE)) (1).pptx
advance database management system book.pdf
AI-driven educational solutions for real-life interventions in the Philippine...
Chinmaya Tiranga quiz Grand Finale.pdf
Ad

CSC111-Chap_02.pdf

  • 1. Computer Programming I - CSC111 Chapter 2 – Basic Computation Dr. Mejdl Safran mejdl@ksu.edu.sa 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