0% found this document useful (0 votes)
35 views

Lecture 02 - Elementary Programming

This document provides an overview of elementary programming concepts including variables, constants, data types, operators, and errors. It discusses getting input from users using the Scanner class and shows examples of programs that compute the area of a circle and average of numbers entered by the user. The key points covered are declaring and initializing variables, primitive data types, arithmetic operators, and using Scanner to get user input.

Uploaded by

Lusper Mhango
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lecture 02 - Elementary Programming

This document provides an overview of elementary programming concepts including variables, constants, data types, operators, and errors. It discusses getting input from users using the Scanner class and shows examples of programs that compute the area of a circle and average of numbers entered by the user. The key points covered are declaring and initializing variables, primitive data types, arithmetic operators, and using Scanner to get user input.

Uploaded by

Lusper Mhango
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Introduction to Computer

Programming
Lecture 2: Elementary Programming

The slides in this lecture are based on D. Liang Chapter 2


Objectives
• In this lecture we are going to look at:
– How to get input from users
– Variables
– Constants
– Identifiers (names of variables, constants, classes, etc)
– Java primitive data types
– Numeric operators
– String data type
– Naming conventions and programming style
– Syntax errors, logic errors and runtime errors
Variables
• A variable is used to store data in a program
• A variable is a data element whose value can change
• A variable is allocated a space in memory
• A variable has a name (also called identifier)
• A variable has a data type (can only hold data of a particular type e.g. integers)
• For example:
Data Element Kind of Data Identifier Data Type
Student age Integer age, studentAge int
Student first name String of fname, firstName, String
alphabetical student1stName
characters
Employee Salary floating point salary, empSalary double, float
number
Identifiers
• Identifiers are simply names.
• An identifier is a sequence of characters that consist of letters,
digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a dollar
sign ($). It cannot start with a digit.
– An identifier cannot be a reserved word. (See Appendix A in
Liang, “Java Keywords,” for a list of reserved words).
• An identifier cannot be true, false, or
null.
• An identifier can be of any length.

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;

double radius; // Declare radius to


// be a double variable;

char a; // Declare a to be a
// character variable;

• NOTE: a variable is Java must be declared before it can be used.

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

