SlideShare une entreprise Scribd logo
1  sur  88
Introduction to java
Object-Oriented Programming
Legendary Carter
1
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.
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
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.
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.)
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.
Object Life Cycle
7
 Object Creation
 Object Usage
 Object Disposal
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.
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
Object Disposal
10
 The Java runtime automatically deletes objects when
they are no longer referenced.
 This process is called garbage collection.
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
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.
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)
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
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).
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.
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.
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
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
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
3-21
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
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
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");
 }
 }
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:

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
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.
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;
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)
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.
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:
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.
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)
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.
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
Declaration of variables
Declaring a variable instructs the computer to allocate a
memory space for storing a value of that type.Example
The following statement instructs the computer to declare a
variable named x, for storing an integer (whole number)
int x;
Initialization of variables
You 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
write
double a=0, b=0, c=0;
To initialize only b, we write
float a, b=0, c; 36
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
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
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
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 = -20000
int:
 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
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 = -200000L
Float:
 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
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.4
Boolean:
 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
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
Types of variables
 There are three kinds of variables in
Java:
1. Local variables
2. Instance variables
3. Class/static variables
44
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 should45
Example
46
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
 Example will be given in class…..
48
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
50
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
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
53
 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 of54
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
Example
Creating Object1
Classname Object1= new Classname();
Calling a method using an object
Object1.Method();
56
57
Mathematics in Java
To 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
59
The Power of a Number
60
The Square Root
61
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 .java
public 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.)
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
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
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
Imports all classes
from awt, awt.event,
and swing packages
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.
Types of Operators.
 Arithmatic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
