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

OOP Chap 1 Deber Markose

The document introduces object-oriented programming concepts including objects, classes, inheritance, encapsulation, polymorphism, and abstraction. It also provides a brief history of the Java programming language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

OOP Chap 1 Deber Markose

The document introduces object-oriented programming concepts including objects, classes, inheritance, encapsulation, polymorphism, and abstraction. It also provides a brief history of the Java programming language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Debre Markos University

Burie Campus
Department of software engineering

Object Oriented programming

Lecture 1:
Introduction to Object-Oriented Programming

Ayisheshim Almaw
[email protected]

1
Chapter 1 :
INTRODUCTION to OOP
• programming paradigms
• Types of programming paradigms
• Overview of OO principles
• Characteristics/ Features of Java
• The Java language Specifications, API, JDK and IDE
• Creating , Compiling and Executing a Java program.

2
Basic Terminology

• Language: is a way of communication is known as language.


e.g. amharic, English etc.
• Program: is a set of instructions which is used to perform a
specific task.
• Programming Language :An artificial language used to
write programs which can be translated into machine
language and executed by computer with the help of some
special software.
• Platform: In programming: Hardware or software on which a
program can execute/run. e.g. – c, c++, Java etc.
 Paradigm: a philosophical or theoretical framework of any kind".
(an example showing how something is to be done)
 Paradigms as "ways of organizing thought".
 Paradigm can also be termed as method to solve some problem3 or
do some task.
what is programming paradigm

• Programming Paradigm refers to a style of programming. By style, it doesn’t


mean the choice of a specific language, but rather it refers to the way you program.
• Programming paradigms are a way to classify programming languages based on
their features.
• A programming paradigm is a way, an approach, a style by which we write programs
in a specific programming language to solve some problem.
• Programming paradigm is an approach to solve problem using some programming
language. or
• Programming paradigm is a method to solve a problem using tools and techniques
that are available to us following some approach.
• A programming paradigm is a style of programming in any programming language. It
is also used to classify programming languages on the basis of paradigms
4
Types of programming paradigms
 The programing paradigms are categorized in multiple categories yet
most significant are only two:

5
Imperative programming paradigm
• When you go shopping, you usually write down the name of the
things you need to buy before reaching the mall.
• Similarly, this paradigm consists of a list of programming statements.
• They are first executed, and then the results are stored in a variable. It
is more of a line-by-line instruction given to the computer.
• The imperative programming paradigm is the oldest paradigm and follows the
most basic idea of programming.
• The programs in these paradigms are executed step by step by changing the
current state of the program.
• This type of paradigm takes the order of the steps into consideration
because different arrangements can produce different results.
• Imperative programming mainly focuses on how a program operates.
• Examples of imperative programming are Object oriented
programming, procedural programming, etc.
6
• You may be thinking what style or approach are we talking about.
• Object oriented programming is the approach creation of objects
and creating programs.
• Functional programming: solving problems with series of
functions
• Logic programming: uses sentences in logical form and creates
an expression by using symbols.
• If a programming language support or falls under a certain
paradigm then this means it has some unique feature or it follows
a certain approach that makes it best to solve a certain kind of
problem.
• For example:
• Object-oriented programming is best suited for implementing real-
world entities by hiding important data and finding methods with
the entities. Example C++, Java, Python, etc.
• Logical programming is best for creating logic by a complex 7
• A good programming language should support multiple paradigms
because different programming problems require a different way
to approach.
• If a programing language support only one or two paradigms then
it may not be sufficient or contains feature required.

8
ASSIGNMENT 1
Q1. DEFINE and describe types of programming
paradigms
(Procedural, Object-Oriented, Functional and Logical)

9
Object-Oriented Paradigm
 Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
• OOPS is a programming approach which provides solution to real life problems
with the help of algorithms based on real world.
• It uses real world approach to solve a problem. So object oriented technique offers
better and easy way to write program then procedural programming languages
• Communication with an object is done by message passing.