public class ComputeArea { allocate memory


/** Main method */ for radius
public static void main(String[] args) {
double radius; radius no value
double area;

// 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

public class ComputeArea {


/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// 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

public class ComputeArea { assign 20 to radius


/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area;
area no value
// 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);
}
}

10
animation
Trace a Program Execution

public class ComputeArea {


/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// Compute area compute area and assign


area = radius * radius * 3.14159; it to variable area

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

11
animation
Trace a Program Execution

public class ComputeArea {


/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// 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

• The general statement for creating a Scanner object is:

Scanner identifier = new Scanner(source);

• For example:

Scanner input = new Scanner(System.in);

• Then use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(),


nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte,
short, int, long, float, double, or boolean value.

• For example, to get the age and name of a student:

Scanner input = new Scanner(System.in);

System.out.print("Enter your age: ");

age = input.nextInt(); // will work if age is declared before

System.out.print("Enter your name: ");

name = input.next(); // will work if name is declared before


Example 2.02 – Area Using User Input

• This program lets the user enter the radius of


a circle and computes its area.

ComputeAreaWithConsoleInput
Example 2.03 – Compute Average

• This program lets the user enter three


numbers and computes their 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

– Float division where at least one operand is a floating point number

• Integer division
– 5/2 yields an integer 2

• Float division
– 5.0/2 yields a float number 2.5

– 5/2.0 yields a float number 2.5

– 5.0/2.0 yields a float number 2.5


Remainder (Modulus) Operator

• The remainder operator is very useful in programming


• For example:
– an even number % 2 yields 0
– an odd number % 2 yields 1
– So you can use this to determine whether a number is even or
odd
• Question: Suppose today is Saturday and you and your friends are
going to meet in 10 days. What day is in 10 days?
Remainder Operator
• Question: Suppose today is Saturday and you and your friends are going
to meet in 10 days. What day is in 10 days?

• 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

• Exercise: modify the program so that it


obtains hours and minutes from the number
of seconds entered by the user.
End of Part 1
Shortcut Assignment Operators
• Java has a number of shortcut assignment operators:

Operator Example Equivalent


+= i += 8 i = i + 8

-= 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

• Java provides four other shortcut operators


– Two operators which increment a variable by 1
– And two others that decrement a variable by 1
Operator Name Description

++var preincrement ++var increments the value of var by 1 and


uses the new value (increments before use)
var++ postincrement var++ uses the current value of var then
increments var by 1 (increments after use)
--var predecrement --var decrements the value of var by 1 and
uses the new value (decrements before use)
var-- postdecrement var-- uses the current value of var then
decrements var by 1 (decrements after use)
Preincrement & Postincrement Example

• 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.

• The + operator used against a string implies join (concatenation).


• For example:

// three strings concatenated to form string “Welcome to Java”

String msg = "Welcome " + "to " + "Java";

// String Chapter is concatenated with integer 2

String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with character B

String s1 = "Supplement" + 'B'; // s1 becomes SupplementB


Convert Strings to Integers
• To convert a string into an int value, you can use the static parseInt method in the
Integer class as follows:
Integer.parseInt(String Variable)
Integer.parseInt(String Value)

• For example:
String year = “2013”;

int yr = Integer.parseInt(year);

int yr = Integer.parseInt(“2013”);

int nextYear = 1 + Integer.parseInt(“2013”);


Convert Strings to Double
• To convert a string into an double value, you can use the static
parseDouble method in the Double class as follows:
Double.parseDouble(String Variable)
Double.parseDouble(String Value)
• For example:
String rate= “0.20”;
double taxrate = Double.parseDouble(rate);
double taxrate = Double.parseDouble(“0.20”);
Double tax = price * Double.parseDouble(“0.20”);
Programming Style and Documentation

• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing Lines
• Block Styles
Appropriate Comments
• Comments help other developers (programmers) understand your
programs.

• Provide comments for everything that is not obvious.

• Include a description at the beginning of the program explaining


what the program does.

• 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

• Indentation and spacing make your program


easy to read (readable).
• Indentation:
– indent the contents of each block three spaces
from the left edge of the block.
• Spacing
– use blank line to separate segments of the code.
Block Styles
• A block is a group of statements surrounded by braces. There are two popular block styles, next-line style and end-of-line style.

Easy To
Read

Saves
Space

• Do not mix styles; choose one style and use it consistently.


Programming Errors
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result
Syntax Errors
public class ShowSyntaxErrors {
public static void main(String[] args) {
i = 30;
System.out.println(i + 4)
}
}

Identify Syntax Errors in the


program above!
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
int i = 1 / 0;
}
}

This will cause the program


to abort.

Division by zero is NOT


allowed.
Logic Errors
import java.util.Scanner;

public class ShowLogicErrors {


// Calculate the area of a circle
public static void main(String[] args) {
// create Scanner
There’s a logic error here.
Scanner inp = new Scanner(System.in);

// Prompt the user to enter a radius area = πr2


System.out.print(“Enter radius: “);
double radius = inp.nextDouble();
circumference = 2πr
// Compute Area
double area = 2 * 3.14 * radius;

// Display the result


System.out.println(“The area of a circle with radius " + radius + “ is “ + area);

System.exit(0);
}
}
Debugging
• Logic errors are called bugs.

• The process of finding and correcting errors is called debugging.


• A common approach to debugging is to use a combination of methods to
narrow down to the part of the program where the bug is located.
– You can hand-trace the program (i.e., catch errors by reading the
program),
– or you can insert print statements in order to show the values of the
variables or the execution flow of the program.

• 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.

• You can use a debugger to:

– Execute a single statement at a time.

– Trace into or stepping over a method.

– Set breakpoints.

– Display variables.

– Display call stack.

– Modify variables.
Summary
• In this lecture we have looked at:
– How to get input from users using the Scanner object

– Variables (declaration, assignment & initialization)


– Constants (declaration)
– Identifiers (names of variables, constants, classes, etc)
– Java primitive data types

– Numeric operators

– String data type

– Naming conventions and programming style

– Syntax errors, logic errors and runtime errors

You might also like