SlideShare a Scribd company logo
Defining and Using Methods, Overloads
Methods
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Table of Contents
1. What Is a Method?
2. Naming and Best Practices
3. Declaring and Invoking Methods
 Void and Return Type Methods
4. Methods with Parameters
5. Value vs. Reference Types
6. Overloading Methods
7. Program Execution Flow 2
sli.do
#fund-java
Have a Question?
3
What Is a Method
Void Method
Simple Methods
 Named block of code, that can be invoked later
 Sample method definition:
 Invoking (calling) the
method several times:
5
public static void printHello () {
System.out.println("Hello!");
}
Method named
printHello
printHello();
printHello();
Method body
always
surrounded
by { }
 More manageable programming
 Splits large problems into small pieces
 Better organization of the program
 Improves code readability
 Improves code understandability
 Avoiding repeating code
 Improves code maintainability
 Code reusability
 Using existing methods several times
Why Use Methods?
6
 Executes the code between the brackets
 Does not return result
Void Type Method
7
public static void printHello() {
System.out.println("Hello");
}
public static void main(String[] args) {
System.out.println("Hello");
}
main() is
also a
method
Prints
"Hello" on
the console
Naming and Best Practices
 Methods naming guidelines
 Use meaningful method names
 Method names should answer the question:
 What does this method do?
 If you cannot find a good name for a method, think
about whether it has a clear intent
Naming Methods
9
findStudent, loadReport, sine
Method1, DoSomething, HandleStuff, SampleMethod
Naming Method Parameters
 Method parameters names
 Preferred form: [Noun] or [Adjective] + [Noun]
 Should be in camelCase
 Should be meaningful
 Unit of measure should be obvious
10
firstName, report, speedKmH,
usersList, fontSizeInPixels, font
p, p1, p2, populate, LastName, last_name, convertImage
 Each method should perform a single, well-defined task
 A Method's name should describe that task in a clear and
non-ambiguous way
 Avoid methods longer than one screen
 Split them to several shorter methods
Methods – Best Practices
11
private static void printReceipt() {
printHeader();
printBody();
printFooter();
}
Self documenting
and easy to test
 Make sure to use correct indentation
 Leave a blank line between methods, after loops and after
if statements
 Always use curly brackets for loops and if statements bodies
 Avoid long lines and complex expressions
Code Structure and Code Formatting
12
static void main(args) {
// some code…
// some more code…
}
static void main(args)
{
// some code…
// some more code…
}
Declaring and Invoking Methods
{…}
 Methods are declared inside a class
 main() is also a method
 Variables inside a method are local
public static void printText(String text) {
System.out.println(text);
}
Declaring Methods
14
Method NameType Parameters
Method
Body
 Methods are first declared, then invoked (many times)
 Methods can be invoked (called) by their name + ():
Invoking a Method
15
public static void printHeader() {
System.out.println("----------");
}
public static void main(String[] args) {
printHeader();
}
Method
Declaration
Method
Invocation
 A method can be invoked from:
 The main method – main()
Invoking a Method (2)
public static void main(String[] args) {
printHeader();
}
public static void printHeader() {
printHeaderTop();
printHeaderBottom();
}
static void crash() {
crash();
}
 Some other method Its own body – recursion
Methods with Parameters
double
String
long
 Method parameters can be of any data type
 Call the method with certain values (arguments)
Method Parameters
18
public static void main(String[] args) {
printNumbers(5, 10);
}
static void printNumbers(int start, int end) {
for (int i = start; i <= end; i++) {
System.out.printf("%d ", i);
}
}
Passing arguments
at invocation
Multiple parameters
separated by comma
 You can pass zero or several parameters
 You can pass parameters of different types
 Each parameter has name and type
public static void printStudent(String name, int age, double grade) {
System.out.printf("Student: %s; Age: %d, Grade: %.2fn",
name, age, grade);
}
Method Parameters (2)
19
Parameter
type
Parameter
name
Multiple parameters
of different types
 Create a method that prints the sign of an integer number n:
Problem: Sign of Integer Number
20
2 The number 2 is positive.
-5
The number 0 is zero.
Check your solution here: https://judge.softuni.bg/Contests/1260
0
The number -5 is negative.
Solution: Sign of Integer Number
21
public static void main(String[] args) {
printSign(Integer.parseInt(sc.nextLine()));
}
public static void printSign(int number) {
if (number > 0)
System.out.printf("The number %d is positive.", number);
else if (number < 0)
System.out.printf("The number %d is negative.", number);
else
System.out.printf("The number %d is zero.", number);
}
Check your solution here: https://judge.softuni.bg/Contests/1260
 Write a method that receives a grade between 2.00 and 6.00
