SlideShare uma empresa Scribd logo
1 de 38
Loops, Methods, Classes
Using Loops, Defining and Using
Methods, Using API Classes,
Exceptions, Defining Classes
Svetlin Nakov
Technical Trainer
www.nakov.com
Software University
http://softuni.bg
2
1. Loops
 while, do-while, for, for-each
2. Methods
 Defining Methods
 Invoking Methods
3. Using the Java API Classes
4. Exception Handling Basics
5. Defining Simple Classes
Table of Contents
3
 The "Java Basics" course is NOT for absolute beginners
 Take the "C# Basics" course at SoftUni first:
https://softuni.bg/courses/csharp-basics
 The course is for beginners, but with previous coding skills
 Requirements
 Coding skills – entry level
 Computer English – entry level
 Logical thinking
Warning: Not for Absolute Beginners
Loops
Loop: Definition
 A loop is a control statement that repeats the execution of a
block of statements
 May execute a code block fixed number of times
 May execute a code block while given condition holds
 May execute a code block for each member of a collection
 Loops that never end are called an infinite loops
while (condition) {
statements;
}
5
While Loop
 The simplest and most frequently used loop
 The repeat condition
 Returns a boolean result of true or false
 Also called loop condition
while (condition) {
statements;
}
6
While Loop – Example: Numbers 0…9
int counter = 0;
while (counter < 10) {
System.out.printf("Number : %dn", counter);
counter++;
}
7
Using the break Operator
 The break operator exits the inner-most loop
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
// Calculate n! = 1 * 2 * ... * n
int result = 1;
while (true) {
if (n == 1)
break;
result *= n;
n--;
}
System.out.println("n! = " + result);
}
8
Do-While Loop
 Another classical loop structure is:
 The block of statements is repeated
 While the boolean loop condition holds
 The loop is executed at least once
do {
statements;
}
while (condition);
9
Product of Numbers [N..M] – Example
 Calculating the product of all numbers in the interval [n..m]:
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int number = n;
BigInteger product = BigInteger.ONE;
do {
BigInteger numberBig = new BigInteger("" + number);
product = product.multiply(numberBig);
number++;;
}
while (number <= m);
System.out.printf("product[%d..%d] = %dn", n, m, product);
10
 The classical for-loop syntax is:
 Consists of
 Initialization statement
 Boolean test expression
 Update statement
 Loop body block
For Loops
for (initialization; test; update) {
statements;
}
11
 A simple for-loop to print the numbers 0…9:
For Loop – Examples
for (int number = 0; number < 10; number++) {
System.out.print(number + " ");
}
 A simple for-loop to calculate n!:
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
12
 continue bypasses the iteration of the inner-most loop
 Example: sum all odd numbers in [1…n], not divisors of 7:
Using the continue Operator
int n = 100;
int sum = 0;
for (int i = 1; i <= n; i += 2) {
if (i % 7 == 0) {
continue;
}
sum += i;
}
System.out.println("sum = " + sum);
13
 The typical for-each loop syntax is:
 Iterates over all the elements of a collection
 The element is the loop variable that takes sequentially all
collection values
 The collection can be list, array or other group of elements of
the same type
For-Each Loop
for (Type element : collection) {
statements;
}
14
 Example of for-each loop:
 The loop iterates over the array of day names
 The variable day takes all its values
 Applicable for all collection: arrays, lists, strings, etc.
For-Each Loop – Example
String[] days = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
for (String day : days) {
System.out.println(day);
}
15
16
 Loops can be nested (one inside another)
 Example: print all combinations from TOTO 6/49 lottery
Nested Loops
for (int i1 = 1; i1 <= 44; i1++)
for (int i2 = i1 + 1; i2 <= 45; i2++)
for (int i3 = i2 + 1; i3 <= 46; i3++)
for (int i4 = i3 + 1; i4 <= 47; i4++)
for (int i5 = i4 + 1; i5 <= 48; i5++)
for (int i6 = i5 + 1; i6 <= 49; i6++)
System.out.printf("%d %d %d %d %d %dn",
i1, i2, i3, i4, i5, i6);
Loops
Live Demo
Methods
Defining and Invoking Methods
19
 Methods are named
