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

L02 - Basic Programming Constructors

The document discusses basic programming constructs in Java including variables, data types, operators, and statements. It defines variables and literals, explains how to declare and assign variables of different data types, and covers naming conventions. It also discusses primitive data types, strings, scopes, and different types of operators in Java.

Uploaded by

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

L02 - Basic Programming Constructors

The document discusses basic programming constructs in Java including variables, data types, operators, and statements. It defines variables and literals, explains how to declare and assign variables of different data types, and covers naming conventions. It also discusses primitive data types, strings, scopes, and different types of operators in Java.

Uploaded by

Yared Getachew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Lecture 2

Basic Programming Constructors


of Java
What is a Variable?
• Variable is a named storage location in the
computer memory.
• are places where information can be stored
while a program is running.
• Their values can be changed at any point
over the course of a program
• Literals are values that are written into the
code of a program.
Creating Variables
• To create a variable, declare its name and
the type of information that it will store.
• The type is listed first, followed by the name.
• Example: int highScore ;

• type name
• This is called Variable declaration, Which tell the
compiler the variables name and the type of data it
will hold.
Creating Variables (continued)

• Now you have the variable (highScore), you will


want to assign a value to it.
highScore = 98;
• This is called assignment statement.
• Here, highScore is a variable declared as an
integer and 98 is Integer Literal.
• Examples of other types of variables:
String studentName;
boolean gameOver;
Naming Variables
• Identifier is a programmer-defined names that
represent some elements of a program.
• Variable names & class names are examples of
identifiers.
• In Java, an identifier can be of any length, but must
start with:
a letter (a – z) or (A – Z),
a dollar sign ($),
or, an underscore ( _ ).
• The rest of the identifier can include any character
except those used as operators in Java such as + ,
- , * and /.
• In addition, there are certain keywords reserved
(e.g., "class") in the Java language which can never
be used as identifiers.
Naming (Continued)
• Java is a case-sensitive language – the
capitalization of letters in identifiers matters.
A rose is not a Rose is not a ROSE

• It is good practice to select variable names that


give a good indication of the type of data they
hold
– For example, if you want to record the size of a hat,
hatSize is a good choice for a name whereas qqq
would be a bad choice
• When naming a variable, the following
convention is commonly used:

– The first letter of a variable name is lowercase


– Each successive word in the variable name begins
with a capital letter
– All other letters are lowercase

• Here are some examples:

pageCount
loadFile
anyString
threeWordVariable
POP QUIZ
• Which of the following are valid variable
names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
Statements
• A statement is a command that causes
something to happen.
• All statements in Java are separated by
semicolons ;
• Example:
System.out.println(“Hello, World”);

• You have already used statements to


create a variable and assign it a value.
Variables and Statements

• One way is to declare a variable and then


assign a value to it with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable

• Another way is to write a single


initialization statement:
int e = 5; // declaring AND assigning
Java is a Strongly-Typed Language
• All variables must be declared with a data
type before they are used.
• Each variable's declared type does not
change over the course of the program.
• Certain operations are only allowed with
certain data types.
• If you try to perform an operation on an
illegal data type (like multiplying Strings),
the compiler will report an error.
Primitive Data Types
• There are eight built-in (primitive) data types in the
Java language

– 4 integer types (byte, short, int, long)


– 2 floating point types (float, double)
– Boolean (boolean)
– Character (char)

• These data types are called “primitive” because you


cannot use them to create objects.
• They are not reference variable.
• They are just used to hold a single value at a time.
Integer Data Types
• Variables data type determines the amount of
memory the variable uses.
• There are four data types that can be used to store
integers.
• The one you choose to use depends on the size of
the number that we want to store.
Data Type Value Range Size
byte -128 to +127 1 byte
short -32768 to +32767 2 byte
int -2147483648 to +2147483647 4 byte
long -9223372036854775808 to 8 byte
+9223372036854775807
• Here are some examples of when you would
want to use integer types:
- byte smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;
• When you write an integer literals in your
program, java assumes it to be of the int data
type.
• long bigValue = 1823337144562;
• This will result error.
• You can force an integer literals to be treated as
a long by suffixing a letter L or l.
Floating Point Data Types
• There are two data types that can be used to
store decimal values (real numbers).
• The one you choose to use depends on the size
of the number that we want to store.

Data Type Size Value Range

float 4 byte 1.4×10-45 to 3.4×1038

double 8 byte 4.9×10-324 to 1.7×10308


• Here are some examples of when you would
want to use floating point types:
– double g = 7.7e100 ;
– double tinyNumber = 5.82e-203;
– float costOfBook = 49.99F;
• When you write a floating point literal in your
program code, java assumes it to be of the
double data type.

– float x = 49.99; //this will result an error.


• You can force a double literal to be treated
as a float, by suffixing F or f.
Boolean Data Type

• Boolean is a data type that can be


used in situations where there are
two options, either true or false.

• Example:
boolean monsterHungry = true;
boolean fileOpen = false;
Character Data Types
• Character is a data type that can be used to
store a single characters such as a letter,
number, punctuation mark, or other symbol.

• Example:
– char firstLetterOfName = 'e' ;
– char myQuestion = '?' ;

• Note that you need to use singular quotation


marks when assigning char data types.
Strings
• Strings consist of a series of characters inside
double quotation marks.

• Examples statements assign String variables:

String name = "John Smith";


String password = "swordfish786";
String fname = new String(“abebe”);

• The String is class and allows you to create


an Objects for handling strings.
• It also have various methods that allows you to
work with strings.
Strings (Cont.)
• Primitive type variables hold the actual data
– E.g. int num = 5;
• A class type variables does not hold the actual data item but
holds the memory address of the data item it is associated
with.
• Due to this class type variables are known as Reference
Variables.
• Because String is a class, it provides numerous methods for
working with String.
– length() // returns number of character including spaces
– CharAt(index) // return character at index position.
– toLowerCase()
– toUpperCase()
– equals(object2); // compare String object2 with the calling object.
Scope of a variable
• The scope of a variable is the part of the program
where the variable may be accessed by its name.
• The variable that is declared inside a method are
called local variables.
• A local variable scope begins at the variable
declaration and ends at the end of the method in
which the variable is declared.
Reserved Words
The following keywords are reserved in the Java
language. They can never be used as identifiers:

abstract assert boolean break byte


case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
Operators
• Operators are special symbols used for
– Mathematical functions
– Assignment statements
– Logical comparisons

• Example
–5 + 6 // uses + operator
– 14 + 5 – 4 * (5 – 3) // uses +, -, *
operators
Operators
• There are 5 different groups of
operators:
oArithmetic operators
oAssignment operator
oIncrement/Decrement operators
oRelational operators
oConditional operators
Arithmetic Operators
• Java has 5 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
• Order of operations (or precedence) when evaluating an
expression is the same as you learned in school (PEMDAS).
• Java Provides a Math class, which contains numerous
methods that are useful for performing complex
mathematical operations.
double result = Math.pow (4.0,2.0);
double result = Math.sqrt (9.0);
Integer Division
• When both operands of the division operator are
integer the result of operation will be an integer.
– E.g. double number;
number = 5 / 2; // number will be 2 not 2.5.

• In order to get a floating-point result one of the


operand must be a floating-point data type.
– number = 5.0 / 2; // number will be 2.5.
Assignment Operator
• The basic assignment operator (=) assigns
the value of expr to var.
var = expr ;
• Java allows you to combine arithmetic and
assignment operators into a single
operator.
• Examples:
x = x + 5; is equivalent to x += 5;
y = y * 7; is equivalent to y *= 7;
Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;
++ is called the increment operator.
count = count - 1;
can be written as:
--count; or count--;
-- is called the decrement operator.
The increment/decrement operator has two forms:

– The prefix form ++count, --count


first adds 1 to the variable and then continues to any other
operator in the expression

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6

– The postfix form count++, count--


first evaluates the expression and then adds 1 to the variable

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
Relational (Comparison) Operators
•Relational operators compare two values.
• Produces a boolean value (true or false)
depending on the relationship.

operation is true when . . .

a > b a is greater than b


a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a <= b a is less than or equal to b
a < b a is less than b
Examples of Relational Operations
int x = 3;
int y = 5;
boolean result;

1) result = (x > y);


now result is assigned the value false because
3 is not greater than 5

2) result = (15 == x*y);


now result is assigned the value true because the product
of
3 and 5 equals 15

3) result = (x != x*y);
now result is assigned the value true because the product
of x and y (15) is not equal to x (3)
Conditional Operators
Symbol Name

&& AND
|| OR
! NOT

• Conditional operators can be referred to as boolean


operators, because they are only used to combine
expressions that have a value of true or false.
Truth Table for Conditional Operators
x y x && y x || y !x

True True True True False

True False False True False

False True False True True

False False False False True


Examples of Conditional Operators
boolean x = true;
boolean y = false;
boolean result;

1. Let result = (x && y);

now result is assigned the value false


(see truth table!)

2. Let result = ((x || y) && x);

(x || y) evaluates to true
(true && x) evaluates to true

now result is assigned the value true


Short-Circuit Evaluations
(a && (b++ > 3))
What happens if a is false?
• Java will not evaluate the right-hand expression (b++ >
3) if the left-hand operator a is false, since the result is
already determined in this case to be false. This
means b will not be incremented!

(x || y)
What happens if x is true?
• Similarly, Java will not evaluate the right-hand operator y
if the left-hand operator x is true, since the result is
already determined in this case to be true.
Conversion between Primitive Data Types
• Before a value can be stored in a variable, the values data
type must be compatible with the variables data type.
• Java automatically convert the lower ranked values
to higher ranked type , i.e. widening conversion.
➢ Double Higher rank
➢ Float
➢ Long
➢ Int
➢ short
Lower rank
➢ byte
– E.g. double x = 2.5;
Int y = 2;
x = y ; // Possible
y = x; // Error … this is Narrowing conversion
Cast Operator
• Java does not automatically convert any conversion that can
result in the loss of data or conversion to lower ranked.
• Cast operator lets you manually convert a value.
double num = 2.5;
int x = (int) num; // convert the value 2.5 to 2 & store it in x.
• Recall Integer Division
double x;
x = 5 / 2; // x = 2.0 integer division.
x = (double) 5 / 2; // x=2.5 cast one operand in to double.
x = (double) ( 5 / 2) ; // x = 2.0
• Mixed integer operations
e.g. short x, y=2, z=4;
x = y+z; // this will result an error.
x = (short) (y+z); //this will work because the arithmetic
operation using mixture of byte, short, & int will always be integer.
Control Structures
What are Control Structures?
• Control structures alter the flow of the
program, the sequence of statements
that are executed in a program.

• Two types of control structures in Java:


– decision statements
– loops
Decision Statements

• A decision statement allows the


code to execute a statement or
block of statements conditionally.

• Two types of decisions statements


in Java:
– if statements
– switch statements
If Statement
if (expression) {
statement;
}
rest_of_program;

• expression must evaluate to a boolean value, either


true or false
• If expression is true, statement is executed and
then rest_of_program
• If expression is false, statement is not executed
and the program continues at rest_of_program
If Statement Flow Diagram
The if decision statement executes
a statement if an expression is true
Is expression no
true?

if (expression) { yes
statement1;
} execute
statement
rest_of_program

execute
rest_of_program
If-Else Statement
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;

• Again, expression must produce a boolean value

• If expression is true, statement1 is executed and


then next_statement is executed.

• If expression is false, statement2 is executed and


then next_statement is executed.
If-Else Flow Diagram
The if-else decision
statement executes a
is
statement if an expression yes no
“expression”
is true and a different true?

statement if it is not true.

if (expression){ execute execute


statement1 statement2
statement1;
} else {
statement2;
} execute
rest_of_program rest_of_program
Chained If-Else Statements

if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
Switch Statements
• The switch statement enables you to test several
cases generated by a given expression.

• For example:
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed

• The expression must evaluate to a char, byte, short


or int, but not long, float, or double.
expression
y
equals Do value1 thing
value1?
switch (expression){
case value1:
// Do value1 thing n
case value2:
// Do value2 thing
expression y
equals Do value2 thing
...
default: value2?
// Do default action
}
// Continue the program n

Do default action

Continue the
program
Break Statements in Switch Statements
• The break statement tells the computer to exit
the switch statement
• For example:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
switch (expression){ expression y
case value1: equals Do value1 thing break
// Do value1 thing value1?
break;

case value2: n
// Do value2 thing
break;
expression y
... equals Do value2 thing break
default: value2?
// Do default action
break;
} n
// Continue the program

do default action