and prints the corresponding grade in words
 2.00 - 2.99 - "Fail"
 3.00 - 3.49 - "Poor"
 3.50 - 4.49 - "Good"
 4.50 - 5.49 - "Very good"
 5.50 - 6.00 - "Excellent"
Problem Grades
22
3.33 Poor
4.50 Very good
2.99 Fail
Check your solution here: https://judge.softuni.bg/Contests/1260
public static void main(String[] args) {
printInWords(Double.parseDouble(sc.nextLine()));
}
public static void printInWords(double grade) {
String gradeInWords = "";
if (grade >= 2 && grade <= 2.99)
gradeInWords = "Fail";
//TODO: make the rest
System.out.println(gradeInWords);
}
Solution Grades
23
 Create a method for printing triangles as shown below:
Problem: Printing Triangle
24
1
1 2
1 2 3
1 2
1
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1
3 4
Check your solution here: https://judge.softuni.bg/Contests/1260
 Create a method that prints a single line, consisting of numbers
from a given start to a given end:
Solution: Printing Triangle (1)
25
public static void printLine(int start, int end) {
for (int i = start; i <= end; i++) {
System.out.print(i + " ");
}
System.out.println();
}
Check your solution here: https://judge.softuni.bg/Contests/1260
 Create a method that prints the first half (1..n) and then the
second half (n-1…1) of the triangle:
Solution: Printing Triangle (2)
26
public static void printTriangle(int n) {
for (int line = 1; line <= n; line++)
printLine(1, line);
for (int line = n - 1; line >= 1; line--)
printLine(1, line);
}
Method with
parameter n
Check your solution here: https://judge.softuni.bg/Contests/1260
Lines 1...n
Lines n-1…1
Live Exercises
Returning Values From Methods
The Return Statement
 The return keyword immediately stops
the method's execution
 Returns the specified value
 Void methods can be terminated by just using return
29
public static String readFullName(Scanner sc) {
String firstName = sc.nextLine();
String lastName = sc.nextLine();
return firstName + " " + lastName;
} Returns a String
Using the Return Values
 Return value can be:
 Assigned to a variable
 Used in expression
 Passed to another method
30
int max = getMax(5, 10);
double total = getPrice() * quantity * 1.20;
int age = Integer.parseInt(sc.nextLine());
 Create a method which returns rectangle area
with given width and height
Problem: Calculate Rectangle Area
31Check your solution here: https://judge.softuni.bg/Contests/1260
3
4
12
5
10
50
6
8
48
7
8
56
Solution: Calculate Rectangle Area
32
public static double calcRectangleArea(double width,
double height) {
return width * height;
}
public static void main(String[] args) {
double width = Double.parseDouble(sc.nextLine());
double height = Double.parseDouble(sc.nextLine());
double area = calcRectangleArea(width, height);
System.out.printf("%.0f%n",area);
}
Check your solution here: https://judge.softuni.bg/Contests/1260
 Write a method that receives a string and a repeat count n
 The method should return a new string
Problem: Repeat String
33
abc
3
abcabcabc
String
2
StringString
Check your solution here: https://judge.softuni.bg/Contests/1260
public static void main(String[] args) {
String inputStr = sc.nextLine();
int count = Integer.parseInt(sc.nextLine());
System.out.println(repeatString(inputStr, count));
}
private static String repeatString(String str, int count) {
String result = "";
for (int i = 0; i < count; i++) result += str;
return result;
}
Solution: Repeat String
34
 Create a method that calculates and returns the value of a
number raised to a given power
Problem: Math Power
35
public static double mathPower(double number, int power) {
double result = 1;
for (int i = 0; i < power; i++)
result *= number;
return result;
}
5.5325628
Check your solution here: https://judge.softuni.bg/Contests/1260
166.375
Live Exercises
Value vs. Reference Types
Memory Stack and Heap
Value vs. Reference Types
38
 Value type variables hold directly their value
 int, float, double,
boolean, char, …
 Each variable has its
own copy of the value
Value Types
39
int i = 42;
char ch = 'A';
boolean result = true;
Stack
42
A
true
(4 bytes)
(2 bytes)
(1 byte)
result
ch
i
 Reference type variables hold а reference
(pointer / memory address) of the value itself
 String, int[], char[], String[]
 Two reference type variables can reference the
same object
 Operations on both variables access / modify
the same data
Reference Types
40
Value Types vs. Reference Types
41
int i = 42;
char ch = 'A';
boolean result = true;
Object obj = 42;
String str = "Hello";
byte[] bytes ={ 1, 2, 3 };
HEAPSTACK
true (1 byte)
result
A (2 bytes)
ch
42 (4 bytes)
i
int32@9ae764
obj
42 4 bytes
String@7cdaf2
str
Hello String
byte[]@190d11
bytes
1 2 3 byte []
Example: Value Types
42
public static void main(String[] args) {
int num = 5;
increment(num, 15);
System.out.println(num);
}
public static void increment(int num, int value) {
num += value;
}
num == 5
num == 20
Example: Reference Types
43
public static void main(String[] args) {
int[] nums = { 5 };
increment(nums, 15);
System.out.println(nums[0]);
}
public static void increment(int[] nums, int value) {
nums[0] += value;
}
nums[0] == 20
nums[0] == 20
Live Exercises
Overloading Methods
 The combination of method's name and parameters
is called signature
 Signature differentiates between methods with same names
 When methods with the same name have different signature,
this is called method "overloading"
public static void print(String text) {
System.out.println(text);
}
Method Signature
46
Method's
signature
 Using the same name for multiple methods with different
signatures (method name and parameters)
Overloading Methods
47
Different
method
signatures
static void print(int number) {
System.out.println(number);
}
static void print(String text) {
System.out.println(text);
}
static void print(String text, int number) {
System.out.println(text + ' ' + number);
}
 Method's return type is not part of its signature
 How would the compiler know which method to call?
Signature and Return Type
48
public static void print(String text) {
System.out.println(text);
}
public static String print(String text) {
return text;
}
Compile-time
error!
 Create a method getMax() that returns the greater of two
values (the values can be of type int, char or String)
Problem: Greater of Two Values
49
z
char
a
z
16
int
2
16
bbb
String
aaa
bbb
Check your solution here: https://judge.softuni.bg/Contests/1260
Live Exercises
Program Execution Flow
0 0 1 0 0
0 1 0 1 0
1 0 0 1 0 1 0
0 1 0 0 0 1 0
1 0 0 1 0 0 1
public static void printLogo() {
System.out.println("Company Logo");
System.out.println("http://www.companywebsite.com");
}
public static void main(String[] args) {
System.out.println("before method executes");
printLogo();
System.out.println("after method executes");
}
 The program continues, after a method execution completes:
Program Execution
Main
 "The stack" stores information about the active subroutines
(methods) of a computer program
 Keeps track of the point to which each active subroutine should
return control when it finishes executing
Program Execution – Call Stack
Method BMethod AMain
Call Stack
call
START Method A Method B
call
returnreturn
 Create a program that multiplies the sum of all even digits of a
number by the sum of all odd digits of the same number:
 Create a method called getMultipleOfEvensAndOdds()
 Create a method getSumOfEvenDigits()
 Create getSumOfOddDigits()
 You may need to use Math.abs() for negative numbers
Problem: Multiply Evens by Odds
Evens: 2 4
Odds: 1 3 5
-12345
Even sum: 6
Odd sum: 9
54
Check your solution here: https://judge.softuni.bg/Contests/1260
Live Exercises
 …
 …
 …
Summary
56
 Break large programs into simple
methods that solve small sub-problems
 Methods consist of declaration and body
 Methods are invoked by their name + ()
 Methods can accept parameters
 Methods can return a value
or nothing (void)
 https://softuni.bg/courses/programming-fundamentals
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
61

More Related Content

What's hot

OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
Sunil OS
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Java strings
Java   stringsJava   strings
Java strings
Mohammed Sikander
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
 
C# Events
C# EventsC# Events
C# Events
Prem Kumar Badri
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
SameerAhmed593310
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
C# Basics
C# BasicsC# Basics
C# Basics
Sunil OS
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
Vishnu Suresh
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 

What's hot (20)

OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java strings
Java   stringsJava   strings
Java strings
 
Collection v3
Collection v3Collection v3
Collection v3
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
C# Events
C# EventsC# Events
C# Events
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java Basics
Java BasicsJava Basics
Java Basics
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 

Similar to 09. Java Methods

Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
BG Java EE Course
 
09. Methods
09. Methods09. Methods
09. Methods
Intro C# Book
 
09 Methods
09 Methods09 Methods
09 Methods
maznabili
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
HUST
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
OXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART IOXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART I
Abdul Rahman Sherzad
 
