Lecture 02 - Elementary Programming
Lecture 02 - Elementary Programming
Programming
Lecture 2: Elementary Programming
4
Declaring Variables
• Declaring a variable involves stating the variable name and its data type.
• The syntax for a declaration statement is:
datatype identifier;
• For example:
int x; // Declare x to be an
// integer variable;
char a; // Declare a to be a
// character variable;
5
Assigning a Value to a Variable
• “assigning a value to a variable” is giving a value to a variable
– assigning a value to a variable is effectively storing the value in a place in memory
corresponding to that variable
• The syntax for the assignment statement is:
identifier = value;
• For example:
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
Example 2.01 – Area of a Circle
• A program to compute the area of a circle
given its radius
ComputeArea
animation
Trace a Program Execution
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
8
animation
Trace a Program Execution
// Assign a radius
radius = 20;
allocate memory
// Compute area for area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
9
animation
Trace a Program Execution
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
10
animation
Trace a Program Execution
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
11
animation
Trace a Program Execution
// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
12
Initialization
• It is possible to declare a variable and assign it a value in one step
• For example:
int x = 1;
double d = 1.4;
• This is called initialisation (i.e. the variable is assigned its initial or first
value)
• The general syntax for a initialisation is:
datatype identifier = value;
13
Getting Input from User
• In our previous examples we have been able to create output but
none of the examples got input from the user
• Useful programs get input from users; process it and give out
desired output
• How do we get input from the console?
• Use the Scanner object
• The Scanner object can read input from the standard input
(System.in) and other sources e.g. files
• The standard input (System.in) refers to the keyboard
Using the Scanner Object
• First you create the Scanner Object
• For example:
ComputeAreaWithConsoleInput
Example 2.03 – Compute Average
ComputeAverage
Constants
• Constants are data elements whose value does not change
• Like variables constants can be declared
• The syntax for declaring a constant is:
final datatype CONSTANTNAME = VALUE;
• For example:
final double PI = 3.14159;
// compute area of circle
area = PI * radius * radius;
18
Numerical Data Types
Numeric Operators
Integer vs. Float Division
• Note: division in Java behaves differently for integers and floating point numbers
– Integer division where all operands are integers
• Integer division
– 5/2 yields an integer 2
• Float division
– 5.0/2 yields a float number 2.5
• You can find that day is Tuesday using the following expression:
Example 2.04: Display Time
• Write a program that obtains minutes from
seconds
DisplayTime
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
Increment & Decrement Operators
• Postincrement:
• Preincrement:
Number Type Conversion
• Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Conversion Rules
• When performing a binary operation involving two operands of different
types, Java automatically converts the operand based on the following
rules:
1. If one of the operands is double, the other is converted into double.
2. Otherwise, if one of the operands is float, the other is converted
into float.
3. Otherwise, if one of the operands is long, the other is converted into
long.
4. Otherwise, both operands are converted into int
Type Casting
• Type casting is converting from one data type to another.
• The syntax for type casting is:
(data type) variable
(data type) value
(data type) (expression)
• For example:
int x = (int) 3.9; (type narrowing | the fraction part is truncated)
double d = (double) 3; (type widening | range increases)
int x2 = (int) d;
int sum = (int) (2.0 + 3.5 + 4.6);
Example 2.05: Sales Tax
• Write a program that displays the sales tax
with a maximum of two digits after the
decimal point.
SalesTax
Character Data Type
• The character data type, char, is used to represent a single character.
• A character literal is enclosed in single quotation marks.
• For example:
char letter = ‘A’;
char numChar = ‘4’;
• The two statements assign character A to the char variable letter and a numerical
character 4 to the char variable numChar, respectively.
The String data type
• The char type only represents one character.
• To represent a string of characters, use the
data type called String.
• For example:
String firstname;
String lastname;
String message = “Welcome to
Message”;
String Concatenation
• A string can be joined (concatenated) to another string, a number or a
character.
• For example:
String year = “2013”;
int yr = Integer.parseInt(year);
int yr = Integer.parseInt(“2013”);
• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing Lines
• Block Styles
Appropriate Comments
• Comments help other developers (programmers) understand your
programs.
• Include your name and the date the program was written.
Naming Conventions
• Choose meaningful and descriptive names.
• Variables and method names:
– Use lowercase.
– If the name consists of several words:
• concatenate all in one
• use lowercase for the first word
• capitalize the first letter of each subsequent word in the name
– For example:
• radius
• area
• studentName
• yearOfStudy
• computeGrade
• getStudentFirstName
Naming Conventions, cont.
• Constants:
– Capitalize all letters in constants, and use underscores to connect words.
– For example:
• PI
• MAX_VALUE
• Classes:
– Capitalize the first letter of each word in the name.
– For example:
• ComputeArea
• ComputeAverage
• SalesTax
Proper Indentation and Spacing
Easy To
Read
Saves
Space
System.exit(0);
}
}
Debugging
• Logic errors are called bugs.
• This approach might work for a short, simple program. But for a large,
complex program, the most effective approach for debugging is to use a
debugger utility.
Debugger
• Debugger is a program that facilitates debugging.
– Set breakpoints.
– Display variables.
– Modify variables.
Summary
• In this lecture we have looked at:
– How to get input from users using the Scanner object
– Numeric operators