88
Introduction to java Object-Oriented Programming Legendary Carter 1

Java notes(OOP) jkuat IT esection

Embed Size (px)

Citation preview

Page 1: Java notes(OOP) jkuat IT esection

Introduction to java

Object-Oriented Programming

Legendary Carter

1

Page 2: Java notes(OOP) jkuat IT esection

Intro…

3-2

Java was conceived to develop advanced software for a wide variety of network devices and  systems. The language drew from a variety of languages such as C++, Eiffel, SmallTalk, Objective C. The result is a language platform that has proven suitable for developing secure, distributed, network-based end-user applications in environments ranging from network embedded devices to the World-Wide Web and the desktop. Java attempts to provide a platform for the development of secure, high performance, robust applications on multiple platforms in heterogeneous, distributed networks. Java does that by being architecture neutral, portable, and dynamically adaptable.

Page 3: Java notes(OOP) jkuat IT esection

What is Java?

3-3

Java is an Object Oriented programming language. This means that Java is a language which can model every day real objects. The code that is written to model an every day object is called a class.

Just as real day objects are composed of other objects so can classes be composed of other classes.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging, running

Page 4: Java notes(OOP) jkuat IT esection

What is Object Oriented Programming (OOP)?

3-4

OOP is software design method that models the characteristics of real or abstract objects using software classes and object

Classes and Objects A class is a template/blue print that

describes the behaviors/states that object of its type support.It is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions.

Page 5: Java notes(OOP) jkuat IT esection

Objects

3-5

An object is an instance of a class. A program can create and use more than one object (instance) of the same class.

Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. Can model real-world objects Can represent GUI (Graphical User Interface)

components Can represent software entities (events, files,

images, etc.) Can represent abstract concepts (for example,

rules of a game, a particular type of dance, etc.)

Page 6: Java notes(OOP) jkuat IT esection

Characteristics of Objects

6

Identity makes an object different from other objects created

from the same class. State

defined by the contents of an object’s attributes. Objects state vary during the execution of program.

Behavior Defined by the messages (functions/methods) an

object provides.

Page 7: Java notes(OOP) jkuat IT esection

Object Life Cycle

7

Object Creation Object Usage Object Disposal

Page 8: Java notes(OOP) jkuat IT esection

Object Creation

8

Objects are created by instantiating a class.ClassName object = new ClassName();

Object creation involves three actions: Declaration

Declaring the type of data Instantiation

Creating a memory space to store the object Initialization

Intializing the attributes in the object.

Page 9: Java notes(OOP) jkuat IT esection

Object Usage

9

Using an object we can get information about it change its state ask it to perform some actions

This done by Manipulating / inspecting its variables Calling its methods

Page 10: Java notes(OOP) jkuat IT esection

Object Disposal

10

The Java runtime automatically deletes objects when they are no longer referenced.

This process is called garbage collection.

Page 11: Java notes(OOP) jkuat IT esection

Java is an Object-Oriented Language.

As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Parsing 11

Page 12: Java notes(OOP) jkuat IT esection

OOP

3-12

An OO program models the application as a world of interacting objects.

An object can create other objects. An object can call another object’s

(and its own) methods (that is, “send messages”).

An object has data fields, which hold values that can change while the program is running.

Page 13: Java notes(OOP) jkuat IT esection

Class vs. Object

3-13

A piece of the program’s source code

Written by a programmer

An entity in a running program

Created when the program is running (by the main method or a constructor or another method)

Page 14: Java notes(OOP) jkuat IT esection

Class vs. Object

3-14

Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects

Specifies the possible behaviors of its objects

Holds specific values of attributes; these values can change while the program is running

Behaves appropriately when called upon

Page 15: Java notes(OOP) jkuat IT esection

The three OOP Principles

3-15

Inheritance is the process by which one class acquires the properties of another class. The parent class called Superclass and the inherited class is called Subclass. The subclass inherit method, objects, constructors and variables of a super class.

Encapsulation is the process of hiding the field and methods of a class by making it private. the mechanism binds together code and the data it manipulates, and keeps both safe from outside interference and misuse..

Polymorphism is mechanism a program is able to take more than one form, it is a mechanism of assigning different behavior or value in subclass to some thing that was in super class(parent class).

Page 16: Java notes(OOP) jkuat IT esection

The Characteristics Of Java:

3-16

