[go: up one dir, main page]

0% found this document useful (0 votes)
11 views39 pages

OOP - Chapter 2

The document is a course outline for Object Oriented Programming focusing on Java elements, including topics such as the Java development environment, variables, objects, input/output, control statements, and arrays. It provides detailed explanations of Java syntax, data types, operators, and control flow mechanisms with examples. The content is structured to guide students through the fundamental concepts of Java programming.

Uploaded by

aliyijemal28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

OOP - Chapter 2

The document is a course outline for Object Oriented Programming focusing on Java elements, including topics such as the Java development environment, variables, objects, input/output, control statements, and arrays. It provides detailed explanations of Java syntax, data types, operators, and control flow mechanisms with examples. The content is structured to guide students through the fundamental concepts of Java programming.

Uploaded by

aliyijemal28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Dire Dawa University Institute of Technology (DDUIoT)

College of Electrical and Computer Engineering (CECE)

Course: Object Oriented Programming [ECEg-2101]

Chapter Two: Java Elements


Prepared by: Haftu M & Bekalu M.
Outline 3/5/2025

 Introduction to the Java development environment,


 Variables and their declaration

 Introduction to objects in class

 Input/output in java

 Java’s control statements

 Java arrays Declaration and manipulation

OOP chapter 2 [by Haftu.M & Bekalu.M] 2


Hellow world java program 3/5/2025

All Java applications begin execution from main ( ) function.


 (This is just like C/C++.)
Public : is a java keyword which is access modifier, if a class is preceded by
public it implies that it can be accessed outside the class even the package

OOP Chapter 2 [by Haftu M. & Bekalu M.] 3


Continued….. 3/5/2025

 Static: allows main ( ) to be called without having to instantiate a particular instance of the class.
 void simply tells the compiler that main ( ) does not return a value
 main ( ) is the method called when a Java application begins. Keep in mind that Java is case-
sensitive. Thus, Main is different from main.
 String args[ ] declares a parameter named args, which is an array of instances of the class String.
Objects of type String store character strings. In this case, args receives any command-line arguments
present when the program is executed.
 System.out.println This line outputs the string “Hellow worled.” followed by a new line on the screen.
Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the
string which is passed to it.
 We can use System.out.print(“Hellow worled”);

OOP Chapter 2 [by Haftu M. & Bekalu M.] 4


Integrated Development Environment 3/5/2025

 They are software applications that provide a comprehensive set of tools for developers to
write, edit, debug, test, and deploy code more efficiently.

 Here are the most widely used IDE’s for java programming development

OOP Chapter 2 [by Haftu M. & Bekalu M.] 5


Variables and data types 3/5/2025

 Variables are named memory location named with identifiers.


Data types
 Java defines eight simple types of data: byte, short, int, long, float, double and Boolean.
These can be put in four groups:
 Integers: This group includes byte, short, int, and long, which are for whole valued signed
numbers
 Floating-point numbers: This group includes float and double, which represent numbers with
fractional precision.
 Characters: This group includes char, which represents symbols in a character set, like letters
and numbers,

OOP Chapter 2 [by Haftu M. & Bekalu M.] 6


Variables and data types 3/5/2025

Strings. Strings are used for storing text. A String variable contains a collection
of characters surrounded by double quotes:

Boolean: This group includes boolean, which is a special type for representing
true/false values.

Data types and their size

OOP Chapter 2 [by Haftu M. & Bekalu M.] 7


Continued 3/5/2025

 Java programs are a collection of identifiers, comments, literals, operators, and keywords etc.
1. Identifiers: they are used for class names, method names, and variable names.
 They can be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
 Value and value in java are different , some types of valid identifiers are :- Sum, X1, Y_Z,
here are some invalid identifiers 2x, high-temp, Not/Ok
2. Literals: A constant value in Java is created by using a literal representation of it. 100, 3.96f,
”A+”,”yes” .
3. Comments: They are never executed during program execution, They can be single line,
multiline comments , they are used to offer certain information the reader of the program. //,
/* here are multiple lines */

OOP Chapter 2 [by Haftu M. & Bekalu M.] 8


Continued …. 3/5/2025

4. Java Keywords: 49 reserved keywords currently defined in the Java language. These
keywords, combined with the syntax of the operators and separators, form the definition of the
Java language. These keywords cannot be used as names for a variable, class, or method.

OOP Chapter2[by Haftu M. & Bekalu M.] 9


Variable declaration 3/5/2025

 The main thing which differentiate java variable declaration from c++ variable