• Objects are organized into classes, from which they inherit methods and
equivalent variables.
• The object-oriented paradigm provides key benefits of reusable code and code
extensibility.
10
Why an object-orientation
• Code recycle and reuse.
• Wrapping up of data into a single unit.
• Easy to partition the work in a project based on objects.
• Message passing technique between objects for communication
makes interface description with external systems much more
straightforward.
• Software Complexity can be easily handled and managed.
• Possible to map objects in a problem domain within a program.
• Data hiding is possible.
• Use of inheritance can eliminate redundant codes in a program11
Overview of OO principles

 Oop simplifies software development and


maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism Oop principles
Abstraction
Encapsulation etc.

12
object :
• Any entity that has state and behavior is known as an object.
• An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID.
• Example, a chair, pen, table, keyboard, bike, etc.
• It can be physical or logical.
• Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.

13
• A class is a group of objects that has common properties.
• class is a template or blueprint from which objects are
created.

14
 In the figure below boy ( boy ) Girl ( girl ) by class
( class ) , And the specific person is this kind of Object
( object ):

15
Inheritance
• Inheritance in java is a mechanism in which one object
acquires all the properties and behaviours of parent
object.
• It provides code reusability.

16
Encapsulation

• Encapsulation is a mechanism where you bind your data and code


together as a single unit.
• encapsulation is a way of packaging data and methods together into
one unit
• Data encapsulation is basically used for achieving
data/information hiding i.e., security.
• Example: a medicine capsule having different components packed
as a single unit. In Java

17
Abstraction
• Abstraction refers to hiding the details and showing the essential
things to the user.
• If you look at the image below, whenever we get a call, we get an
option to either pick it up or just reject it. But in reality, there is a
lot of code that runs in the background.
• So you don’t know the internal processing of how a call is
generated, that’s the beauty of abstraction.

18
Polymorphism

• Polymorphism means taking many forms, where ‘poly’ means


many and ‘morph’ means forms.
• It is the ability of a variable, function or object to take on multiple
forms. In other words,
• Polymorphism means more than one forms.
• Eg. Water can be of in any form solid, liquid or gas.
• Inheritance lets us inherit attributes and methods from another
class.
• Polymorphism uses those methods to perform different tasks. This
allows us to perform a single action in different ways.

19
History of Java

 James Gosling, Mike Sheridan, and Patrick


Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in
electronic appliances like set-top boxes.
 Firstly, it was called "Greentalk" by James Gosling and file
extension was .gt.
 After that, it was called Oak and was developed as a part of
the Green project.

20
Q. Why Oak name for java language?
• Why Oak? Oak is a symbol of strength and choosen as a national
tree of many countries like U.S.A., France, Germany, Romania
etc.
• In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.
Q. Why they choosed java name for java language?
 The team gathered to choose a new name. The suggested words
were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc.
 They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy
to spell and fun to say.
 According to James Gosling "Java was one of the top choices along
with Silk". Since java was so unique, most of the team members
preferred java.
21
• Java is an island of Indonesia where first coffee was produced
(called java coffee).
• Notice that Java is just a name not an acronym
• Java is an object-oriented programming language developed by Sun
Microsystems, and it was released in 1995.
• James Gosling initially developed Java in Sun
Microsystems (which was later merged with Oracle Corporation)
What is java?
• Java is a general purpose, concurrent, class based, object
oriented programming language.
• Java as an object-oriented language was designed from the
outset to be platform independent, robust, and secure.
• Platform: Any hardware or software environment in which a
program runs, is known as a platform. Since Java has its own
runtime environment (JRE) and API, it is called platform. 22
Characteristics/ Features of Java
• Object-Oriented - Java supports the features of object-oriented
programming. Its object model is simple and easy to expand.
• Platform independent - Java works on different platforms
(Windows, Mac, Linux, Raspberry Pi, etc.)
• Simple - Java has included many features of C / C ++, which makes
it easy to understand.
• Secure - Java provides a wide range of protection from viruses and
malicious programs.
• Portable - Java provides us with the concept of portability. Running
the same program with Java on different platforms is possible.
• Robust - During the development of the program, it helps us to find
possible mistakes as soon as possible.
• Multi-threaded - The multithreading programming feature in Java
allows you to write a program that performs several different tasks
simultaneously 23
Where java is used?