Simple: The fundamentals are learned quickly; programmers can be productive from the very beginning.

Familiar: Java looks like a familiar language C++, but removes some of the complexities of C++

Object oriented: so it can take advantage of modern software development methodologies. Programmers can access existing libraries of tested objects, which can be extended to provide new behavior.

Portable: Java is designed to support applications capable of executing on a variety of hardware architectures and operating systems.

Page 17: Java notes(OOP) jkuat IT esection

3-17

The architecture-neutral and portable language platform of Java is known as the Java Virtual Machine

Multithreaded: for applications with many concurrent threads of activity.

Interpreted: for maximum portability and dynamic capabilities.

Robust and Secure: Java provides extensive compile-time and run-time checking. There are no explicit pointers, and the automatic garbage collection eliminates many programming errors. Sophisticated security features have been designed into the language and run-time system.

Page 18: Java notes(OOP) jkuat IT esection

Development Process with Java Java source files are written as plain text

documents. The programmer typically writes Java source code in an Integrated Development Environment (IDE) for programming. An IDE supports the programmer in the task of writing code, e.g. it provides auto-formating of the source code, highlighting of the important keywords, etc.

At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. These instructions are stored in .class files and can be executed by the Java Virtual Machine. 18

Page 19: Java notes(OOP) jkuat IT esection

Creating a Java Program

3-19

The standard way of producing and executing a program is:

Edit the program with a text editor; save the text with an appropriate name.

Compile: the program to produce the object code

Link: the object code with some standard functions to produce an executable file

Execute (run): the program

Page 20: Java notes(OOP) jkuat IT esection

A Java program is both compiled and interpreted

3-20

with the compiler, a Java program is translated into an intermediate platform-independent language called Java bytecodes

with an interpreter, each Java bytecode instruction is interpreted and run on the computer. Compilation happens just once; interpretation occurs each time the program is executed

Page 21: Java notes(OOP) jkuat IT esection

3-21

Page 22: Java notes(OOP) jkuat IT esection

Types of Java Programs

3-22

There are two classes of Java programs

Java stand-alone applications: they are like any other application written in a high level language

Java applets: they are special purpose applications specifically designed to be remotely downloaded and run in a client machine

Page 23: Java notes(OOP) jkuat IT esection

public class SomeClass

3-23

Fields

Constructors

Methods}

Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects

Procedures for constructing a new object of this class and initializing its fields

Actions that an object of this class can take (behaviors)