Parameters
ParametersParameters
Parameters
James Brotsos
 
Relational Operators in C
Relational Operators in CRelational Operators in C
Relational Operators in C
Lakshmi Sarvani Videla
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
Md Showrov Ahmed
 
Xamarin: C# Methods
Xamarin: C# MethodsXamarin: C# Methods
Xamarin: C# Methods
Eng Teong Cheah
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
mayorothenguyenhob69
 
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
RohitNukte
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Kavitha713564
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
Srinivasa Babji Josyula
 
Csphtp1 03
Csphtp1 03Csphtp1 03
Csphtp1 03
HUST
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
Vani Kandhasamy
 
Chapter 2.4
Chapter 2.4Chapter 2.4
Chapter 2.4sotlsoc
 

Similar to 09. Java Methods (20)

Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
09. Methods
09. Methods09. Methods
09. Methods
 
09 Methods
09 Methods09 Methods
09 Methods
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
OXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART IOXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART I
 
Parameters
ParametersParameters
Parameters
 
Relational Operators in C
Relational Operators in CRelational Operators in C
Relational Operators in C
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
Xamarin: C# Methods
Xamarin: C# MethodsXamarin: C# Methods
Xamarin: C# Methods
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
Csphtp1 03
Csphtp1 03Csphtp1 03
Csphtp1 03
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
 
Chapter 2.4
Chapter 2.4Chapter 2.4
Chapter 2.4
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 

Recently uploaded

急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
VivekSinghShekhawat2
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 

Recently uploaded (20)

急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 

09. Java Methods

  • 1. Defining and Using Methods, Overloads Methods Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. Table of Contents 1. What Is a Method? 2. Naming and Best Practices 3. Declaring and Invoking Methods  Void and Return Type Methods 4. Methods with Parameters 5. Value vs. Reference Types 6. Overloading Methods 7. Program Execution Flow 2
  • 4. What Is a Method Void Method
  • 5. Simple Methods  Named block of code, that can be invoked later  Sample method definition:  Invoking (calling) the method several times: 5 public static void printHello () { System.out.println("Hello!"); } Method named printHello printHello(); printHello(); Method body always surrounded by { }
  • 6.  More manageable programming  Splits large problems into small pieces  Better organization of the program  Improves code readability  Improves code understandability  Avoiding repeating code  Improves code maintainability  Code reusability  Using existing methods several times Why Use Methods? 6
  • 7.  Executes the code between the brackets  Does not return result Void Type Method 7 public static void printHello() { System.out.println("Hello"); } public static void main(String[] args) { System.out.println("Hello"); } main() is also a method Prints "Hello" on the console
  • 8. Naming and Best Practices
  • 9.  Methods naming guidelines  Use meaningful method names  Method names should answer the question:  What does this method do?  If you cannot find a good name for a method, think about whether it has a clear intent Naming Methods 9 findStudent, loadReport, sine Method1, DoSomething, HandleStuff, SampleMethod
  • 10. Naming Method Parameters  Method parameters names  Preferred form: [Noun] or [Adjective] + [Noun]  Should be in camelCase  Should be meaningful  Unit of measure should be obvious 10 firstName, report, speedKmH, usersList, fontSizeInPixels, font p, p1, p2, populate, LastName, last_name, convertImage
  • 11.  Each method should perform a single, well-defined task  A Method's name should describe that task in a clear and non-ambiguous way  Avoid methods longer than one screen  Split them to several shorter methods Methods – Best Practices 11 private static void printReceipt() { printHeader(); printBody(); printFooter(); } Self documenting and easy to test
  • 12.  Make sure to use correct indentation  Leave a blank line between methods, after loops and after if statements  Always use curly brackets for loops and if statements bodies  Avoid long lines and complex expressions Code Structure and Code Formatting 12 static void main(args) { // some code… // some more code… } static void main(args) { // some code… // some more code… }
  • 13. Declaring and Invoking Methods {…}
  • 14.  Methods are declared inside a class  main() is also a method  Variables inside a method are local public static void printText(String text) { System.out.println(text); } Declaring Methods 14 Method NameType Parameters Method Body
  • 15.  Methods are first declared, then invoked (many times)  Methods can be invoked (called) by their name + (): Invoking a Method 15 public static void printHeader() { System.out.println("----------"); } public static void main(String[] args) { printHeader(); } Method Declaration Method Invocation
  • 16.  A method can be invoked from:  The main method – main() Invoking a Method (2) public static void main(String[] args) { printHeader(); } public static void printHeader() { printHeaderTop(); printHeaderBottom(); } static void crash() { crash(); }  Some other method Its own body – recursion
  • 18.  Method parameters can be of any data type  Call the method with certain values (arguments) Method Parameters 18 public static void main(String[] args) { printNumbers(5, 10); } static void printNumbers(int start, int end) { for (int i = start; i <= end; i++) { System.out.printf("%d ", i); } } Passing arguments at invocation Multiple parameters separated by comma
  • 19.  You can pass zero or several parameters  You can pass parameters of different types  Each parameter has name and type public static void printStudent(String name, int age, double grade) { System.out.printf("Student: %s; Age: %d, Grade: %.2fn", name, age, grade); } Method Parameters (2) 19 Parameter type Parameter name Multiple parameters of different types
  • 20.  Create a method that prints the sign of an integer number n: Problem: Sign of Integer Number 20 2 The number 2 is positive. -5 The number 0 is zero. Check your solution here: https://judge.softuni.bg/Contests/1260 0 The number -5 is negative.
  • 21. Solution: Sign of Integer Number 21 public static void main(String[] args) { printSign(Integer.parseInt(sc.nextLine())); } public static void printSign(int number) { if (number > 0) System.out.printf("The number %d is positive.", number); else if (number < 0) System.out.printf("The number %d is negative.", number); else System.out.printf("The number %d is zero.", number); } Check your solution here: https://judge.softuni.bg/Contests/1260
  • 22.  Write a method that receives a grade between 2.00 and 6.00 and prints the corresponding grade in words  2.00 - 2.99 - "Fail"  3.00 - 3.49 - "Poor"  3.50 - 4.49 - "Good"  4.50 - 5.49 - "Very good"  5.50 - 6.00 - "Excellent" Problem Grades 22 3.33 Poor 4.50 Very good 2.99 Fail Check your solution here: https://judge.softuni.bg/Contests/1260
  • 23. public static void main(String[] args) { printInWords(Double.parseDouble(sc.nextLine())); } public static void printInWords(double grade) { String gradeInWords = ""; if (grade >= 2 && grade <= 2.99) gradeInWords = "Fail"; //TODO: make the rest System.out.println(gradeInWords); } Solution Grades 23
  • 24.  Create a method for printing triangles as shown below: Problem: Printing Triangle 24 1 1 2 1 2 3 1 2 1 1 1 2 1 2 3 1 2 3 4 1 2 3 1 2 1 3 4 Check your solution here: https://judge.softuni.bg/Contests/1260
  • 25.  Create a method that prints a single line, consisting of numbers from a given start to a given end: Solution: Printing Triangle (1) 25 public static void printLine(int start, int end) { for (int i = start; i <= end; i++) { System.out.print(i + " "); } System.out.println(); } Check your solution here: https://judge.softuni.bg/Contests/1260
  • 26.  Create a method that prints the first half (1..n) and then the second half (n-1…1) of the triangle: Solution: Printing Triangle (2) 26 public static void printTriangle(int n) { for (int line = 1; line <= n; line++) printLine(1, line); for (int line = n - 1; line >= 1; line--) printLine(1, line); } Method with parameter n Check your solution here: https://judge.softuni.bg/Contests/1260 Lines 1...n Lines n-1…1
  • 29. The Return Statement  The return keyword immediately stops the method's execution  Returns the specified value  Void methods can be terminated by just using return 29 public static String readFullName(Scanner sc) { String firstName = sc.nextLine(); String lastName = sc.nextLine(); return firstName + " " + lastName; } Returns a String
  • 30. Using the Return Values  Return value can be:  Assigned to a variable  Used in expression  Passed to another method 30 int max = getMax(5, 10); double total = getPrice() * quantity * 1.20; int age = Integer.parseInt(sc.nextLine());
  • 31.  Create a method which returns rectangle area with given width and height Problem: Calculate Rectangle Area 31Check your solution here: https://judge.softuni.bg/Contests/1260 3 4 12 5 10 50 6 8 48 7 8 56
  • 32. Solution: Calculate Rectangle Area 32 public static double calcRectangleArea(double width, double height) { return width * height; } public static void main(String[] args) { double width = Double.parseDouble(sc.nextLine()); double height = Double.parseDouble(sc.nextLine()); double area = calcRectangleArea(width, height); System.out.printf("%.0f%n",area); } Check your solution here: https://judge.softuni.bg/Contests/1260
  • 33.  Write a method that receives a string and a repeat count n  The method should return a new string Problem: Repeat String 33 abc 3 abcabcabc String 2 StringString Check your solution here: https://judge.softuni.bg/Contests/1260
  • 34. public static void main(String[] args) { String inputStr = sc.nextLine(); int count = Integer.parseInt(sc.nextLine()); System.out.println(repeatString(inputStr, count)); } private static String repeatString(String str, int count) { String result = ""; for (int i = 0; i < count; i++) result += str; return result; } Solution: Repeat String 34
  • 35.  Create a method that calculates and returns the value of a number raised to a given power Problem: Math Power 35 public static double mathPower(double number, int power) { double result = 1; for (int i = 0; i < power; i++) result *= number; return result; } 5.5325628 Check your solution here: https://judge.softuni.bg/Contests/1260 166.375
  • 37. Value vs. Reference Types Memory Stack and Heap
  • 39.  Value type variables hold directly their value  int, float, double, boolean, char, …  Each variable has its own copy of the value Value Types 39 int i = 42; char ch = 'A'; boolean result = true; Stack 42 A true (4 bytes) (2 bytes) (1 byte) result ch i
  • 40.  Reference type variables hold а reference (pointer / memory address) of the value itself  String, int[], char[], String[]  Two reference type variables can reference the same object  Operations on both variables access / modify the same data Reference Types 40
  • 41. Value Types vs. Reference Types 41 int i = 42; char ch = 'A'; boolean result = true; Object obj = 42; String str = "Hello"; byte[] bytes ={ 1, 2, 3 }; HEAPSTACK true (1 byte) result A (2 bytes) ch 42 (4 bytes) i int32@9ae764 obj 42 4 bytes String@7cdaf2 str Hello String byte[]@190d11 bytes 1 2 3 byte []
  • 42. Example: Value Types 42 public static void main(String[] args) { int num = 5; increment(num, 15); System.out.println(num); } public static void increment(int num, int value) { num += value; } num == 5 num == 20
  • 43. Example: Reference Types 43 public static void main(String[] args) { int[] nums = { 5 }; increment(nums, 15); System.out.println(nums[0]); } public static void increment(int[] nums, int value) { nums[0] += value; } nums[0] == 20 nums[0] == 20
  • 46.  The combination of method's name and parameters is called signature  Signature differentiates between methods with same names  When methods with the same name have different signature, this is called method "overloading" public static void print(String text) { System.out.println(text); } Method Signature 46 Method's signature
  • 47.  Using the same name for multiple methods with different signatures (method name and parameters) Overloading Methods 47 Different method signatures static void print(int number) { System.out.println(number); } static void print(String text) { System.out.println(text); } static void print(String text, int number) { System.out.println(text + ' ' + number); }
  • 48.  Method's return type is not part of its signature  How would the compiler know which method to call? Signature and Return Type 48 public static void print(String text) { System.out.println(text); } public static String print(String text) { return text; } Compile-time error!
  • 49.  Create a method getMax() that returns the greater of two values (the values can be of type int, char or String) Problem: Greater of Two Values 49 z char a z 16 int 2 16 bbb String aaa bbb Check your solution here: https://judge.softuni.bg/Contests/1260
  • 51. Program Execution Flow 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 1 0 0 1
  • 52. public static void printLogo() { System.out.println("Company Logo"); System.out.println("http://www.companywebsite.com"); } public static void main(String[] args) { System.out.println("before method executes"); printLogo(); System.out.println("after method executes"); }  The program continues, after a method execution completes: Program Execution
  • 53. Main  "The stack" stores information about the active subroutines (methods) of a computer program  Keeps track of the point to which each active subroutine should return control when it finishes executing Program Execution – Call Stack Method BMethod AMain Call Stack call START Method A Method B call returnreturn
  • 54.  Create a program that multiplies the sum of all even digits of a number by the sum of all odd digits of the same number:  Create a method called getMultipleOfEvensAndOdds()  Create a method getSumOfEvenDigits()  Create getSumOfOddDigits()  You may need to use Math.abs() for negative numbers Problem: Multiply Evens by Odds Evens: 2 4 Odds: 1 3 5 -12345 Even sum: 6 Odd sum: 9 54 Check your solution here: https://judge.softuni.bg/Contests/1260
  • 56.  …  …  … Summary 56  Break large programs into simple methods that solve small sub-problems  Methods consist of declaration and body  Methods are invoked by their name + ()  Methods can accept parameters  Methods can return a value or nothing (void)
  • 60.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 61.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 61

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. Add Image!
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*