declaration is the addition of access modifier before data type.
 Syntax : Access_Modifier data_type Variable Name
 Example
public class Addition {
public int a=34; //here I am declaring variable a and assigning
value
public int b=45;// declaring variable b and assigning value
public static void main(String[] args) {
// we can declare here but no need of adding access modifier
here
int x=67;
int y=89;
}}

OOP Chapter 2 [by Haftu M. & Bekalu M.] 10


Operators in java

1. Arithmetic Operators: Arithmetic Operators Examples


Arithmetic operators are used in
mathematical expressions in the
same way that they are used in
algebra. The following table lists the
arithmetic operators:

3/5/2025
OOP Chapter 2 [by Haftu M. & Bekalu M.]
11
Example with arithmetic operators 3/5/2025

public class Addition {


public int a=34; //here I am declaring
public int b=45;// declaring variable b and assigning value
public static void main(String[] args) {
// we can declare here but no need of adding access modifier here
int x=67;
int y=89;
int s=x+y;// this is addition operator
int m=y%x;// this is modulo operator
System.out.println("the value of s is:"+s);
System.out.println("the remainder is: "+m);
}}
Output:
the value of s is:156
the remainder is: 22
OOP Chapter 2 [by Haftu M. & Bekalu M.] 12
Continued...
• The Bitwise Operators Examples
2. The Bitwise Operators: Java
defines several bitwise operators
which can be applied to the
integer types, long, int, short,
char, and byte. These operators
act upon the individual bits of
their operands.

3/5/2025 OOP Chapter 2 [by Haftu M. & Bekalu M.] 13


Bitwise Operator Example
public class BtExample {
Logic gate operations
public static void main(String[] args) {
int x=3;// 3 is 11 in binary number system AND : 1 & 1 will only be 1, other
int y=2;//2 is 10 in binary number system
int z=x&y;/* & is biwise and operator ,
combinations will result 0.
z will be 10 which is 2 decimal number system */
OR: 0 | 0 will only be 0, other
int or=x|y;//| this is bitwise or operator
System.out.println("The bitwise result is:"+z); combinations will result 1.
System.out.println("The bitwise result is:"+z);
}} Execlusive Or (XOR) :it will be 1 if the
Here is the output:
value of two bits are exactly opposite,
The bitwise result is:2
The bitwise result is:3 else it will be 0.

3/5/2025 OOP Chapter 2 [by Haftu M. & Bekalu M.] 14


Relational Operator
 Sample Java program
3. Relational Operators: public class Compare {
They determine the relationship that public static void main(String[] args)
one variable value has to the other. {
int Total=79;
Specifically, they determine equality boolean y=Total>=75;
System.out.println("Value of Y will be:"+y);
and ordering. }}
output: Value of Y will be: true
 The outcome of these operations is a Boolean
value. They are most frequently used in the
expressions that control the if statement and the
various loop statements.

3/5/2025 OOP Chapter 2 [by Haftu M. & Bekalu M.] 15


The Assignment Operator
 Example
 It is the single equal sign, =. The assignment operator
works in Java much as it does in any other computer
language. It has this general form:
 var = expression;
 Here, the type of var must be compatible with the
data type of expression. The assignment operator does
have one interesting attribute that you may not be
familiar with: it allows you to create a chain of
assignments. For example, consider this fragment:int x,
y, z;
 x = y = z = 100; // set x, y, and z to 100

3/5/2025 OOP Chapter 2 [by Haftu M. & Bekalu M.] 16


Logic oriented programming 3/5/2025

5. Conditional Operator: Java includes a special ternary (three-way) operator that can
replace certain types of if-then-else statements.

 The conditional operator has this general form:

expression1 ? expression2 : expression3

 Here, expression1 can be any expression that is evaluated to a Boolean value.

 If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.


The result of the ? operation is that of the expression evaluated

OOP Chapter 2 [by Haftu M. & Bekalu M.] 17


Example using Ternary Operator 3/5/2025

public class AbsolutCalc {


public static void main(String args[]) {
int absI, i;// declare two variable with one statement
i=5;
absI=i>0?i:-i;
System.out.println("absolute value of 5 is:"+absI);
i=-8;
absI=i<0?-i:i;
System.out.println("absolute value of -8 is:"+absI);
}}
Output:
absolute value of 5 is:5
absolute value of -8 is:8

OOP Chapter 2 [by Haftu M. & Bekalu M.] 18


Data Input in Java 3/5/2025

 Import: it is a keyword that helps the compiler to locate a class that can be used in a
program.
 Java has rich set of predefined class that we can reuse than “reinventing the wheel”
 These classes are grouped to package , which is a collection of related classes, collectively
named java class libraries or java APIs(application programming interfaces).
 All import declaration must appear before any class declaration.
 Example import java.util.Scanner;
 We are importing the class named “Scanner” from the package java.util. , It contains the
collections framework, legacy collection classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes (a string tokenizer, a random-number
generator, and a bit array).

OOP Chapter 2 [by Haftu M. & Bekalu M.] 19


Data Input in Java program example 3/5/2025

 Example

OOP Chapter 2 [by Haftu M. & Bekalu M.] 20


Control statements in java programming 3/5/2025

 A programming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program.
 Java’s program control statements can be classified into the following categories:
 selection, iteration, and jump.
 Selection statements allows program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
 Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops) until the condition is true.
 Jump statements allows program to execute in a nonlinear fashion. All of Java’s control
statements are examined here.

OOP Chapter2 [by Haftu M. & Bekalu M.] 21


Control statements in java programming
 If Statement: It is Java’s conditional Sample java program
public class OddEven {
branch statement. It can be used to public static void main(String[] args) {
int a=9;//
route program execution through two if (a%2!=0)// here it checks if 9/2
remainder is d/t from 0
different paths. {
System.out.println(a+ " is odd number");
If(condition){ }
else
Statement;} {
System.out.println();
}
else{

Statement2;}

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 22


Control statements in java programming
 Nested if 2 : is an if statement that is the Sample java program
public class NestedIf {
target of another if or else. They are very public
{
static void main(String args[])
//nested if
common in programming. int x=10;
if(x>=0) {
 When you nest ifs, the main thing to if(x%5==0) {
System.out.println("x >0 and multiple
remember is that an else statement of 5");
}
always refers to the nearest if statement else {
System.out.println("x >0 but not
that is within the same block as the else multiple of 5");
}
and that is not already associated with an }else {
System.out.println("x is less than 0");
else. }}}
Output: x >0 and multiple of 5

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 23


Control statements in java programming
3: The if-else-if Ladder: A common programming Sample java program
construct that is based upon a sequence of nested ifs is
the if-else-if ladder.

if(condition1)
Statement 1;

else if(condition 2)
Statement2;

else if(condtion3)
Statement3 ;
The if statements are executed from the top to down

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 24


Control statements in java programming
public class GradePointCalc {
3: switch statements : Switch Statements: Java's multi way public static void main(String[] args) {
double grade,grade_point,credit_hour=3;
branch statement. It provides an easy way to dispatch for(int i=60;i<=100;i+=10)
switch(i) {
execution to different parts of your code based on the case 60:
grade=2;
grade_point=grade*credit_hour;
value of an expression. As such, it often provides a better System.out.println("grade is score 60 is"+grade_point);
break;
alternative than a large series of if-else-if statements. case 70:
grade=3;
switch(case){ grade_point=grade*credit_hour;
System.out.println("grade is score 70 is"+grade_point);
case value1: break;
case 80:
Statement1; grade=3.75;
grade_point=grade*credit_hour;
break; System.out.println("grade is score 80 is"+grade_point);
case value2: break;
case 90:
Statement2; grade=4;
grade_point=grade*credit_hour;
break; System.out.println("grade is score 80 is"+grade_point);
break;
default: case 100:
Statement; grade=4;
grade_point=grade*credit_hour;
break; System.out.println("Excellent"+grade_point);
break;
}}}
3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 25
Iteration Statements
for, while, and do-while. These statements create what we commonly call loops.

a loop repeatedly executes the same set of instructions until a termination condition is met.

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 26


Jump statements
break statement: A break statement takes control out of the loop.

continue statement: A continue statement takes control to the beginning of the loop.

 The continue statement breaks one iteration (in the loop), if a specified condition occurs,

and continues with the next iteration in the loop.

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 27


Continued
Sample java program with continue statement:

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 28


Array Declaration and manipulation
 An array is a named collection of contiguous storage locations that are next to each other

that contain data items of the same data type.

 Arrays offer a more streamlined way to store data than using individual data items for

each variable.

 Arrays also allow us to work with their data more efficiently than with data stored in

individual variables.

 Let’s take we do have 10 different values to be stored for further processing if we don’t plan

to use array we are expected to create 10 different named memory location(Variables),

this will be somehow tedious.


3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 29
One-Dimensional Arrays
 An array is considered a data structure.

 A data structure is an organized collection of data.

 In an array, data are arranged in a linear or sequence which can be detected when the

program is compiled.

Declaring and Creating Arrays

 arrays in Java are treated as objects.

 Like objects, they are instantiated with the new operator and they have instance variables

(for example, length).

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 30


Declaring and Creating Arrays
 Like variables for objects, array variables are considered reference variables.

 When arrays are used as parameters, a reference to the array is passed rather than a copy

of the entire array.

 The primary difference between arrays and full-fledged objects is that arrays aren’t

defined in terms of an Array class. Thus, arrays don’t fit into Java’s Object hierarchy. They

don’t inherit any properties from Object and they cannot be subclassed.

 We can consider array as a container that contains a number of variables that can be

accessed through the relative position of the array elements.

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 31


Declaring and Creating Arrays
 The variables are called components. If an array object has N components, then we say

that the array length is N.

 Each of the components of the array has the same type, which is called the array’s

component type. An empty array is one that contains zero variables.

 A one-dimensional array has components that are called the array’s elements. Their type is

the array’s element type.

 An array’s elements may be of any type, including primitive and reference types. This

means you can have arrays of int, char, boolean, String, Object,Image, TextField

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 32


Declaring and Creating Arrays
When declaring a one-dimensional array, you have to indicate both the

array’s element type and its length.

Just as in declaring and creating other kinds of objects, creating an array

object requires that we create both a name for the array and then the array

itself. Example
public class ArrayDeclaration {
public static void main(String[] args) {
int arr[];// am declare a name for array
arr=new int[4];// am creating the array itself
}}
3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 33
Declaring and Creating Arrays
 Array can be declared as follows
int arr1 [ ];//the brackets may follow the array's name
int [] array1;//the bracket may proceed the array's name
Sample array Example
public class ArrayDeclaration {
public static void main(String[] args) {
String Starray[]=new String[5];//String array declaration
for(int i=0;i<Starray.length;i++) {
Starray[i]=new String("Hellow"+i);//assigning array value
System.out.println("Array of:"+i+" "+Starray[i]);
}}}

3/5/2025 OOP Chapter2 [by Haftu M. & Bekalu M.] 34


Initializing Arrays
 Array elements are automatically initialized to default values that depend on the element type:

 Boolean elements are initialized to false, and integer and real types are initialized to 0.

 Arrays can also be assigned initial values when they are created, although this is feasible only

for relatively small arrays. An array initializer is written as a list of expressions separated by

commas and enclosed by braces.

 Example

int Evens[]= {0,2,4,6,8};


String Names[]= {"Abel","Bethelhem","Rahel"};//Assigning String values

3/5/2025 35
OOP Chapter2 [by Haftu M. & Bekalu M.]
Assigning and Using Array Values
 Array elements can be used in the same way as other variables. The only difference, of course, is

that references to the elements are subscripted.

 For example, the following assignment statements assign values to the elements of two arrays,

named Evens and Names:


int Evens[]= new int[6];//array declaration
Evens[4]=10;
Evens[2]=12;
Evens[3]=20;
String Names[]=new String[4]; //array declaration
Names[2]="Aster";
Names[3]="Gelila";
Names[4]="Yared";

3/5/2025 36
OOP Chapter2 [by Haftu M. & Bekalu M.]
Sample code snippet
package ethioTechnotube;
public class ArrayDeclaration {
public static void main(String[] args) {
int Evens[]= {0,2,4,6,8};
String Names[]= {"Abel","Bethelhem","Rahel"};//Assigning String values
System.out.println("first even:"+Evens[0]);
String Starray[]=new String[5];//String array declaration
for(int i=0;i<Starray.length;i++) {
Starray[i]=new String("Hellow"+i);//assigning array value
System.out.println("Array of:"+i+" "+Starray[i]);
}}}
Output
first even:0
Array of:0 Hellow0
Array of:1 Hellow1
Array of:2 Hellow2
Array of:3 Hellow3
Array of:4 Hellow4
3/5/2025 37
OOP Chapter2 [by Haftu M. & Bekalu M.]
Group Discussion

Group 1: Variable and Variable Declaration

Group 2:Operators in java

 Group 3:Java’s control statements

Group 4: Java Input /output

Group5: Array Declaration and manipulation

3/5/2025 38
OOP Chapter2 [by Haftu M. & Bekalu M.]
End of Chapter Two ,
Thank You for Your Attention!!
Do you have any question?????
Chapter 3: Classes objects and methods
[Coming Soon…]
End!! 39

You might also like