{

Class header

SomeClass.java

import ... import statements

Page 24: Java notes(OOP) jkuat IT esection

Components of a Java program

3-24

Comments  // Object oriented programming // Written 10/09/2013 // OUR java program!   public class ClassName{ public static void main(String[]

args) { System.out.println(“ MY OUTPUT"); } }

Page 25: Java notes(OOP) jkuat IT esection

3-25

The program starts with a comment: //Object oriented programming // Written 10/09/2013 // OUR java program! all the characters after the symbols // up to the

end of the line are ignored; they do not change the way the program runs, but they can be very useful in making the program easier to understand; they should be used to clarify some part of a program, to explain what a program does and how it does it.

There could also be comments beginning with a /* and continue, possibly across many lines, until a */ is found, like so:

 

Page 26: Java notes(OOP) jkuat IT esection

Import statements In Java you have to access a class

always via its full-qualified name, e.g. the package name and the class name.

in Java if a fully qualified name, which includes the package and the class name, is given then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.

Example import java.util.Scanner; 26

Page 27: Java notes(OOP) jkuat IT esection

3-27

/*

A class definition: Java programs include at least a class definition such as public class

A class can be define as the blueprint or prototype that defines the field and methods common to all objects of certain kind

ClassName. The class extends from the first opening curly brace { to the last closing curly brace }

The main() method: a method is a collection of programming statements that have been given a name and that execute when called to run. Methods are also delimited by curly braces.

Page 28: Java notes(OOP) jkuat IT esection

The main() method

3-28

All Java applications (not applets) must have a class (only one) with a main() method where execution begins;

Each application needs at least one main method to execute:When you run the "java" executable, you specify the class you wish to run. The Java Virtual Machine then looks for a main method in the class if it does not find one it will complain.

programming statements within main() are executed one by one, until its termination;

the main() method is preceded by the words public static void called modifiers;

Page 29: Java notes(OOP) jkuat IT esection

3-29

The main() method always has a list of command line arguments that are passed to the program main(String[] args) (which we are going to ignore for now)

Page 30: Java notes(OOP) jkuat IT esection

Statements

3-30

Statements are instructions to the computer to determines what to do end with a semicolon ';' (a terminator, not a separator)

In this example there is only one statement System.out.println(" MY OUTPUT "); to print a message and move the cursor to the next line, by using the method System.out.println() to print a constant string of characters and a newline. Within a method the statements are executed in sequential order: sequential execution.

Page 31: Java notes(OOP) jkuat IT esection

Reserved words

3-31

class, static, public, void have all been reserved by the designers and they can't be used with any other meaning. (For a complete list see the prescribed book.)

Case sensitive Java compilers are case sensitive,

meaning that they see lower case and upper case differently. Upper / lower case should be used so programmers can better read the code. Any literal used for identification of an entity is called an identifier. In Java, the identifiers aString AString ASTRING are all different:

Page 32: Java notes(OOP) jkuat IT esection

3-32

Running a Java Program % javac ClassName.java // compilation % java ClassName // running by interpreter MY OUTPUT // output the compiler javac produces a file called

ClassName.class; this file is to be interpreted by the interpreter

java; you use the .java extension when compiling a

file, but you do not use the .class extension when calling the interpreter to run the program;

IMPORTANT: if a class, such as ClassName above, is declared public, it must be compiled in a file called ClassName.java. Otherwise the compiler will give an error.

Page 33: Java notes(OOP) jkuat IT esection

Programming Style

3-33

Adhering to a style makes programs easier to read for humans. There are rules that most Java programmers follow, such as:

One statement per line Indentation: 3 spaces. Indicates dependency

between statements. Comments should be added to clarify code

sections that are not obvious Blank lines: should be used to separate

different logic sections of the code Naming (identifiers): we did in c and c++

(recal)

Page 34: Java notes(OOP) jkuat IT esection

Programming Errors

3-34

Programming errors can be divided into: Compilation time errors: are detected by

the compiler at compilation time. The executable is not created. i.e instructing the computer to do what cannot be done by the machine.

Syntax errors: appear when the program runs i.e when a rule of programming is violated. Typically execution stops when an exception such as this happens, it is possible to handle these errors

Logical errors: the program compiles and runs with no problems but gives out wrong results due to wrong formulae.

Page 35: Java notes(OOP) jkuat IT esection

Variables

A variable is a programming concept of a location in the memory for storing a value that may change from time to time. However, the values that can be stored in a variable must be of the same data type. A program must store the values it is using for computation in variables or other advanced storage locations.

35

Page 36: Java notes(OOP) jkuat IT esection

Declaration of variablesDeclaring a variable instructs the computer to allocate a memory space for storing a value of that type.ExampleThe following statement instructs the computer to declare a variable named x, for storing an integer (whole number)int x;Initialization of variablesYou can give a variable some initial value during declaration (also known as initializing a variable). For example to initialize floats a, b, and c to zero during declaration, we writedouble a=0, b=0, c=0;To initialize only b, we writefloat a, b=0, c;

 

36

Page 37: Java notes(OOP) jkuat IT esection

Variable rules /naming conventions

a) A variable must be declared before being used.

b) A variable can not be declared more than once

c) A variable can be declared anywhere in the program I.e. it’s not a must to declare it at the beginning of a Class. We can declare it at the middle of other statements or Methods.

d) A library key word must not be used when declaring a variable e.g. public, private etc.

37

Page 38: Java notes(OOP) jkuat IT esection

Java Basic Data Types Variables are nothing but reserved memory

locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

There are two data types available in Java: Primitive Data Types Reference/Object Data Types

38

Page 39: Java notes(OOP) jkuat IT esection

Primitive Data Types: There are eight primitive data types supported by

Java. Primitive data types are predefined by the language and named by a keyword. Let us now look into detail about the eight primitive data types.

byte:Byte data type is an 8-bit signed two's complement

integer. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7 -1) Default value is 0 Byte data type is used to save space in large arrays,

mainly in place of integers, since a byte is four times smaller than an int.

Example: byte a = 100 , byte b = -50 39

Page 40: Java notes(OOP) jkuat IT esection

short: Short data type is a 16-bit signed two's complement

integer. Minimum value is -32,768 (-2^15) Maximum value is 32,767 (inclusive) (2^15 -1) Short data type can also be used to save memory as

byte data type. A short is 2 times smaller than an int Default value is 0. Example: short s = 10000, short r = -20000int: Int data type is a 32-bit signed two's complement

integer. Minimum value is - 2,147,483,648.(-2^31) Maximum value is 2,147,483,647(inclusive).(2^31 -

1) Int is generally used as the default data type for

integral values unless there is a concern about memory.

The default value is 0. Example: int a = 100000, int b = -200000

40

Page 41: Java notes(OOP) jkuat IT esection

Long: Long data type is a 64-bit signed two's complement

integer. Minimum value is -9,223,372,036,854,775,808.(-2^63) Maximum value is 9,223,372,036,854,775,807

(inclusive). (2^63 -1) This type is used when a wider range than int is

needed. Default value is 0L. Example: long a = 100000L, int b = -200000LFloat: Float data type is a single-precision 32-bit IEEE 754

floating point. Float is mainly used to save memory in large arrays of

floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as

currency. Example: float f1 = 234.5f

41

Page 42: Java notes(OOP) jkuat IT esection

Double: double data type is a double-precision 64-bit IEEE

754 floating point. This data type is generally used as the default data

type for decimal values, generally the default choice.

Double data type should never be used for precise values such as currency.

Default value is 0.0d. Example: double d1 = 123.4Boolean: boolean data type represents one bit of information. There are only two possible values: true and false. This data type is used for simple flags that track

true/false conditions. Default value is false. Example: boolean one = true

42

Page 43: Java notes(OOP) jkuat IT esection

Char: char data type is a single 16-bit Unicode character. Minimum value is '\u0000' (or 0). Char data type is used to store any character. Example: char letterA ='A'Reference Data Types: Reference variables are created using defined

constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.

Class objects, and various type of array variables come under reference data type.

Default value of any reference variable is null. A reference variable can be used to refer to any object

of the declared type or any compatible type. Example: Animal animal = new Animal("giraffe"); 43

Page 44: Java notes(OOP) jkuat IT esection

Types of variables

There are three kinds of variables in Java:

1. Local variables 2. Instance variables 3. Class/static variables

44

Page 45: Java notes(OOP) jkuat IT esection

Local variables: Local variables are declared in methods,

constructors, or blocks. Local variables are created when the method,

constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.

Access modifiers cannot be used for local variables.

Local variables are visible only within the declared method, constructor or block.

Local variables are implemented at stack level internally.

There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

45

Page 46: Java notes(OOP) jkuat IT esection

Example

46

Page 47: Java notes(OOP) jkuat IT esection

Instance variables: Instance variables are declared in a class, but outside

a method, constructor or any block. When a space is allocated for an object in the heap, a

slot for each instance variable value is created. Instance variables are created when an object is

created with the use of the keyword 'new' and destroyed when the object is destroyed.

Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

Instance variables can be declared in class level before or after use.

Access modifiers can be given for instance variables.47

Page 48: Java notes(OOP) jkuat IT esection

Example will be given in class…..

48

Page 49: Java notes(OOP) jkuat IT esection

Class/static variables: Class variables also known as static variables are

declared with the static keyword in a class, but outside a method, constructor or a block.

There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.

Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.

Static variables are created when the program starts and destroyed when the program stops.

49

Page 50: Java notes(OOP) jkuat IT esection

50

Page 51: Java notes(OOP) jkuat IT esection

Constants/Literals A constant just like a variable, is used

to store values in memory. A constant’s value however, may not change. Constants are used to store values that do not change in any run of the program including the pi of a circle, the tax of a payroll processing program, the pass mark in an examination processing program, etc.

51

Page 52: Java notes(OOP) jkuat IT esection

Java - Methods A Java method is a collection of statements

that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.

52

Page 53: Java notes(OOP) jkuat IT esection

53

Page 54: Java notes(OOP) jkuat IT esection

Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.

Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.

Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

Method Body: The method body contains a collection of statements that define what the method does.

54

Page 55: Java notes(OOP) jkuat IT esection

Calling a Method: In creating a method, you give a

definition of what the method is to do. To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.

When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached.

55

Page 56: Java notes(OOP) jkuat IT esection

ExampleCreating Object1Classname Object1= new Classname();Calling a method using an objectObject1.Method();

56

Page 57: Java notes(OOP) jkuat IT esection

57

Page 58: Java notes(OOP) jkuat IT esection

Mathematics in JavaTo assist you with various types of calculations, the java.lang package contains a class named Math. In this class are the most commonly needed operations in mathematics. The java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.The Minimum and Minimum of Two Values

58

Page 59: Java notes(OOP) jkuat IT esection

59

Page 60: Java notes(OOP) jkuat IT esection

The Power of a Number

60

Page 61: Java notes(OOP) jkuat IT esection

The Square Root

61

Page 62: Java notes(OOP) jkuat IT esection

Classes and Source Files

3-62

Each class is stored in a separate file

The name of the file must be the same as the name of the class, with the extension .javapublic class Car

{ ...}

Car.java By convention, the name of a class (and its source file) always starts with a capital letter.

(In Java, all names are case-sensitive.)

Page 63: Java notes(OOP) jkuat IT esection

Libraries

3-63

Java programs are usually not written from scratch.

There are hundreds of library classes for all occasions.

Library classes are organized into packages. For example:

java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — GUI development package

Page 64: Java notes(OOP) jkuat IT esection

import

3-64

Full library class names include the package name. For example:

java.awt.Color javax.swing.JButton

import statements at the top of the source file let you refer to library classes by their short names: import javax.swing.JButton; JButton go = new JButton("Go");

Fully-qualified name

Page 65: Java notes(OOP) jkuat IT esection

import (cont’d)

3-65

You can import names for all the classes in a package by using a wildcard .*:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes.

Imports all classes from awt, awt.event, and swing packages

Page 66: Java notes(OOP) jkuat IT esection

Java Basic Operators

3-66

An operator is used in a program to manipulate data types values. It combines two operands in an expression.

i.e. z = x + y Unary and Binary operators.  Unary operator takes only one operand

while Binary operator takes two operands. e.g. +, - are Binary while ++, -- are Unary operators.

Evaluation of an expression.An expression is evaluated from the left to

the right hand side.

Page 67: Java notes(OOP) jkuat IT esection

Types of Operators.

Arithmatic Operators Relational Operators Logical Operators Assignment Operators

67

Page 68: Java notes(OOP) jkuat IT esection

1.Arithmatic Operators. An Arithmatic operator operates on

two operands in an expression to produce a value (number). The possible Arithmatic operators are:-

Operator Meaning + Addition - Substraction * Multiplication / Division % Modulus 68

Page 69: Java notes(OOP) jkuat IT esection

2.Relational Operators/ Conditional Operators.

Relational operators are used in Boolean expression to compare the values of the two operands which produce a value of either True or False. A Boolean expression is an expression whose value can either be True or False.

Operator Meaning > Greater than > = Greater than or equal to < Less than < = Less than or equal to = = Equal to ! = Not equal to 69

Page 70: Java notes(OOP) jkuat IT esection

3.Logical Operators Logical opeartors are used to

combine two Boolean expressions into a compound Boolean expression. The truth table rules are used to test the Truth or False of a compound expression depending on the truth and false of each expression in the compound expression.

Operator Meaning && And // Or ! Not(Negation)   70

Page 71: Java notes(OOP) jkuat IT esection

Truth Table

Where T stands for Truth and F stands for False.

71

Page 72: Java notes(OOP) jkuat IT esection

4.Assignment Operator (=)

The assignment operator is used to assign the variable on the left hand side the value of expression which is on the right hand side.

Examples a = b means “Take the value of b and store it in a

variable a” x = x + 1 means “Take the value of x, i.e.

increment the value of x by one or just increment x”

72

Page 73: Java notes(OOP) jkuat IT esection

5.Short-cut Operators Java has shortcuts for writting some expressions. The shortcut

operators include the following + +,- -,+ =, * =, / =. These operators will be explained by using examples below.

Examples; a=b; Means ”Take the value of b and Store it in a Variable a” x=x+1; Means”Take the Value of x, add one to it, and store

results back to a variable x; x=x-1; Means”Take the Value of x, subtract one to it, and

store results back to a variable x;

Expression Equivalent to   x+ + x = x + 1 x- - x = x - 1 x + = y x = x + y x - = y x = x - y x * = y x = x * y

73

Page 74: Java notes(OOP) jkuat IT esection

6.Ternary Operators/Conditional Operator ( ? : ):

  This is used in decision making. It takes

the following:-Expression 1 ? Expression 2:

Expression 3

variable x = (expression) ? value if true : value if false

Expression 1 is evaluated if it is True, then Expression 2 is evaluated and becomes the value of the whole expression. Otherwise Expression 3 is evaluated and becomes the value of the expression.

Example..

74

Page 75: Java notes(OOP) jkuat IT esection

75

Page 76: Java notes(OOP) jkuat IT esection

Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

76

Page 77: Java notes(OOP) jkuat IT esection

77

Page 78: Java notes(OOP) jkuat IT esection

CONTROL STRUCTURES Control structures are structures used to control the

execution of programs statements. They include decision making and repetition.

Sequential execution alone is not enough to solve typical read word problems because of the following reasons.

-Need for decision making -Need for repetition (a)What is decision making? Decision making is selection of the various

alternatives in other words; we select which alternative path to follow depending on the outcome of some conditions.

(b)If we have two alternatives. Here, we test he Boolean condition and choose one

path to follow. If the condition is true, or the other path if the condition is False.

78

Page 79: Java notes(OOP) jkuat IT esection

(c)If we have more than two alternatives. Here, we do multiple testing of conditions, each time choosing a path to follow. If there are many alternatives in a problem, we have sequence of conditions to be tested, but each result to either True or False value.Structures used in Java programming.Three decision making structures used in Java programming are:- The if……. else structure The nested if..else structures The Switch structure Ternary structure/Condition

79

Page 80: Java notes(OOP) jkuat IT esection

(a)The If…. else structure.The If ….else structure basically means “if a condition is True, then do something (True statement), else do something else (False statement) SyntaxIf(condition) {Path1 (True statement)}Else{Path2 (False statement)}

80

Page 81: Java notes(OOP) jkuat IT esection

Steps in execution Test condition If it is true, then execute path1 (True

statement)if it is False, then execute path2(False statement)

Go to what follows the if……else structure

N. B The condition must be BooleanEXAMPLE 1Write the program to output “PASS” if the mean of three numbers is more or equal to 50 and output”FAIL”if the mean is less than 50.

81

Page 82: Java notes(OOP) jkuat IT esection

(b) Nested if…..else structures.

Nesting of if…..else statement is applied when you have more than one condition to test and the condition depends on the outcome of the previous one

Syntaxif(condition1){True statement1;}else if (condition2);{True statement2;}..else{True statementn;} 82

Page 83: Java notes(OOP) jkuat IT esection

Examples 1Assume the grade obtained in an exam depends on the mean mark of three subjects as shown below. Design and writ e a program to input three marks and compute the grade Mean mark GradeAt least 70 up to 100……......………..............AAt least 60 up to less than 70…………………...BAt least 50 but less than 60…………….………..CBelow 50……………………………………….………..F

83

Page 84: Java notes(OOP) jkuat IT esection

Example 3 Assume that every employee gets 20% house

allowance. Assume also that those earning at least 10,000 pay some tax at the rate of 10%. Design and Write algorithm and code to input the net salary N.B Net Salary = salary+house allowance-tax

84

Page 85: Java notes(OOP) jkuat IT esection

TEST TABLE.The test table is the programmer’s tool for testing the algorithm as well as the code/program for logical correctness.

Example 2

Design and write a program that reads in the age of a person and outputs an appropriate message based on;If age<18 print “Below 18 years” and If age>=18 print “Issue an ID”

85

Page 86: Java notes(OOP) jkuat IT esection

Example

86

Object Usage:

void someMethod(){Classname object = new

Classname();if(object.isMku){

Object.Dit();}

}

Identity

State

Behavior

Objects attributes and methods are accessed by using . operator. Java does not have -> operator like in C and C++.

Page 87: Java notes(OOP) jkuat IT esection

Java Data Types

87

Two major data types Primitive

Because java program has to run on different architecture and OS, the size of the data should remain same. Otherwise, on different machines the output will be different

Reference All objects are of type reference data type. Java

doesn’t allow directly to access memory. But objects are refered by pointers only.

Page 88: Java notes(OOP) jkuat IT esection

Reference Data Types

88

Examples: Arrays Strings Objects Interfaces

The name reference means a pointer in the memory. All objects are referred by their memory location only. But user cannot directly access memory location.

Memory management is taken care by JVM itself.