pieces of code
 Defined in the class
body
 Can be invoked
multiple times
 Can take parameters
 Can return a value
Methods: Defining and Invoking
private static void printAsterix(int count) {
for (int i = 0; i < count; i++) {
System.out.print("*");
}
System.out.println();
}
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
printAsterix(i);
}
}
20
Methods with Parameters and Return Value
static double calcTriangleArea(double width, double height) {
return width * height / 2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter triangle width: ");
double width = input.nextDouble();
System.out.print("Enter triangle height: ");
double height = input.nextDouble();
System.out.println("Area = " + calcTriangleArea(width, height));
}
Method names in Java
should be in camelCase
21
 Recursion == method can calls itself
Recursion
public static void main(String[] args) {
int n = 5;
long factorial = calcFactorial(n);
System.out.printf("%d! = %d", n, factorial);
}
private static long calcFactorial(int n) {
if (n <= 1) {
return 1;
}
return n * calcFactorial(n-1);
}
Methods
Live Demo
Using the Java API Classes
24
 Java SE provides thousands of ready-to-use classes
 Located in packages like java.lang, java.math, java.net,
java.io, java.util, java.util.zip, etc.
 Using static Java classes:
 Using non-static Java classes
Build-in Classes in the Java API
LocalDate today = LocalDate.now();
double cosine = Math.cos(Math.PI);
Random rnd = new Random();
int randomNumber = 1 + rnd.nextInt(100);
Using the Java API Classes
Live Demo
Exception Handling Basics
Catch and Throw Exceptions
27
 In Java exceptions are handled by the try-catch-finally
construction
 catch blocks can be used multiple times to process different
exception types
Handling Exceptions
try {
// Do some work that can raise an exception
} catch (SomeException ex) {
// Handle the caught exception
} finally {
// This code will always execute
}
28
Handling Exceptions – Example
public static void main(String[] args) {
String str = new Scanner(System.in).nextLine();
try {
int i = Integer.parseInt(str);
System.out.printf(
"You entered a valid integer number %d.n", i);
}
catch (NumberFormatException nfex) {
System.out.println("Invalid integer number: " + nfex);
}
}
29
 A method in Java could declare "throws SomeException"
 This says "I don't care about SomeException", please re-throw it
The "throws …" Declaration
public static void copyStream(InputStream inputStream,
OutputStream outputStream) throws IOException {
byte[] buf = new byte[4096]; // 4 KB buffer size
while (true) {
int bytesRead = inputStream.read(buf);
if (bytesRead == -1)
break;
outputStream.write(buf, 0, bytesRead);
}
}
30
 When we use a resource that is expected to be closed, we use the
try-with-resources statement
Resource Management in Java
try(
BufferedReader fileReader = new BufferedReader(
new FileReader("somefile.txt"));
) {
while (true) {
String line = fileReader.readLine();
if (line == null) break;
System.out.println(line);
} catch (IOException ioex) {
System.err.println("Cannot read the file ".);
}
Defining Simple Classes
Using Classes to Hold a Set of Fields
32
 Classes in Java combine a set of named fields / properties
 Defining a class Point holding X and Y coordinates:
Defining Classes in Java
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() { … }
public void setY(int y) { … }
}
33
 Eclipse provides tools
for automatically
generate constructors
and getters / setters
for the class fields
Defining Classes in Eclipse
Defining Simple Classes
Live Demo
35
 Java supports the classical loop constructs
 while, do-while, for, for-each
 Similarly to C#, JavaScript, PHP, C, C++, …
 Java support methods
 Methods are named code blocks
 Can take parameters and return a result
 Java supports classical exception handling
 Through the try-catch-finally construct
 Developers can define their own classes
 With fields, methods, constructors, getters, setters, etc.
Summary
?
https://softuni.bg/courses/java-basics/
Loops, Methods, Classes
37
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from
 "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license
 "C# Basics" course by Software University under CC-BY-NC-SA license
License
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

Mais conteúdo relacionado

Mais procurados

Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro 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 complexityIntro C# Book
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories 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 handlingIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingSvetlin Nakov
 

Mais procurados (20)

Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
06.Loops
06.Loops06.Loops
06.Loops
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
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
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
09. Methods
09. Methods09. Methods
09. Methods
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 