• According to Sun, 3 billion devices run java. There are many devices where java is
currently used.
• Types of Java Applications
• There are mainly 4 type of applications that can be created using java programming:
1. Standalone Application (desktop application or window-based application): An
application that we need to install on every machine such as media player, antivirus etc.
Example: such as acrobat reader, media player, antivirus etc.
2) Web Application
• An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc.
• Example: javatpoint.com,dmu.edu.et etc
3) Enterprise Application
• An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
• Example: banking applications
4) Mobile Application: An application that is created for mobile devices. Currently Android
and Java ME are used for creating mobile applications.
• Example: Smart Card, Robotics, Games etc. 24
The Java language Specifications, API, JDK
and IDE
• Java language Specifications: a technical specifications of the language
that includes the syntax and semantics of the language.
• API (Application Program Interface): Contains predefined classes and
interfaces for developing java programs.
Three editions of java API
– J2SE: Java 2 Standard Edition
– J2EE: Java 2 Enterprise Edition
– J2ME: Java 2 Micro Edition
Three major java development tools
– Jbulider
– NetBeans
– Eclipse

25
Java JVM, JDK and JRE

• Java virtual Machine(JVM) is a virtual Machine that provides


runtime environment to execute java byte code.
• JVM (Java Virtual Machine) is an abstract machine.
• JVMs are available for many hardware and software platforms.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime
environment

26
Java Runtime Environment (JRE)
• JRE : provides the libraries, the Java Virtual Machine, and
other components to run applets and applications written in
the Java programming language.
• JRE does not contain tools and utilities such as compilers or
debuggers for developing applets and applications.

27
JDK (Java Development Kit)
• JDK Includes a complete JRE (Java Runtime Environment) plus
tools for developing, debugging, and monitoring Java applications.
• JDK is required to build and run Java applications and applets.

28
Creating , Compiling and Executing a Java
program. Create/Modify source code

Source Code

A bytecode file with Compile Source Code


Welcome.class e.g javac welcom.java

Bytecode

Run Bytecode
e.g.java Welcome

Result

29
Phases of a Java Program
 Java programs normally go through five phases-
edit, compile, load, verify and execute.

30
Phases of a Java Program

31
Phase 1: Creating a program
• Involves editing a file with an editor
• The following are some Java Integrated Development
Environments (IDEs).
– Jbuilder, NetBeans , Sun ONE Studio, Eclipse, jEdit,
Jcreator, BlueJ, jGRASP, etc.
– Most of this editors can be downloaded for free.

– Any text editor can also be used for creating Java programs.

– Programs written on IDEs or any other editors are known as


Source Code.

32
– Java source code file names end with .java extension
Phase 2: Compiling Java Programs into Bytecodes
• Since a computer cannot understand a source program, program
called a compiler is used to translate the source program into a
machine language program called an object program.
• With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
• The bytecode can then run on any computer (platform) with a Java
Virtual Machine
• A virtual machine is a software application that simulates a
computer-JVM is one of the most widely used virtual machine
• Java Virtual Machine, which is part of JRE, is a software that
interprets Java bytecode. Java Bytecode

• To compile Java Program Java Virtual


Machine
 Javac welcome.java Any
Computer
• To execute java programs
 Java welcome
33
Continued…
Runs on Windows PC
Running JVM

Code Compile Result

Java Program Java Compiler Java Byte code UNIX


(*.java) javac (*.class) Running JVM

Macintosh
Running JVM

34
Phase 3: Loading a program
• A program must be placed in memory before it can execute
: a process known as loading.

• The class loader takes the .class file (produced during


compilation process) containing the program’s bytecodes
and transform them to primary memory.

• The class loader also loads any of the .class files provided
by java that your program uses.

• The .class files can be loaded from a disk on your system


