ElementaryProgrammingPPT
ElementaryProgrammingPPT
ELEMENTARY PROGRAMMING
You will learn elementary programming using Java primitive
data types and related subjects, such as variables, constants,
operators, expressions, and input and output.
Writing Simple Programs
• Writing a program involves designing algorithms and data
structures, as well as translating algorithms into
programming code.
• An Algorithm describes how a problem is solved in terms of
the actions to be executed, and it specifies the order in
which the actions should be executed.
• Algorithms can help the programmer plan a program before
writing it in a programming language.
computing an area of a circle. The algorithm for this
program can be described as follows:
1.compute the area using the following formula
2.Read in the Radius
Area = radius * radius * ∏
3.Display the area.
Java provides data types for representing integers, floating-point
numbers, characters, and Boolean types. These types are known
as primitive data types.
When you code, you translate an algorithm into a programming
language understood by the computer.
// Display results
ComputingAreaWithConsoleInput.java
import java.util.Scanner; // Scanner is in the java.util package
public class ComputeAreaWithConsoleInput
System.out.print("Enter a number for radius: "); double
radius = input.nextDouble();
// Compute area
double area = radius * radius * 3.14159;
// Display result
System.out.println("The area for the circle of radius " +
radius + " is " + area);
} }
OUTPUT :
Enter a number for radius: 23
The area for the circle of radius 23.0
is 1661.90111
System.out.println(x = 1);
which is equivalent to
x = 1; System.out.println(x);
// Compute area
double area = radius * radius * PI;
// Display result
System.out.println("The area for the circle of radius " radius + " is "
+ area);
}
}
There are three benefits of using constants:
• you don’t have to repeatedly type the same value if it is used
multiple times;
• if you have to change the constant value (e.g., from 3.14 to
3.14159 for PI), you need to change it only in a single location
in the source code;
• A descriptive name for a constant makes the program easy to
read.
NAMING CONVENTIONS
Naming conventions makes your programs easy to read and
avoids errors.
• Use lowercase for variables and methods. If a name consists
of several words, concatenate them into one, making the first
word lowercase and capitalizing the first letter of each
subsequent word—for example, the variables radius and area
Numeric Data Types and Operations
• Every data type has a range of values. The compiler allocates
memory space to store each variable or constant according to
its data type.
• Java provides eight primitive data types for numeric values,
characters, and Boolean values.
• Java has six numeric types: four for integers and two for
floating-point number
• Table
• Java uses two types for floating-point numbers: float and
double.
• The double type is twice as big as float, so the double is known
as double precision and float as single precision.
• Normally, we use the double type, because it is more accurate
than the float type.
Reading Numbers from the Keyboard
-7 % 3 yields -1
-12 % 4 yields 0
-26 % -8 yields -2
20 % -13 yields 7
• Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is
always 1. Thus, you can use this property to determine
whether a number is even or odd.
• If today is Saturday, it will be Saturday again in 7 days
• Suppose you and your friends are going to meet in 10 days.
What day is in 10 days? You can find that the day is Tuesday
using the following expression:
LISTING DisplayTime.java
import java.util.Scanner;
public class DisplayTime {
public static void main(String[] args) { Scanner input = new
Scanner(System.in);
// Prompt the user for input
System.out.print("Enter an integer for seconds: "); int seconds =
input.nextInt();
Numeric Literals
A literal is a constant value that appears directly in a program.
For example, 34 and 0.305 are literals in the following
statements:
int numberOfYears = 34;
Integer Literals
• An integer literal can be assigned to an integer variable as long as it can
fit into the variable.
• A compilation error would occur if the literal were too large for the variable
to hold.
• for example The statement byte b = 128, will cause a compile error,
because 128 cannot be stored in a variable of the byte type.
• An integer literal is assumed to be of the int type, whose value is between
-231 (-2147483648) to 231–1 (2147483647).
• To denote an integer literal of the long type, append it with the letter L or l
(lowercase L).
• For example, the following code display the decimal value 65535 for
hexadecimal number FFFF.
• System.out.println(0XFFFF); // Displays 65535
Floating-Point Literals
• Floating-point literals are written with a decimal point. By default, a
floating-point literal is treated as a double type value.
• For example, 5.0 is considered a double value, not a float value .
For example, you can use 100.2f or 100.2F for a float number, and 100.2d or
100.2D for a double number.
The double type values are more accurate than float type values.
System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);
displays 1.0 / 3.0 is 0.3333333333333333
Scientific Notations
Floating-point literals can be written in scientific notation in the form of a *
10^b.
For example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456,
and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent
and it can be either in lowercase or uppercase.
Evaluating Java Expressions
, For example ,the arthimetic expression
3 4 x 10 ( y 5 )( a b c) 4 9 x
9( )
5 x x y
can be translated into a Java expression as:
(3 + 4 * x)/5 – 10 * (y - 5)*(a + b + c)/x + 9 *(4 / x + (9 + x)/y)
Operators contained within pairs of parentheses are evaluated first.
Parentheses can be nested, in which case the expression in the inner parentheses is
evaluated first.
Multiplication, division, and remainder operators are applied next. Order of operation is
applied from left to right. Addition and subtraction are applied last.
Here is an example of how an expression is evaluated:
LISTING FahrenheitToCelsius.java
import java.util.Scanner;
public class FahrenheitToCelsius { public static
void main(String[] args) {
Scanner input = new Scanner(System.in);
The ++ and —— are two shorthand operators for incrementing and decrementing a
variable by 1. These are handy because that’s often how much the value needs to be
changed in many programming task
For example, the following code increments i by 1 and decrements j by 1.
Int i = 3, j = 3;
i++; // i becomes 4
j——; // j becomes 2
Using increment and decrement operators make expressions short; it also makes
them complex and difficult to read.
tiple times such as this: int k = ++i + i.
using these operators in expre ssions that modify multiple variables or the same variable
Numeric Type Conversions
• When performing a binary operation involving two operands of different types, Java
automatically converts the operand based on the following rules:
• If one of the operands is double, the other is converted into double.
• Otherwise, if one of the operands is float, the other is converted into float.
• Otherwise, if one of the operands is long, the other is converted into long.
• Otherwise, both operands are converted into int.
• Thus the result of 1 / 2 is 0, and the result of 1.0 / 2 is 0.5.
• Type Casting is an operation that converts a value of one data type into a value of
another data type.
• Casting a variable of a type with a small range to variable with a larger range is known as
widening a type. Widening a type can be performed automatically without explicit
casting.
• Casting a variable of a type with a small range to variable with a larger range is known as
widening a type. Widening a type can be performed automatically without explicit
casting.
• Casting a variable of a type with a large range to variable with a smaller range is known
as narrowing a type. Narrowing a type must be performed explicitly.
• Caution: Casting is necessary if you are assigning a value to a variable of a smaller type
range. A compilation error will occur if casting is not used in situations of this kind. Be
careful when using casting. Lost information might lead to inaccurate results.
• The syntax for casting a type is to specify the target type in parentheses, followed by the
Common Errors And Pitfalls
Common elementary programming errors often involve undeclared variables, uninitialized
variables, integer overflow, unintended integer division, and round-off errors.
Undeclared/Uninitialized Variables and Unused Variables
A variable must be declared with a type and assigned a value before using it.
A common error is not declaring a variable or initializing a variable.
Consider the following code:
double interestRate = 0.05; double interest = interestrate * 45;
Above interestrate has not been declared and initialized. Java is case sensitive, so it considers
interestRate and interestrate to be two different variables.
If a variable is declared, but not used in the program, it might be a potential programming
error.
Integer Overflow
Numbers are stored with a limited numbers of digits. When a variable is assigned a value that
is too large (in size) to be stored, it causes overflow
Numbers are stored with a limited numbers of digits. When a variable is assigned a value that
is too large (in size) to be stored, it causes overflow
int value = 2147483647 + 1; // value will actually be -2147483648
because the largest value that can be stored in a variable of the int type is 2147483647.
2147483648 will be too large for an int value.
Java does not report warnings or errors on overflow, so be careful when working with numbers
When a floating-point number is too small (i.e., too close to zero) to be stored, it causes underflow. Java approximates it to zero,
so normally you don’t need to be concerned about underflow.
Round-off Errors
A round-off error, also called a rounding error, is the difference between the calculated
approximation of a number and its exact mathematical value.
For example, 1/3 is approximately 0.333 if you keep three decimal places, and is 0.3333333
if you keep seven decimal places. Since the number of digits that can be stored in a variable
is limited, round-off errors are inevitable.
Unintended Integer Division
Java uses the same divide operator, namely /, to perform both integer and floating-point
division.
When two operands are integers, the / operator performs an integer division. The result of
the operation is an integer. The fractional part is truncated.
To force two integers to perform a floating-point division, make one of the integers into a
floating-point number.
a) int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2;
System.out.println(average);
b)
int number1 = 1;
int number2 = 2;