Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer www.nakov.com.

Slides:



Advertisements
Similar presentations
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Advertisements

Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
Chapter 4: Control Structures II
JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Bogomil Dimitrov Technical Trainer Software.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Chapter 4: Control Structures II
JavaScript Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Chapter 5: Control Structures II
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Java Syntax Data Types, Variables, Operators, Expressions, Statements, Console I/O, Conditional Statements SoftUni Team Technical Trainers Software University.
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Technical Trainer Software University
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Bogomil Dimitrov Technical Trainer Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
C# Advanced Topics Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Object-Oriented Programming in Java How Java Implements OOP: Classes, Objects, Exceptions, Etc. SoftUni Team Technical Trainers Software University
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Processing Sequences of Elements
Objects and Classes Using Objects and Classes Defining Simple Classes SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Exception Handling, Reading and Writing in Files, Serialization,
Repeating Code Multiple Times
Functional Programming
Functional Programming and Stream API
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Presentation transcript:

Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer Software University

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:  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; 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; statements;} 6

While Loop – Example: Numbers 0…9 int counter = 0; while (counter < 10) { System.out.printf("Number : %d\n", counter); System.out.printf("Number : %d\n", counter); counter++; counter++;} 7

break 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(); int n = new Scanner(System.in).nextInt(); // Calculate n! = 1 * 2 *... * n // Calculate n! = 1 * 2 *... * n int result = 1; int result = 1; while (true) { while (true) { if (n == 1) if (n == 1) break; break; result *= n; result *= n; n--; n--; } System.out.println("n! = " + result); 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; 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); BigInteger numberBig = new BigInteger("" + number); product = product.multiply(numberBig); product = product.multiply(numberBig); number++;; number++;;} while (number <= m); System.out.printf("product[%d..%d] = %d\n", 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 + " "); System.out.print(number + " ");}  A simple for -loop to calculate n!: long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= 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 : continue Using the continue Operator int n = 100; int sum = 0; for (int i = 1; i <= n; i += 2) { if (i % 7 == 0) { if (i % 7 == 0) { continue; continue; } sum += i; 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" }; "Thursday", "Friday", "Saturday", "Sunday" }; for (String day : days) { System.out.println(day); 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 i2 = i1 + 1; i2 <= 45; i2++) for (int i3 = i2 + 1; i3 <= 46; i3++) for (int i3 = i2 + 1; i3 <= 46; i3++) for (int i4 = i3 + 1; i4 <= 47; i4++) for (int i4 = i3 + 1; i4 <= 47; i4++) for (int i5 = i4 + 1; i5 <= 48; i5++) for (int i5 = i4 + 1; i5 <= 48; i5++) for (int i6 = i5 + 1; i6 <= 49; i6++) for (int i6 = i5 + 1; i6 <= 49; i6++) System.out.printf("%d %d %d %d %d %d\n", System.out.printf("%d %d %d %d %d %d\n", i1, i2, i3, i4, i5, i6); 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++) { for (int i = 0; i < count; i++) { System.out.print("*"); System.out.print("*"); } System.out.println(); System.out.println();} public static void main(String[] args) { int n = 5; int n = 5; for (int i = 1; i <= n; i++) { for (int i = 1; i <= n; i++) { printAsterix(i); printAsterix(i); }}

20 Methods with Parameters and Return Value static double calcTriangleArea(double width, double height) { return width * height / 2; return width * height / 2;} public static void main(String[] args) { Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in); System.out.print("Enter triangle width: "); System.out.print("Enter triangle width: "); double width = input.nextDouble(); double width = input.nextDouble(); System.out.print("Enter triangle height: "); System.out.print("Enter triangle height: "); double height = input.nextDouble(); double height = input.nextDouble(); System.out.println("Area = " + calcTriangleArea(width, height)); 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; int n = 5; long factorial = calcFactorial(n); long factorial = calcFactorial(n); System.out.printf("%d! = %d", n, factorial); System.out.printf("%d! = %d", n, factorial);} private static long calcFactorial(int n) { if (n <= 1) { if (n <= 1) { return 1; return 1; } return n * calcFactorial(n-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 // Do some work that can raise an exception } catch (SomeException ex) { // Handle the caught exception // Handle the caught exception } finally { // This code will always execute // This code will always execute}

28 Handling Exceptions – Example public static void main(String[] args) { String str = new Scanner(System.in).nextLine(); String str = new Scanner(System.in).nextLine(); try { try { int i = Integer.parseInt(str); int i = Integer.parseInt(str); System.out.printf( System.out.printf( "You entered a valid integer number %d.\n", i); "You entered a valid integer number %d.\n", i); } catch (NumberFormatException nfex) { catch (NumberFormatException nfex) { System.out.println("Invalid integer number: " + 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 { OutputStream outputStream) throws IOException { byte[] buf = new byte[4096]; // 4 KB buffer size byte[] buf = new byte[4096]; // 4 KB buffer size while (true) { while (true) { int bytesRead = inputStream.read(buf); int bytesRead = inputStream.read(buf); if (bytesRead == -1) if (bytesRead == -1) break; break; outputStream.write(buf, 0, bytesRead); 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( BufferedReader fileReader = new BufferedReader( new FileReader("somefile.txt")); new FileReader("somefile.txt")); ) { while (true) { while (true) { String line = fileReader.readLine(); String line = fileReader.readLine(); if (line == null) break; if (line == null) break; System.out.println(line); System.out.println(line); } catch (IOException ioex) { System.err.println("Cannot read the file ".); 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; private int x, y; public Point(int x, int y) { public Point(int x, int y) { this.x = x; this.x = x; this.y = y; this.y = y; } public int getX() { public int getX() { return x; return x; } public void setX(int x) { public void setX(int x) { this.x = x; this.x = x; } public int getY() { … } public int getY() { … } public void setY(int y) { … } 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

? ? ? ? ? ? ? ? ? Loops, Methods, Classes

37  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with JavaCC-BY-SA  "C# Basics" course by Software University under CC-BY-NC-SA licenseC# BasicsCC-BY-NC-SA License

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg