Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Object oriented programming Chapter 02

Object oriented programming Chapter 02

Uploaded by

fikadu.meu.edu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Object oriented programming Chapter 02

Object oriented programming Chapter 02

Uploaded by

fikadu.meu.edu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Chapter Two

Basics in Java Programming

Slide 1
© Information Technology
Outlines
 Blocks of java programming
 Identifiers (Variable, classes, methods, interfaces…)
 Data Types
 keywords
 Operators
 Control statements
 Decision Statements
 If statement, Switch statement
 Repetition Statements
• For loop, While, Do while loop
 Arrays and working with arrays
Slide 2
© Information Technology
Variable types and identifiers

Java Variables
• Variables are containers for storing data values.
• Name of a location in memory that holds a data value.
• In Java, there are different types of variables, for example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean - stores values with two states: true or false

Slide 3
© Information Technology
Variable types and identifiers…

Declaring (Creating) Variables


• To create a variable, you must specify the type and assign it a value
• Syntax
type variableName =
type variableName;
value;

• Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to assign
values to the variable.
• To create a variable that should store text, look at the following example:

Slide 4
© Information Technology
Variable types and identifiers…

Declaring (Creating) Variables…


• Create a variable called name of type String and assign it the value "John":
• Then, Create a variable called myNum of type int assign it the value 15:
public class Example {
public static void main(String[] args) {
String name = "John"; // String Variable
int myNum = 15; // Integer Varible
System.out.println(name);//John
}
}

Slide 5
© Information Technology
Variable types and identifiers…

Final Variables
• you can add the final keyword if you don't want others (or yourself) to
overwrite existing values (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
public class Example {
public static void main(String[] args) {
final int myNum = 15;
myNum = 20; // will generate an error: Cannot assign a value to a final keyword
System.out.println(myNum);
}
}

Slide 6
© Information Technology
Variable types and identifiers…

Display Variables
• The println() method is often used to display variables.
• To combine both text and a variable, use the + character.

public class Example {


public static void main(String[] args) {
String name = “john”;
System.out.println(“Hello” + name);
}
}

Slide 7
© Information Technology
Variable types and identifiers…

Declare Many Variables


• To declare more than one variable of the same type, use a comma-separated
list.

public class Example {


public static void main(String[] args) {
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
}
}

Slide 8
© Information Technology
Variable types and identifiers…

Java Identifiers
• All Java components require unique name.
• Name used for classes, methods, interfaces and variables are called Identifier.
• Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create
understandable and maintainable code.
• EX:
int minutesPerHour = 60;

Slide 9
© Information Technology
Variable types and identifiers…

Java Identifiers…
The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter, underscore or dollar sign
• Names should start with a lowercase letter and it cannot contain whitespace
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like Java keywords, such as int or Boolean) cannot be used as names

Slide 10
© Information Technology
Java Data Types

• As explained in the previous topic, a variable in Java must be a


specified data type.
• Data types are divided into two groups:
Primitive data types – includes byte, short, int, long, float, double, boolean
and char.
Non-primitive data types - such as String, Arrays and Classes (you will learn
more about these in a later chapter)

Slide 11
© Information Technology
Java Data Types…

Primitive Data Types


• A primitive data type specifies the size and type of variable values, and it has no additional methods. There are
eight primitive data types in Java:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values


char 2 bytes Stores a single character/letter or ASCII values
Slide 12
© Information Technology
Java Data Types…

Primitive Data Types…


• Primitive number types are divided into two groups:
Integer types: stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends
on the numeric value.
Floating point types: represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
• Even though there are many numeric types in Java, the most used for numbers
are int (for whole numbers) and double (for floating point numbers).

Slide 13
© Information Technology
Java Data Types…

Primitive Data Types…


Integer Types: Byte
• The byte data type can store whole numbers from -128 to 127. This can be
used instead of int or other integer types to save memory when you are certain
that the value will be within -128 and 127
public class Example {
public static void main(String[] args) {
byte myNum = 100;
System.out.println(myNum);
}
}

Slide 14
© Information Technology
Java Data Types…

Primitive Data Types…


Integer Types: short
• The short data type can store whole numbers from -32,768 to 32,767:

public class Example {


public static void main(String[] args) {
short myNum = 5000;
System.out.println(myNum);
}
}

Slide 15
© Information Technology
Java Data Types…

Primitive Data Types…


