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

ElementaryProgrammingPPT

ElementaryProgrammingPPT

Uploaded by

17211a0286
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

ElementaryProgrammingPPT

ElementaryProgrammingPPT

Uploaded by

17211a0286
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

ELEMENTARY PROGRAMMING IN JAVA

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.

The outline of the program is:


// ComputeArea.Java: compute the area of a circle Comment

public class ComputeArea // Class Name


{ public static void main(String[] args) // Main Method signature
{ double radius; // Data type & variable double area;

// Assign a radius radius = 20;


// Compute area
area = radius * radius * 3.14159; // Expression

// Display results

System.out.println("The area for the circle of radius " + radius + "


is " + area);
}
• The program needs to declare a symbol called a variable that
will represent the radius.
• Variables are used to store data and computational results in
the program.
• Use descriptive names rather than x and y. Use radius for
radius, and area for area. Specify their data types to let the
compiler know what radius and area are, indicating whether
they are integer, float, or something else.
• The program declares radius and area as double-precision
variables. The reserved word double indicates that radius
and area are double-precision floating-point values stored in
the computer.
• The plus sign (+) has two meanings: one for addition and the
other for concatenating (combining) strings
• The plus sign (+) used in the above program is called a string
Reading Input from the Console
• The radius is fixed in the above source code. To use a
different radius, you have to modify the source code and
recompile it. Obviously, this is not convenient, so instead you
can use the Scanner class for console input.
• Java uses System.out to refer to the standard output device
and System.in to the standard input device.
• By default, the output device is the display monitor and the
input device is the keyboard.
• To perform console output, you simply use the println
method to display a primitive value or a string to the console.
• Console input is not directly supported in Java, but you can
use the Scanner class to create an object to read input from
System.in, as follows:

• Scanner input = new Scanner(System.in);


• The syntax new Scanner(System.in) creates an object of the
Scanner type.
• The syntax Scanner input declares that input is a variable
whose type is Scanner
• The whole line Scanner input = new Scanner(System.in)
creates a Scanner object and assigns its reference to the
variable input.
• An object may invoke its methods
• You can invoke the nextDouble( ) method to read a double value
as follows:
• double radius = input.nextDouble();

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

• Above output displays a string


"Enter a number for radius: " to
System.out.print("Enter a number for radius: ");
• The above Line is identical to the println method except that
println moves to the beginning of the next line after displaying
the string.
• But Print does not advance to the next line
• The Scanner class is in the java.util. It is imported.
• There are two types of import statements: specific import and
wildcard import.
• The specific import specifies a single class in the import
statement.
• For example, the following statement imports Scanner from the
package java.util.
import java.util.Scanner;
• The wildcard import imports all the classes in a package by
using the asterisk as the wildcard.
• For example, the following statement imports all the classes
• The information for the classes in an imported package is not
read in at compile time or runtime unless the class is used in
the program
• The import statement simply tells the compiler where to locate
the classes.
• There is no performance difference between a specific import
and a wildcard import declaration.
IDENTIFIERS
An identifier is a sequence of characters that consists of
letters, digits, underscores (_), and dollar signs ($).
The following are the rules for naming identifiers:
• 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 true, false, or null.
• An identifier can be of any length.
For example:
• Legal identifiers are for example: $2, ComputeArea, area,
radius, and showMessageDialog.
• Illegal identifiers are for example: 2A, d+4.
• Do not name identifiers with the $ character. By convention,
the $ character should be used only in mechanically
generated source code.
VARIABLES
Variables are used to store data in a program
You can write the code shown below to compute the area for
different radii:
// Compute the first area radius = 1.0;
area = radius*radius*3.14159;
Declaring Variables
• Variables are used for representing data of a certain type.
• To use a variable, you declare it by telling the compiler the name
of the variable as well as what type of data it represents. This is
called variable declaration.
• Declaring a variable tells the compiler to allocate appropriate
memory space for the variable based on its data type.
The following are examples of variable declarations:
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;
If variables are of the same type, they can be declared
together using short-hand form:
Datatype var1, var2, …, varn; è variables are separated by
commas
The variables are separated by commas.
Variables often have initial values. You can declare a variable and
initialize it in one step.
For example:
int count = 1;
This is equivalent to the next two statements:
int count;
count = 1;
You can also use a shorthand form to declare and initialize
variables of the same type together.
For example:
int i = 1, j = 2;
Assignment Statements and Assignments Expressions
After a variable is declared, you can assign a value to it by using
an assignment statement.
The syntax for assignment statement is:
variable = expression;
x = 1; // Assign 1 to x; Thus 1 = x is wrong
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
x = 5 * (3 / 2) + 3 * 2; // Assign the value of the
expression to x;
x = y + 1; // Assign the addition of y and 1 to
x;
The variable can also be used in the expression.
x = x + 1; // the result of x + 1 is assigned to x;
To assign a value to a variable, the variable name
must be on the left of the assignment operator.
1 = x would be wrong.
InJava, an assignment statement can also be treated as an
expression that evaluates to the value being assigned to the
variable on the left-hand side of the assignment operator. For
this reason, an assignment statement is also known as an
assignment expression, and the symbol = is referred to as the
assignment operator.

System.out.println(x = 1);
which is equivalent to
x = 1; System.out.println(x);

The following statment is also correct:


i = j = k = 1;
which is equivalent to
k = 1; j = k; i = j;
Named Constants
The value of a variable may change during the execution of the
program, but a constant represents permanent data that never
change.
The syntax for declaring a constant:

final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159; // Declare a constant


final int SIZE = 3;
A constant must be declared and initialized before it can be
used. You cannot change a constant‟s value once it is
declared. By convention, constants are named in
uppercase.
import java.util.Scanner;
// Scanner is in the java.util package

public class ComputeAreaWithConstant {


public static void main(String[] args) {
final double PI = 3.14159; // Declare a constant

// Create a Scanner object

Scanner input = new Scanner(System.in);


// Prompt the user to enter a radius
System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();

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

Methods for Scanner Objects


Numeric Operators
The operators for numeric data types include the standard
arithmetic operators: addition (+), subtraction (–), multiplication
(*), division (/), and remainder (modulo operator)(%).
operands are the values operated by an operator.
Numeric Operators
When both operands of a division are integers, the result of the
division is the quotient and the fractional part is truncated.
For example

5/2 yields an integer 2


5.0/2 yields a double value 2.5
-5/2 yields an integer value -2
-5.0/2 yields a double value -2.5

The % operator, known as remainder or modulo operator, yields


the remainder after division.
5 % 2 yields 1 (the remainder of the division.)

-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();

int minutes = seconds / 60; // Find minutes in seconds


int remainingSeconds = seconds % 60; // Seconds remaining
System.out.println(seconds + " seconds is " + minutes +
" minutes and " + remainingSeconds + " seconds");
}
}
OUTPUT
Enter an integer for seconds: 500
Exponent Operations
The Math.pow(a, b) method can be used to compute a^b The
pow method is defined in the Math class in the Java API.
You invoke the method using the syntax Math.pow(a, b) (e.g.,
Math.pow(2, 3)), which returns the result of a^b (2^3).
Here, a and b are parameters for the pow method and the
numbers 2 and 3 are actual values used to invoke the method.
For example
System.out.println(Math.pow(2, 3)); // Displays 8.0

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

System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);


displays 1.0F / 3.0F is 0.33333334
A float value has 7 to 8 number of significant digits and a double value has
15 to 17 number of significant digits.

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);

System.out.print("Enter a degree in Fahrenheit: ");


double fahrenheit = input.nextDouble();

// Convert Fahrenheit to Celsius


double celsius = (5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is " +
celsius + " in Celsius");
} }
OUTPUT
Enter a degree in Fahrenheit: 100
Fahrenheit 100.0 is 37.77777777777778 in Celsius
Augmented Assignment Operators
The operators +, -, *, /, and % can be combined with the assignment operator to form
augmented operators
The += is called the addition assignment operator
The augmented assignment operator is performed last after all the other operators in the
expression are evaluated
x /= 4 + 5.5 * 1.5;
is same as
x = x / (4 + 5.5 * 1.5);
There are no spaces in the augmented assignment operators. For example, + = should be
+=.
Table
Increment and Decrement Operators

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

i++ is pronounced as i plus plus and i—— as i minus minus.


These operators are known as postfix increment (or postincrement) and postfix
decrement (or postdecrement), because the operators ++ and —— are placed after the
variable

These operators can also be placed before the variable.


For example
int i = 3, j = 3;
++i; // i becomes 4
——j; // j becomes 2
Increment and Decrement Operators

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;

You might also like