or over a network. 35
Phase 4 : Bytecode Verification
• Involves examining bytecodes to ensure that they are valid and do not
violate Java’s security restriction.
• Java enforces strong security, to make sure that Java programs arriving over
the network do not damage your files or your system (as computer viruses
and worms might).
Phase 5: Execution
• The JVM executes the program’s bytecodes, thus performing the
actions specified by the program.
• .class file is not final machine code yet. It is virtual machine
code. JVM need a second compilation to convert virtual
machine code to real machine code. We call it just-in-time
compiler (JIT).
• This greatly affects the speed of the execution.
• Traditionally, our C/C++ program can finish all the compilation
before execution. The generated machine code could 36run
A Simple Application
Example 1:
//This application program prints Welcome to Java!
message on the console window.
public class Welcome
{
public static void main(String[] args)
{
System.out.println("Welcome to Java!");
}
} 37
• Java System.out.println() is used to print an
argument that is passed to it.
• System is the class name, it is declared as final.
• It is a final class defined in the java.lang package.
• The out is an instance of the System class and is
of type PrintStream.
• println(): is a method of PrintStream class.

38
Remarks
• Every java program must have at least one class

• A class is a construct that defines data and methods

• Everything must be in class

• By convention, class name start with an uppercase letter

• In order to run a class, the class must contain a method named main

Commands on a command prompt to Compile and Execute


 javac Welcome.java // compile
 java Welcome // run or execute
 output:...

39
Anatomy of a Java Program
• A java program contains:
– Comments
– Reserved words
– Package
– Modifiers
– Statements
– Blocks
– Classes
– Methods
– The main method