Integer Types: int
• The int data type can store whole numbers from -2,147,483,648 to
2,147,483,647. In general, the int data type is the preferred data type when we
create variables with a numeric value.
public class Example {
public static void main(String[] args) {
int myNum = 100000;
System.out.println(myNum);
}
}

Slide 16
© Information Technology
Java Data Types…

Primitive Data Types…


Integer Types: long
• The long data type can store whole numbers from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807. This is used when int is not large enough to
store the value. Note that you should end the value with an "L".
public class Example {
public static void main(String[] args) {
long myNum = 15000000000L;
System.out.println(myNum);
}
}

Slide 17
© Information Technology
Java Data Types…

Primitive Data Types…


Floating Point Types: float
• The float data type can store fractional numbers from 3.4e−038 to 3.4e+038.
Note that you should end the value with an "f“.

public class Example {


public static void main(String[] args) {
float myNum = 5.75f;
System.out.println(myNum);
}
}

Slide 18
© Information Technology
Java Data Types…

Primitive Data Types…


Floating Point Types: double
• The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you should end the value with a "d".

public class Example {


public static void main(String[] args) {
double myNum = 19.99d;
System.out.println(myNum);
}
}

Slide 19
© Information Technology
Java Data Types…

Primitive Data Types…


Floating Point Types…
• A floating point number can also be a scientific number with an "e" to indicate
the power of 10.
public class Example {
public static void main(String[] args) {
double d1 = 12E4d;
float f1 = 35e3f;
System.out.println(f1); //outputs 35000.0
System.out.println(d1); //outputs 120000.0
}
}
Slide 20
© Information Technology
Java Data Types…

Primitive Data Types…


Booleans
• A boolean data type is declared with the boolean keyword and can only take
the values true or false. Boolean values are mostly used for conditional testing
public class Example {
public static void main(String[] args) {
boolea isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); //outputs true
System.out.println(isFishTasty); //outputs false
}
}
Slide 21
© Information Technology
Java Data Types…

Primitive Data Types…


Characters
• The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c'

public class Example {


public static void main(String[] args) {
char myVar1 = ‘A’;
System.out.println(myVar1); //outputs A
}
}

Slide 22
© Information Technology
Java Data Types…

Primitive Data Types


Characters…
• Alternatively, you can use ASCII values to display certain characters

public class Example {


public static void main(String[] args) {
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1); //outputs A
System.out.println(myVar2); //outputs B
System.out.println(myVar3); //outputs C
}
}
Slide 23
© Information Technology
Java Data Types…

Non-Primitive Data Types


• Non-primitive data types are called reference types because they refer to
objects.
• The main difference between primitive and non-primitive data types are:
Primitive types are predefined (already defined) in Java. Non-primitive types are created
by the programmer and is not defined by Java (except for String ).
Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
The size of a primitive type depends on the data type, while non-primitive types have all
the same size. Slide 24
© Information Technology
Java Data Types…

Non-Primitive Data Types…


String
• The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes.

public class Example {


public static void main(String[] args) {
String greeting = “Hello World”;
System.out.println(greeting); //outputs Hello World
}
}

Slide 25
© Information Technology
Java Keywords…

Slide 26
© Information Technology
Java Operators

• Operators are used to perform operations on variables and values.


• Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators

Slide 27
© Information Technology
Java Operators…
Arithmetic Operators
• Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example public class Example{
+ Addition Adds together two values x+y public static void main(String args[]){
int a =10;
- Subtraction Subtracts one value from x-y int b =20;
another int c =25;
* Multiplicatio Multiplies two values x*y int d =25;
n System.out.println("a + b = "+(a + b));
/ Division Divides one value by another x/y System.out.println("a - b = "+(a - b));
System.out.println("a * b = "+(a * b));
% Modulus Returns the division x%y
System.out.println("b / a = "+(b / a));
remainder System.out.println("b % a = "+(b % a));
System.out.println("c % a = "+(c % a));
++ Increment Increases the value of a ++x
variable by 1 System.out.println("a++ = "+(a++));
System.out.println("b-- = "+(b--));
-- Decrement Decreases the value of a --x
variable by 1 System.out.println("d++ = "+(d++));
© Information Technology
System.out.println("++d = "+(++d)); Slide 28
Java Operators…
Assignment Operators
• Assignment operators are used to assign values to variables.
Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

!= x != 3 x = x !3

Slide 29
© Information Technology
Java Operators…
Comparison Operators
• Comparison operators are used to compare two values
Operator Name Example
public class Example{
== Equal to x == y public static void main(String args[]){
int a =10;
!= Not equal x != y int b =20;
Output:
> Greater than x>y
System.out.println("a == b = "+(a==b)); a == b = false
a != b = true
System.out.println("a != b = "+(a !=b)); a > b = false
< Less than x<y System.out.println("a > b = "+(a > b)); a < b = true
b >= a = true
System.out.println("a < b = "+(a < b)); b <= a = false
>= Greater than or equal x >= y
to System.out.println("b >= a = "+(b>=a));
<= Less than or equal to x <= y System.out.println("b <= a = "+(b<=a));
}
}
© Information Technology
Slide 30
Java Operators…
Logical Operators
• Logical operators are used to determine the logic between variables or values
public class Example{
Opera Name Description Example
tor public static void main(String args[]){
&& Logical Returns true if both x < 5 && x boolean a = true;
and statements are true < 10
boolean b = false;
System.out.println("a && b ="+(a&&b));
|| Logical or Returns true if one x < 5 || x <
of the statements is 4 System.out.println("a || b = "+(a||b));
true
System.out.println("!(a && b)=“ + ! ( a&&
! Logical not Reverse the result, !(x < 5 && b) ); u t:
returns false if the x < 10)
O ut p
result is true } = fa lse
& & b e
} a t r u
|| b = true
a b )=
&
© Information Technology !(a & Slide 31
Java Type Casting

• Type casting is when you assign a value of one primitive data type to another
type.
• In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
 byte (1byte)-> short (2byte)
 char (2byte)-> int (4byte)
 float (4byte)-> double (8byte)
Narrowing Casting (manually) - converting a larger type to a smaller size type
 double (8byte)-> float (4byte)
 long (8byte)-> int (4byte)
 char (2byte)-> short (4byte)

Slide 32
© Information Technology
Java Type Casting…
Widening(implicit) Casting
• Widening casting is done automatically when passing a smaller size type to a
larger size type
public class Example {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; //automatic casting: int to double

System.out.println(myInt); //outputs 9
System.out.println(myDouble); //outputs 9.0
}
}

Slide 33
© Information Technology
Java Type Casting…
Narrowing(explicit) Casting
• Narrowing casting must be done manually by placing the type in parentheses
in front of the value:
public class Example {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; //manual casting: double to int

System.out.println(myDouble); //outputs 9.78


System.out.println(myInt); //outputs 9
}
}

Slide 34
© Information Technology
Java Control Statements
Conditions and If Statements
• Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to: a == b
Not Equal to: a != b
• You can use these conditions to perform different actions for different
decisions.

Slide 35
© Information Technology
Java Conditions and If Statements…

• Java has the following conditional statements:


Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed

Slide 36
© Information Technology
Java Conditions and If Statements…
The if Statement
• Use the if statement to specify a block of Java code to be executed if a
condition is true
• Syntax if (condition) {
// block of code to be executed if the condition is
true
}

public class Example {


public static void main(String[] args) {
if (20 > 18) {
System.out.println("20 is greater than 18"); //outputs 20 is greater than 18
}
}
}

Slide 37
© Information Technology
Java Conditions and If Statements…
The else Statement
• Use the else statement to specify a block of code to be executed if the
condition is false
• Syntax if (condition) {
// block of code to be executed if the condition is true
} else{
// block of code to be executed if the condition is false
}

public class Example {


public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening."); // outputs Good evening.
}
}
Slide 38
} © Information Technology
Java Conditions and If Statements…
The else if Statement
• Use the else if statement to specify a new condition if the first condition is false
• Syntax

if (condition1) {
// block of code to be executed if the condition1 is true
} else if (condition2){
// block of code to be executed if the condition1 is false and
condition2 is true
} else{
// block of code to be executed if the condition1 is false and
condition2 is false
}

Slide 39
© Information Technology
Java Conditions and If Statements…
The else if Statement…
public class Example {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 25) {
System.out.println("Good day."); //outputs Good day.
} else {
System.out.println("Good evening.");
}
}
}
Slide 40
© Information Technology
Java Conditions and If Statements…
Short Hand If...Else (Ternary Operator)
• There is also a short-hand if else, which is known as the ternary operator
because it consists of three operands.
• It can be used to replace multiple lines of code with a single line. It is often
used to replace simple if else statements
• Syntax
variable = (condition) ? expressionTrue :
expressionFalse;

Slide 41
© Information Technology
Java Conditions and If Statements…
Short Hand If...Else (Ternary Operator)…

public class Example {


public static void main(String[] args) {
int time = 20;
String result;
result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result); //outputs Good evening.
}
}

Slide 42
© Information Technology
Java Switch Statements

• Use the switch statement to select one of many code blocks to be executed.
• Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Slide 43
© Information Technology
Java Switch Statements…

• This is how it works:


The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional.

Slide 44
© Information Technology
Java Switch Statements…
public class Example {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5: Output
System.out.println("Friday"); Thursday
break;
case 6:
System.out.println("Saturday");
break;
}
}
} © Information Technology
Slide 45
Java Switch Statements…
public class Example {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
} Output
}
Looking forward to the Weekend

Slide 46
© Information Technology
Java Iteration Statements

• Loops can execute a block of code as long as a specified condition is reached.


• Loops are handy because they save time, reduce errors, and they make code
more readable.
While Loop
• The while loop loops through a block of code as long as a specified condition is true
• Syntax
while (condition) {
// code block to be executed
}

Slide 47
© Information Technology
Java Iteration Statements..

While Loop…

public class Example {


public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++; Output
} 0
} 1
2
} 3
4

Slide 48
© Information Technology
Java Iteration Statements..

The do/While Loop


• The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.
• Syntax
do {
// code block to be executed
}
while (condition);

Slide 49
© Information Technology
Java Iteration Statements..

The do/While Loop…


public class Example {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} Output
0
while (i < 5);
1
} 2
} 3
4

Slide 50
© Information Technology
Java Iteration Statements..

For Loop
• When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop.
• Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

• Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been executed.
Slide 51
© Information Technology
Java Iteration Statements..

For Loop…
public class Example {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
} Output
0
} 1
2
3
4

Slide 52
© Information Technology
Java Iteration Statements..

For-Each Loop
• There is also a "for-each" loop, which is used exclusively to loop through
elements in an array
• Syntax
for (type variableName : arrayName) {
// code block to be executed
}

Slide 53
© Information Technology
Java Iteration Statements..

For-Each Loop…

public class Example {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
} Output
} Volvo
} BMW
Ford
Mazda

Slide 54
© Information Technology
Java Break and Continue
Java Break
• The break statement can also be used to jump out of a loop.
public class Example {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
} Output
System.out.println(i); 0
1
} 2
} 3
}
Slide 55
© Information Technology
Java Break and Continue…
Java Continue
• The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
public class Example {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) { Output
0
continue; 1
} 2
System.out.println(i); 3
} 5
6
}
7
} 8
9 Slide 56
© Information Technology
Java Arrays

• Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.
• To declare an array, define the variable type with square brackets

String[] cars;

• We have now declared a variable that holds an array of strings. To insert values
to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces
String[] cars = {"Volvo", "BMW", "Ford",
"Mazda"};
Slide 57
© Information Technology
Java Arrays…

• To create an array of integers, you could write:


int[] myNum = {10, 20, 30,
40};
Access the Elements of an Array
• You access an array element by referring to the index number.
• Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Slide 58
© Information Technology
Java Arrays…

Access the Elements of an Array…

public class Example {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
} Output
} Volvo

Slide 59
© Information Technology
Java Arrays…

Change an Array element


• To change the value of a specific element, refer to the index number:
public class Example {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]); //outputs Opel instead of Volvo
}
}

Slide 60
© Information Technology
Java Arrays…

Array Length
• To find out how many elements an array has, use the length property
public class Example {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length); Output
} 4
}

Slide 61
© Information Technology
Java Arrays…

Loop Through an Array


• You can loop through the array elements with the for loop, and use the length
property to specify how many times the loop should run.
public class Example {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) { Output
System.out.println(cars[i]); Volvo
BMW
} Ford
} Mazda
}
Slide 62
© Information Technology
Java Arrays…

Loop Through an Array with For-each


• There is also a "for-each" loop, which is used exclusively to loop through
elements in arrays
public class Example {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Output
for (String i : cars) { Volvo
System.out.println(i); BMW
} Ford
} Mazda
}
Slide 63
© Information Technology
Java Arrays…

Multidimensional Arrays
• A multidimensional array is an array of arrays.
• To create a two-dimensional array, add each array within its own set of curly
braces
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6,
• Example 7} };
• myNumbers is now an array with two arrays as its elements.
• To access the elements of the myNumbers array, specify two indexes: one for
the array, and one for the element inside that array. The next example accesses
the third element (2) in the second array (1) of myNumbers:

Slide 64
© Information Technology
Java Arrays…

Multidimensional Arrays…
public class Example {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
} Output
} 7

Slide 65
© Information Technology

You might also like