67
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
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
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
Truth Table
Where T stands for Truth and F stands for False.
71
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
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
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
75
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
77
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
(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
(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)
 Syntax
If(condition)
{
Path1 (True statement)
}
Else
{
Path2 (False statement)
}
80
 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 Boolean
EXAMPLE 1
Write 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
(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
 Syntax
if(condition1)
{
True statement1;
}
else if (condition2);
{
True statement2;
}
.
.
else
{
True statementn;
}
82
Examples 1
Assume 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 Grade
At least 70 up to 100……......………..............A
At least 60 up to less than 70…………………...B
At least 50 but less than 60…………….………..C
Below 50……………………………………….………..F
83
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
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
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++.
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.
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.

Contenu connexe

Tendances

Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionKnoldus Inc.
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET frameworkRicha Handa
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionSina Manavi
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionMudit Gupta
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handlingmussawir20
 
Banking Management System Project
Banking Management System ProjectBanking Management System Project
Banking Management System ProjectChaudhry Sajid
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and AwarenessAbdul Rahman Sherzad
 
Complaint management system
Complaint management systemComplaint management system
Complaint management systemnamanbiltiwala
 
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKMax Pronko
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 

Tendances (20)

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET framework
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL Injection
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Java History
Java HistoryJava History
Java History
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
 
Banking Management System Project
Banking Management System ProjectBanking Management System Project
Banking Management System Project
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Client Side Technologies
Client Side TechnologiesClient Side Technologies
Client Side Technologies
 
Applets
AppletsApplets
Applets
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
 
Complaint management system
Complaint management systemComplaint management system
Complaint management system
 
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
 
dbms lab manual
dbms lab manualdbms lab manual
dbms lab manual
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 

En vedette

Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with javaHawkman Academy
 
Software para diagnostico, optimización y utilerias
Software para diagnostico, optimización y utileriasSoftware para diagnostico, optimización y utilerias
Software para diagnostico, optimización y utileriasxnoxtrax
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesteach4uin
 
Java Exploit Analysis .
Java Exploit Analysis .Java Exploit Analysis .
Java Exploit Analysis .Rahul Sasi
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained SimplyCiaran McHale
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 

En vedette (20)

Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
 
Java Class Loader
Java Class LoaderJava Class Loader
Java Class Loader
 
Software para diagnostico, optimización y utilerias
Software para diagnostico, optimización y utileriasSoftware para diagnostico, optimización y utilerias
Software para diagnostico, optimización y utilerias
 
Java
JavaJava
Java
 
Presentation
PresentationPresentation
Presentation
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Java Exploit Analysis .
Java Exploit Analysis .Java Exploit Analysis .
Java Exploit Analysis .
 
Java Reflection @KonaTechAdda
Java Reflection @KonaTechAddaJava Reflection @KonaTechAdda
Java Reflection @KonaTechAdda
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Java Datatypes
Java DatatypesJava Datatypes
Java Datatypes
 
Reflection in Java
Reflection in JavaReflection in Java
Reflection in Java
 
Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained Simply
 
Java features
Java featuresJava features
Java features
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 

Similaire à Java notes(OOP) jkuat IT esection

Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objectsvmadan89
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...AnkurSingh340457
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Languagedheva B
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to JavaDevaKumari Vijay
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programmingPraveen Chowdary
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSujit Majety
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
POP vs OOP Introduction
POP vs OOP IntroductionPOP vs OOP Introduction
POP vs OOP IntroductionHashni T
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java LanguagePawanMM
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 

Similaire à Java notes(OOP) jkuat IT esection (20)

Java_presesntation.ppt
Java_presesntation.pptJava_presesntation.ppt
Java_presesntation.ppt
 
Java notes
Java notesJava notes
Java notes
 
INTRODUCTION TO JAVA
INTRODUCTION TO JAVAINTRODUCTION TO JAVA
INTRODUCTION TO JAVA
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
 
MCA NOTES.pdf
MCA NOTES.pdfMCA NOTES.pdf
MCA NOTES.pdf
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Language
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Java pdf
Java   pdfJava   pdf
Java pdf
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
POP vs OOP Introduction
POP vs OOP IntroductionPOP vs OOP Introduction
POP vs OOP Introduction
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 

Java notes(OOP) jkuat IT esection

  • 1. Introduction to java Object-Oriented Programming Legendary Carter 1
  • 2. 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.
  • 3. 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
  • 4. 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.
  • 5. 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.)
  • 6. 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.
  • 7. Object Life Cycle 7  Object Creation  Object Usage  Object Disposal
  • 8. 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.
  • 9. 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
  • 10. Object Disposal 10  The Java runtime automatically deletes objects when they are no longer referenced.  This process is called garbage collection.
  • 11. 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
  • 12. 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.
  • 13. 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)
  • 14. 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
  • 15. 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).
  • 16. 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.
  • 17. 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.
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 3-21
  • 22. 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
  • 23. 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
  • 24. 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");  }  }
  • 25. 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: 
  • 26. 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
  • 27. 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.
  • 28. 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;
  • 29. 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)
  • 30. 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.
  • 31. 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:
  • 32. 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.
  • 33. 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)
  • 34. 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.
  • 35. 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
  • 36. Declaration of variables Declaring a variable instructs the computer to allocate a memory space for storing a value of that type.Example The following statement instructs the computer to declare a variable named x, for storing an integer (whole number) int x; Initialization of variables You 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 write double a=0, b=0, c=0; To initialize only b, we write float a, b=0, c; 36
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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 = -20000 int:  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
  • 41. 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 = -200000L Float:  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
  • 42. 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.4 Boolean:  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
  • 43. 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
  • 44. Types of variables  There are three kinds of variables in Java: 1. Local variables 2. Instance variables 3. Class/static variables 44
  • 45. 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 should45
  • 47. 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
  • 48.  Example will be given in class….. 48
  • 49. 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
  • 50. 50
  • 51. 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
  • 52. 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
  • 53. 53
  • 54.  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 of54
  • 55. 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
  • 56. Example Creating Object1 Classname Object1= new Classname(); Calling a method using an object Object1.Method(); 56
  • 57. 57
  • 58. Mathematics in Java To 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
  • 59. 59
  • 60. The Power of a Number 60
  • 62. 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 .java public 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.)
  • 63. 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
  • 64. 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
  • 65. 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 Imports all classes from awt, awt.event, and swing packages
  • 66. 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.
  • 67. Types of Operators.  Arithmatic Operators  Relational Operators  Logical Operators  Assignment Operators 67
  • 68. 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
  • 69. 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
  • 70. 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
  • 71. Truth Table Where T stands for Truth and F stands for False. 71
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 75
  • 76. 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
  • 77. 77
  • 78. 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
  • 79. (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
  • 80. (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)  Syntax If(condition) { Path1 (True statement) } Else { Path2 (False statement) } 80
  • 81.  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 Boolean EXAMPLE 1 Write 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
  • 82. (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  Syntax if(condition1) { True statement1; } else if (condition2); { True statement2; } . . else { True statementn; } 82
  • 83. Examples 1 Assume 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 Grade At least 70 up to 100……......………..............A At least 60 up to less than 70…………………...B At least 50 but less than 60…………….………..C Below 50……………………………………….………..F 83
  • 84. 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
  • 85. 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
  • 86. 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++.
  • 87. 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.
  • 88. 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.