Continue the
break
program
• This is how it is accomplished with a switch:
switch (grade) {
case 'A':
System.out.println("You got an A.");
break;
case 'B':
System.out.println("You got a B.");
break;
case 'C':
System.out.println("You got a C.");
break;
default:
System.out.println("You got an F.");
}

• if-else chains can be sometimes be rewritten


as a “switch” statement.
• switches are usually simpler and faster
Loops
• A loop allows you to execute a statement or
block of statements repeatedly.

• Three types of loops in Java:


1. while loops
2. for loops
3. do-while loops
The while Loop
while (expression){
statement
}

• This while loop executes as long as the given logical


expression between parentheses is true. When
expression is false, execution continues with the
statement following the loop block.

• The expression is tested at the beginning of the loop, so


if it is initially false, the loop will not be executed at all.
• For example:

int sum = 0;
int i = 1;

while (i <= 10){


sum += i;
i++;
}

• What is the value of sum?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The do-while loop
do {
Statement;
} while (expression);

• First the Statement is executed and then the Boolean


expression is tested.
• Then the Statement continue to be executed as long as the
expression is true.
• The do-while loop is a posttest loop, which means its
boolean is expression is tested after each iteration.
• The do-while loop must terminated with semicolon.
The for Loop
for (init_expr; loop_condition; increment_expr) {
statement;
}

The control of the for loop appear in parentheses and is made up of


three parts:

1. The first part, the init_expression,sets the initial


conditions for the loop and is executed before the loop starts.

2. Loop executes so long as the loop_condition is true and


exits otherwise.

3. The third part of the control information, the


increment_expr, is usually used to increment the loop
counter. This is executed at the end of each loop iteration.
• For example:

int sum = 0;

for (int i = 1; i <= 10; i++) {


sum += i;
}

• What is the value of sum?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
• Example :

for(int div = 0; div < 100; div++)


{
if(div % 2 == 0) {
System.out.println("even: " + div);
} else {
System.out.println("odd: " + div);
}
}
• What will this for loop do?
prints out each integer from 0 to 99,
correctly labeling them even or odd
even: 0
odd: 1 …
• If there is more than one variable to set up or
increment they are separated by a comma.

for(int i=0, j=0; i*j < 100; i++, j+=2) {


System.out.println(i * j);
}

• You do not have to fill all three control expressions


but you must still have two semicolons.

int n = 0;
for(; n <= 10;) {
System.out.println(++n);
}
The for loop

Initialize count
The while loop

n n
Test condition Test condition
is true? is true?

y
y
Execute loop
statement Execute loop
statement(s)

Increment
Next statement count

New statement
The continue Statement
• The continue statement causes the program
to jump to the next iteration of the loop.

/*
* print out "5689"
*/
for(int m = 5; m < 10; m++) {
if(m == 7) {
continue;
}
System.out.print(m);
}
• Another continue example:

int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}

• What is the value of sum?


1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
The break Statement
• We have seen the use of the break statement
in the switch statement.
• You can also use the break statement to exit
the loop entirely.
// prints out numbers unless
// num is ever exactly 100
int num = 0;
while (num >= 0) {
if(num == 100) {
break;
}
System.out.println(num);
num += 5;
}
Nested Loops
• You can nest loops of any kind one inside
another to any depth. What does this print?
for(int i = 10; i > 0; i--) {
if (i > 7) {
continue;
6
} 5
while (i > 3) { 5
if(i == 5) { 3
break; 3
}
2
System.out.println(--i);
}
1
System.out.println(i);
}
Nested Loops
• Example
for (int hours = 1; hours <=12; hours++)
{
for (int minutes =0; minutes <=59; minutes++)
{
for (int second=0;second <=59;second++)
{
System.out.printf(“%02d:%02d:%02d\n”,
+hours,minute,second);
}
}
}
• The inner loop goes all of its iteration for each
iteration of the outer loop.
POP QUIZ
1. In the switch statement, which types can
expression evaluate to? char, byte, short, int
2. What must be used to separate each
section of a for statement. semicolons
3. Which statement causes a program to
skip to the next iteration of a loop. continue
4. Write a for loop that outputs 100 to 1 in
reverse sequence.
5. Write a for loop that outputs all numbers
that are divisible by 3 between 0-50.
End of Lecture 2

You might also like