Semelhante a 05. Java Loops Methods and Classes

Semelhante a 05. Java Loops Methods and Classes (20)

00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Thread
ThreadThread
Thread
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 

Mais de 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 traversalIntro 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 CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

Mais de Intro C# Book (12)

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.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
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
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 

Último

20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrHenryBriggs2
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirtrahman018755
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查ydyuyu
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...gajnagarg
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsMonica Sydney
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Roommeghakumariji156
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsPriya Reddy
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理F
 
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime BalliaBallia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Balliameghakumariji156
 
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsMonica Sydney
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样ayvbos
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...meghakumariji156
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...kajalverma014
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsMonica Sydney
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdfMatthew Sinclair
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdfMatthew Sinclair
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasDigicorns Technologies
 

Último (20)

20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
 
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime BalliaBallia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
 
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 

05. Java Loops Methods and Classes

  • 1. Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg
  • 2. 2 1. Loops  while, do-while, for, for-each 2. Methods  Defining Methods  Invoking Methods 3. Using the Java API Classes 4. Exception Handling Basics 5. Defining Simple Classes Table of Contents
  • 3. 3  The "Java Basics" course is NOT for absolute beginners  Take the "C# Basics" course at SoftUni first: https://softuni.bg/courses/csharp-basics  The course is for beginners, but with previous coding skills  Requirements  Coding skills – entry level  Computer English – entry level  Logical thinking Warning: Not for Absolute Beginners
  • 5. Loop: Definition  A loop is a control statement that repeats the execution of a block of statements  May execute a code block fixed number of times  May execute a code block while given condition holds  May execute a code block for each member of a collection  Loops that never end are called an infinite loops while (condition) { statements; } 5
  • 6. While Loop  The simplest and most frequently used loop  The repeat condition  Returns a boolean result of true or false  Also called loop condition while (condition) { statements; } 6
  • 7. While Loop – Example: Numbers 0…9 int counter = 0; while (counter < 10) { System.out.printf("Number : %dn", counter); counter++; } 7
  • 8. Using the break Operator  The break operator exits the inner-most loop public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); // Calculate n! = 1 * 2 * ... * n int result = 1; while (true) { if (n == 1) break; result *= n; n--; } System.out.println("n! = " + result); } 8
  • 9. Do-While Loop  Another classical loop structure is:  The block of statements is repeated  While the boolean loop condition holds  The loop is executed at least once do { statements; } while (condition); 9
  • 10. Product of Numbers [N..M] – Example  Calculating the product of all numbers in the interval [n..m]: Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); int number = n; BigInteger product = BigInteger.ONE; do { BigInteger numberBig = new BigInteger("" + number); product = product.multiply(numberBig); number++;; } while (number <= m); System.out.printf("product[%d..%d] = %dn", n, m, product); 10
  • 11.  The classical for-loop syntax is:  Consists of  Initialization statement  Boolean test expression  Update statement  Loop body block For Loops for (initialization; test; update) { statements; } 11
  • 12.  A simple for-loop to print the numbers 0…9: For Loop – Examples for (int number = 0; number < 10; number++) { System.out.print(number + " "); }  A simple for-loop to calculate n!: long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } 12
  • 13.  continue bypasses the iteration of the inner-most loop  Example: sum all odd numbers in [1…n], not divisors of 7: Using the continue Operator int n = 100; int sum = 0; for (int i = 1; i <= n; i += 2) { if (i % 7 == 0) { continue; } sum += i; } System.out.println("sum = " + sum); 13
  • 14.  The typical for-each loop syntax is:  Iterates over all the elements of a collection  The element is the loop variable that takes sequentially all collection values  The collection can be list, array or other group of elements of the same type For-Each Loop for (Type element : collection) { statements; } 14
  • 15.  Example of for-each loop:  The loop iterates over the array of day names  The variable day takes all its values  Applicable for all collection: arrays, lists, strings, etc. For-Each Loop – Example String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; for (String day : days) { System.out.println(day); } 15
  • 16. 16  Loops can be nested (one inside another)  Example: print all combinations from TOTO 6/49 lottery Nested Loops for (int i1 = 1; i1 <= 44; i1++) for (int i2 = i1 + 1; i2 <= 45; i2++) for (int i3 = i2 + 1; i3 <= 46; i3++) for (int i4 = i3 + 1; i4 <= 47; i4++) for (int i5 = i4 + 1; i5 <= 48; i5++) for (int i6 = i5 + 1; i6 <= 49; i6++) System.out.printf("%d %d %d %d %d %dn", i1, i2, i3, i4, i5, i6);
  • 19. 19  Methods are named pieces of code  Defined in the class body  Can be invoked multiple times  Can take parameters  Can return a value Methods: Defining and Invoking private static void printAsterix(int count) { for (int i = 0; i < count; i++) { System.out.print("*"); } System.out.println(); } public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) { printAsterix(i); } }
  • 20. 20 Methods with Parameters and Return Value static double calcTriangleArea(double width, double height) { return width * height / 2; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter triangle width: "); double width = input.nextDouble(); System.out.print("Enter triangle height: "); double height = input.nextDouble(); System.out.println("Area = " + calcTriangleArea(width, height)); } Method names in Java should be in camelCase
  • 21. 21  Recursion == method can calls itself Recursion public static void main(String[] args) { int n = 5; long factorial = calcFactorial(n); System.out.printf("%d! = %d", n, factorial); } private static long calcFactorial(int n) { if (n <= 1) { return 1; } return n * calcFactorial(n-1); }
  • 23. Using the Java API Classes
  • 24. 24  Java SE provides thousands of ready-to-use classes  Located in packages like java.lang, java.math, java.net, java.io, java.util, java.util.zip, etc.  Using static Java classes:  Using non-static Java classes Build-in Classes in the Java API LocalDate today = LocalDate.now(); double cosine = Math.cos(Math.PI); Random rnd = new Random(); int randomNumber = 1 + rnd.nextInt(100);
  • 25. Using the Java API Classes Live Demo
  • 26. Exception Handling Basics Catch and Throw Exceptions
  • 27. 27  In Java exceptions are handled by the try-catch-finally construction  catch blocks can be used multiple times to process different exception types Handling Exceptions try { // Do some work that can raise an exception } catch (SomeException ex) { // Handle the caught exception } finally { // This code will always execute }
  • 28. 28 Handling Exceptions – Example public static void main(String[] args) { String str = new Scanner(System.in).nextLine(); try { int i = Integer.parseInt(str); System.out.printf( "You entered a valid integer number %d.n", i); } catch (NumberFormatException nfex) { System.out.println("Invalid integer number: " + nfex); } }
  • 29. 29  A method in Java could declare "throws SomeException"  This says "I don't care about SomeException", please re-throw it The "throws …" Declaration public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buf = new byte[4096]; // 4 KB buffer size while (true) { int bytesRead = inputStream.read(buf); if (bytesRead == -1) break; outputStream.write(buf, 0, bytesRead); } }
  • 30. 30  When we use a resource that is expected to be closed, we use the try-with-resources statement Resource Management in Java try( BufferedReader fileReader = new BufferedReader( new FileReader("somefile.txt")); ) { while (true) { String line = fileReader.readLine(); if (line == null) break; System.out.println(line); } catch (IOException ioex) { System.err.println("Cannot read the file ".); }
  • 31. Defining Simple Classes Using Classes to Hold a Set of Fields
  • 32. 32  Classes in Java combine a set of named fields / properties  Defining a class Point holding X and Y coordinates: Defining Classes in Java class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { … } public void setY(int y) { … } }
  • 33. 33  Eclipse provides tools for automatically generate constructors and getters / setters for the class fields Defining Classes in Eclipse
  • 35. 35  Java supports the classical loop constructs  while, do-while, for, for-each  Similarly to C#, JavaScript, PHP, C, C++, …  Java support methods  Methods are named code blocks  Can take parameters and return a result  Java supports classical exception handling  Through the try-catch-finally construct  Developers can define their own classes  With fields, methods, constructors, getters, setters, etc. Summary
  • 37. 37  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license  "C# Basics" course by Software University under CC-BY-NC-SA license License
  • 38. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg

Notas do Editor

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