40
Comments
• Preceded by two slashes (//) in a line, or enclosed between /* and */ in one or
multiple lines.
Reserved Words
• Reserved words or keywords are words that have a specific meaning to the compiler
and cannot be used for other purposes in the program.
Example,
class, public, static, and void.
• Packages: A group of predefined classes
Example
• JOptionPane is in javax.swing package i.e it is imported to a program using import
statement.
• java. lang package is imported implicitly in every java program, eg. System class is not
imported b/c it is in this package
Modifiers
• Reserved words that specify the properties of the data, methods, and classes and how they
can be used.
• Ex. public and static, private, final, abstract, and protected.

41
Statements
• Represents an action or a sequence of actions.
• Eg.: System.out.println("Welcome to Java!") is a statement to display the greeting "Welcome to Java!"
• Should end with a semicolon (;).

Block
• A pair of braces in a program forms a block that groups components of a program.

Classes : is a group of objects that has common properties. It is a template or blueprint


from which objects are created.
• Methods: A collection of statements that performs a sequence of operations.
• Main Method
• The main method provides the control of program flow.
• The Java interpreter executes the application by invoking the main method.
• The main method looks like this:
public static void main(String[] args) {
// Statements;
42
}
Java Class Library
• These libraries of classes provide support for I/O, the graphic user
interface, string manipulation, math and so on.
• The basic java library that accompanies your java development
software is stored in a file called class.zip.
• Inside class.zip is a hierarchy of packages, each of which contains a
group of related java classes.

• There are four basic packages inside class.zip.


– java.lang: contains support for arithmetic manipulation, numeric data types,
and arrays.
– java.io: contains support for I/O.
– java.util: contains a variety of utility routines, including a random number
generator and a date class.
– java.awt: contains classes for a GUI as well as some simple drawing
routines.
• The class.zip file also contains java.net, which provides support 43for
Data Types, Variables and Keywords
References and Primitive Data Types

• The data type of a value (or variable in some contexts) is an attribute


that tells what kind of data that value can have
In java there are two categories of data types:
– Primitive (Basic/Simple) types: consists of int, float, char and
Boolean.
– Reference types: consists of interfaces, classes, and arrays.

44
Character and String Data Type
Character data type:
– Used to represent a single character
– A character literal is enclosed in single quotation
marks.
Eg. char letter=‘A’;
String Data type
– Represent a string of character
– A predefined class in java library
– It is known as reference type
Eg. Sting message =“Welcome to Java”
45
Variables
• variable is a name which is used to store a value of any type during
program execution.
• A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location.
• It is a combination of "vary + able" which means its value can be
changed. A variable is assigned with a data type.
• An identifier is a name that uniquely identifies a variable, a method
(function), a class or any other element in java that requires a name.
• The following are considered valid in identifiers names:
– Upper case and lower case letters a through z. E.g. int x, string
name…
– Underscore character (_). E.g. string Stud_name…
– The dollar sign ($). E.g. char val$...
– Except for the first character, the digits 0-9. E.g. int x1, x2,.. int 1x,
2x (Wrong)
– Identifiers are case sensitive. E.g. String Name is not the same as
String name 46
Declaration of variable in Java
• Declaring a variable means what kind of data it will
store.
• Variables display named storage locations, whose
values can be changed during the execution of the
program.
• The syntax for declaring a variable is
datatype variableName;
Eg:
int count;
double radius;
double interestRate;
47
Initialization of Variables in Java
• This means assigning a value to variables.
The syntax for initializing a variable is
datatype variableName= value
• // actual initialization
 width = 10;
 age = 26;

48
Constants Variables
• Represents permanent data that never changes.

• Syntax for declaring a constant:

final data_type CONSTANTNAME = VALUE;

• The word final is a Java keyword for declaring a constant.


Eg. final double PI = 3.14159;
• Java Programming language defines mainly three kind of variables.
1. Instance Variables
2. Static Variables (Class Variables)
3. Local Variables
1. Instance variables in Java
• Instance variables are variables that are declare inside a class but outside any
method,constructor or block.
class Student
{
// Here name and age are instance variable of Student class.
String name;
int age; 49
2. Static variables in Java
• Static variables are class variables declared with
static keyword.
class Student {
String name;
int age;
static int instituteCode=1101; }
3. Local variables in Java
• Local variables are declared in method, constructor or block .
float getDiscount(int price) {
class A {
float discount;
int amount = 100; //instance variable
discount=price*(20/100);
static int pin = 2315; //static variable
return discount;
public static void main(String[] args) {
}
int age = 35; //local variable
}} 50
Array Basics
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• Used to store a collection of data,
• A collection of variables of the same type.
Declaring Array Variables
• Syntax
dataType[] arrayName;
• For example, declares a variable myList that references an
array of double data type elements.

double[] myList;
51
Initialize an Array in Java
• By using new operator array can be initialized.
• Example:
int[] age = new int[5]; //5 is the size of array.
Arrays can be initialized at declaration time also.
• Example:
int age[5]={22,25,30,32,35};

String[] cars;
 We have now declared a variable that holds an array of strings.
 To insert values to it, we can use an array literal - place the values in
a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
 To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40}; 52
Access the Elements of an Array
• You access an array element by referring to the index
number.
• This statement accesses the value of the first element in
cars:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]); // Outputs Volvo
Change an Array Element
• To change the value of a specific element, refer to the
index number:
• ArrayName[index No]=“value”;
cars[0] = "Opel";

53
54
Two-Dimensional Array Basics
• Used to represent a matrix or a table

• syntax for declaring a two-dimensional array:


dataType[][] arrayNamr;
or
dataType arrayName[][]; // Allowed, but not preferred
• As an example, here is how you would declare a two-dimensional
array variable matrix of int values:

int[][] matrix;

55
int jimmy [3][5];
jimmy[1][3] means

56
Control Structures
• Control structures are a way to alter the natural sequence of execution
in a Java program.
• They act as “direction signals” to control the path a program takes.
• The process of performing one statement after another is called the flow
of execution or flow of control.
• Control structures include:
» Block statements
» Decision statements
» Loops

57
Decision Statements
• The control statements that allow alternative actions based up on
conditions that are evaluated at run time are generally called
decision or selection statements.
• These include if and switch statements.
If Statements
• A simple if statement executes an action if and only if the condition
is true.
• The syntax:

if (boolean-expression)
{
statement(s);
} 58
public class Sample{

public static void main(String


args[]){
int a=20, b=30;

if(b>a)
System.out.println("b is
greater");
}
}

59
If … Else Statement
• To take alternative actions when the condition is false, you can use a n
if… else statement.
• The actions that a if…else statement specifies differ based on whether
the condition is true or false.
• The syntax:

if (boolean-expression)
{
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
} 60
public class Sample {

public static void main(String args[]) {


int a = 80, b = 30;

if (b > a) {
System.out.println("b is greater");
} else {
System.out.println("a is greater");
} }}

61
Nested if Statements
• The nested if statement can be used to implement multiple
alternatives.

Eg. if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F'; 62
Switch Statements
• Java provides it to handle multiple conditions efficiently,
replace the nested if statement.
• The syntax:
switch (switch-expression)
{
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
} 63
public class Sample {
public static void main(String args[]) { case 4:
System.out.println("You chose Four");
int a = 5; break;
switch (a) {
case 5:
case 1:
System.out.println("You chose Five");
System.out.println("You chose One"); break;
break;
default:
case 2: System.out.println("Invalid Choice.
System.out.println("You chose Two"); Enter a no between 1 and 5");
break;
break;
} }}
case 3:
System.out.println("You chose
Three");
break;

64
Decision Statements
• Sometimes it is necessary for the program to execute the statement several times, and
Java loops execute a block of commands a specified number of times until a condition is
met.
• A computer is the most suitable machine to perform repetitive tasks and can tirelessly do
a task tens of thousands of times.
• These sequences are easily processed by iteration statement blocks. Such
programming statements are called loops, because the flow of execution “loops
back” to the beginning of the block.
The while Loop
 Java while loops statement allows to repeatedly run the same block of code
until a condition is met
• The syntax:
while (condition)
{
// Loop body
Statement(s);
65
}
public class Sample {

public static void main(String args[]) {


int n = 1, times = 5;

while (n <= times) {


System.out.println("Java while loops:" + n);
n++;
} }}

66
The do-while Loop
• Java do-while loops are very similar to the while loops, but it
always executes the code block at least once and furthermore as
long as the condition remains true.
• Syntax :

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
• Executes the loop body first, then checks the loop-
continuation-condition to determine whether to continue or
terminate the loop. 67
public class Sample {

public static void main(String args[])


{
int n = 1, times = 0;

do {
System.out.println("Java do
while loops:" + n);
n++;
} while (n <= times);
}}

68
The for Loop
• Java for loops is very similar to Java while loops in that it
continues to process a block of code until a statement becomes
false, and everything is defined in a single line.
• A for loop can be used to simplify the proceeding loop:

for (i = initialValue; i < endValue; i++)


{
// Loop body
...
}
69
public class Sample {

public static void main(String


args[]) {
int n = 1, times = 5;

for (n = 1; n <= times; n = n + 1) {


System.out.println("Java for
loops:" + n);
}}}

70
Method in Java
• A method is a collection of statements that are grouped together to
perform an operation.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also
known as functions.
• Why use methods?
o To reuse code:
o define the code once, and
o use it many times.
• For example, if we have a class Human, then this class should
have methods like eating(), walking(), talking() etc, which
describes the behavior of the object.
71
Declaring a Method
• A method must be declared within a class.
• It is defined with the name of the method, followed by
parentheses ().
• Java provides some pre-defined methods, such
as System.out.println(), but
• you can also create your own methods to perform certain actions:
syntax to declare the method in Java
return-type methodName(parameter-list)
{
//body of method
}

72
• Return Type : A method may return value. Data type of value return by
a method is declare in method heading.
• Method name : Actual name of the method.
• Parameter : Value passed to a method.
• Method body : collection of statement that defines what method does.
Calling a Method
• Methods are called to perform the functionality implemented in it.
• We can call method by its name and store the returned value into a
variable.
• write the method's name followed by two parentheses () and a semicolon;
Syntax methodName ();

73
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}}

74
Parameters and Arguments
• Parameter is variable defined by a method that receives value
when the method is called.
• Parameter are always local to the method they don’t have scope
outside the method. While
• argument is a value that is passed to a method when it is called.
• You can add as many parameters as you want, just separate them
with a comma.

75
 When a parameter is passed to the method, it is called
an argument.
So, from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.

public class Main {


static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}} 76
• End of Ch.1
Questions, Ambiguities, Doubts, … ???

You might also like