SlideShare a Scribd company logo
Java Foundations
Basic Syntax, I/O,
Conditions, Loops
and Debugging
Your Course
Instructors
Svetlin Nakov
George Georgiev
The Judge System
Sending your Solutions
for Automated Evaluation
Testing Your Code in the Judge System
 Test your code online in the SoftUni Judge system:
https://judge.softuni.org/Contests/3294
Basic Syntax, I/O, Conditions,
Loops and Debugging
Java Introduction
Table of Contents
1. Java Introduction and Basic Syntax
2. Comparison Operators in Java
3. The if-else / switch-case Statements
4. Logical Operators: &&, ||, !, ()
5. Loops: for, while, do-while
6. Debugging and Troubleshooting
7
Java: Introduction
and Basic Syntax
Java – Introduction
 Java is modern, flexible, general-purpose
programming language
 Object-oriented by nature, statically-typed, compiled
 In this course will use Java Development Kit (JDK) 12
 Later versions will work as well
9
static void main(String[] args) {
// Source Code
}
Program
entry
point
 IntelliJ IDEA is powerful IDE for Java and other languages
 Create a project
Using IntelliJ Idea
10
Declaring Variables
 Defining and Initializing variables
 Example:
11
{data type / var} {variable name} = {value};
int number = 5;
Data type
Variable name
Variable value
Console I/O
Reading from and Writing to the Console
Reading from the Console
 We can read/write to the console,
using the Scanner class
 Import the java.util.Scanner class
 Reading input from the console using
13
import java.util.Scanner;
…
Scanner sc = new Scanner(System.in);
String name = sc.nextLine(); Returns String
Converting Input from the Console
 scanner.nextLine() returns a String
 Convert the string to number by parsing:
14
import java.util.Scanner;
…
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = Integer.parseInt(sc.nextLine());
double salary = Double.parseDouble(sc.nextLine());
 We can print to the console, using the System class
 Writing output to the console:
 System.out.print()
 System.out.println()
Printing to the Console
15
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.println("Hi, " + name);
// Name: George
// Hi, George
 Using format to print at the console
 Examples:
16
Using Print Format
Placeholder %s stands for string
and corresponds to name
Placeholder %d stands
for integer number and
corresponds to age
String name = "George";
int age = 5;
System.out.printf("Name: %s, Age: %d", name, age);
// Name: George, Age: 5
 D – format number to certain digits with leading zeros
 F – format floating point number with certain digits after the
decimal point
 Examples:
int percentage = 55;
double grade = 5.5334;
System.out.printf("%03d", percentage); // 055
System.out.printf("%.2f", grade); // 5.53
Formatting Numbers in Placeholders
17
 Using String.format to create a string by pattern
 Examples:
String name = "George";
int age = 5;
String result = String.format(
"Name: %s, Age: %d", name, age);
System.out.println(result);
// Name: George, Age 5
Using String.format(…)
18
 You will be given 3 input lines:
 Student name, age and average grade
 Print the input in the following format:
 "Name: {name}, Age: {age}, Grade {grade}"
 Format the grade to 2 decimal places
Problem: Student Information
19
John
15
5.40
Name: John, Age: 15, Grade: 5.40
import java.util.Scanner;
…
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = Integer.parseInt(sc.nextLine());
double grade = Double.parseDouble(sc.nextLine());
System.out.printf("Name: %s, Age: %d, Grade: %.2f",
name, age, grade);
Solution: Student Information
20
Comparison Operators
==, !=, <, >, <=, >=
==
Comparison Operators
22
Operator Notation in Java
Equals ==
Not Equals !=
Greater Than >
Greater Than or Equals >=
Less Than <
Less Than or Equals <=
 Values can be compared:
Comparing Numbers
2
3
int a = 5;
int b = 10;
System.out.println(a < b);
System.out.println(a > 0);
System.out.println(a > 100);
System.out.println(a < a);
System.out.println(a <= 5);
System.out.println(b == 2 * a);
// true
// true
// false
// false
// true
// true
The if-else Statement
Implementing Control-Flow Logic
 The simplest conditional statement
 Test for a condition
 Example: Take as an input a grade and check if the student
has passed the exam (grade >= 3.00)
The if Statement
25
double grade = Double.parseDouble(sc.nextLine());
if (grade >= 3.00) {
System.out.println("Passed!");
}
In Java, the opening
bracket stays on the
same line
 Executes one branch if the condition is true and another,
if it is false
 Example: Upgrade the last example, so it prints "Failed!",
if the mark is lower than 3.00:
The if-else Statement
26
The else
keyword stays
on the same
line, after the }
if (grade >= 3.00) {
System.out.println("Passed!");
} else {
// TODO: Print the message
}
 Write a program that reads hours and minutes from the console
and calculates the time after 30 minutes
 The hours and the minutes come on separate lines
 Example:
Problem: I Will be Back in 30 Minutes
27
23
59 0:29
1
46 2:16
0
01 0:31
11
32 12:02
11
08 11:38
12
49 13:19
Solution: I Will be Back in 30 Minutes (1)
28
int hours = Integer.parseInt(sc.nextLine());
int minutes = Integer.parseInt(sc.nextLine()) + 30;
if (minutes > 59) {
hours += 1;
minutes -= 60;
}
// Continue on the next slide
Solution: I Will be Back in 30 Minutes (2)
29
if (hours > 23) {
hours = 0;
}
if (minutes < 10) {
System.out.printf("%d:%02d%n", hours, minutes);
} else {
System.out.printf("%d:%d", hours, minutes);
}
%n goes on
the next line
The Switch-Case Statement
Simplified if-else-if-else
 Works as sequence of if-else statements
 Example: read input a number and print its corresponding month:
The switch-case Statement
31
int month = Integer.parseInt(sc.nextLine());
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
// TODO: Add the other cases
default: System.out.println("Error!"); break;
}
 By given country print its typical language:
 English -> England, USA
 Spanish -> Spain, Argentina, Mexico
 other -> unknown
Problem: Foreign Languages
32
England English
Spain Spanish
Solution: Foreign Languages
33
// TODO: Read the input
switch (country) {
case "USA":
case "England": System.out.println("English"); break;
case "Spain":
case "Argentina":
case "Mexico": System.out.println("Spanish"); break;
default: System.out.println("unknown"); break;
}
Logical Operators
Writing More Complex Conditions
&&
 Logical operators give us the ability to write multiple
conditions in one if statement
 They return a boolean value and compare boolean values
Logical Operators
35
Operator Notation in Java Example
Logical NOT ! !false -> true
Logical AND && true && false -> false
Logical OR || true || false -> true
 A theatre has the following ticket prices according to the age of
the visitor and the type of day. If the age is < 0 or > 122,
print "Error!":
Problem: Theatre Promotions
36
Weekday
42
18$ Error!
Day / Age 0 <= age <= 18 18 < age <= 64 64 < age <= 122
Weekday 12$ 18$ 12$
Weekend 15$ 20$ 15$
Holiday 5$ 12$ 10$
Holiday
-12
Solution: Theatre Promotions (1)
37
String day = sc.nextLine().toLowerCase();
int age = Integer.parseInt(sc.nextLine());
int price = 0;
if (day.equals("weekday")) {
if ((age >= 0 && age <= 18) || (age > 64 && age <= 122)) {
price = 12;
}
// TODO: Add else statement for the other group
}
// Continue…
Solution: Theatre Promotions (2)
38
else if (day.equals("weekend")) {
if ((age >= 0 && age <= 18) || (age > 64 && age <= 122)) {
price = 15;
} else if (age > 18 && age <= 64) {
price = 20;
}
} // Continue…
Solution: Theatre Promotions (3)
39
else if (day.equals("holiday")){
if (age >= 0 && age <= 18)
price = 5;
// TODO: Add the statements for the other cases
}
if (age < 0 || age > 122)
System.out.println("Error!");
else
System.out.println(price + "$");
Loops
Code Block Repetition
 A loop is a control statement that repeats
the execution of a block of statements.
 Types of loops:
 for loop
 Execute a code block a fixed number of times
 while and do…while
 Execute a code block while given condition is true
Loop: Definition
41
For-Loops
Managing the Count of the Iteration
 The for loop executes statements a fixed number of times:
For-Loops
43
Initial value
Loop body
for (int i = 1; i <= 10; i++) {
System.out.println("i = " + i);
}
Increment
Executed at
each iteration
The bracket is
again on the
same line
End value
 Print the numbers from 1 to 100, that are divisible by 3
 You can use "fori" live template in Intellij
Example: Divisible by 3
44
for (int i = 3; i <= 100; i += 3) {
System.out.println(i);
}
Push [Tab] twice
 Write a program to print the first n odd numbers and their sum
Problem: Sum of Odd Numbers
45
5
1
3
5
7
9
Sum: 25
3
1
3
5
Sum: 9
Solution: Sum of Odd Numbers
46
int n = Integer.parseInt(sc.nextLine());
int sum = 0;
for (int i = 1; i <= n; i++) {
System.out.println(2 * i - 1);
sum += 2 * i - 1;
}
System.out.printf("Sum: %d", sum);
While Loops
Iterations While a Condition is True
 Executes commands while the condition is true:
int n = 1;
while (n <= 10) {
System.out.println(n);
n++;
}
While Loops
48
Loop body
Condition
Initial value
Increment the counter
 Print a table holding number*1, number*2, …, number*10
Problem: Multiplication Table
49
int number = Integer.parseInt(sc.nextLine());
int times = 1;
while (times <= 10) {
System.out.printf("%d X %d = %d%n",
number, times, number * times);
times++;
}
Do…While Loop
Execute a Piece of Code One or More Times
 Like the while loop, but always executes at least once:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 10);
Do ... While Loop
51
Loop body
Condition
Initial value
Increment
the counter
 Upgrade your program and take the initial times from the console
Problem: Multiplication Table 2.0
52
int number = Integer.parseInt(sc.nextLine());
int times = Integer.parseInt(sc.nextLine());
do {
System.out.printf("%d X %d = %d%n",
number, times, number * times);
times++;
} while (times <= 10);
Debugging the Code
Using the InteliJ Debugger
 The process of debugging application includes:
 Spotting an error
 Finding the lines of code that cause the error
 Fixing the error in the code
 Testing to check if the error is gone
and no new errors are introduced
 Iterative and continuous process
Debugging the Code
5
4
 Intellij has a
built-in debugger
 It provides:
 Breakpoints
 Ability to trace the
code execution
 Ability to inspect
variables at runtime
Debugging in IntelliJ IDEA
5
5
 Start without Debugger: [Ctrl+Shift+F10]
 Toggle a breakpoint: [Ctrl+F8]
 Start with the Debugger:
[Alt+Shift+F9]
 Trace the program: [F8]
 Conditional breakpoints
Using the Debugger in IntelliJ IDEA
56
 A program aims to print the first n odd numbers and their sum
Problem: Find and Fix the Bugs in the Code
57
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
int sum = 1;
for (int i = 0; i <= n; i++) {
System.out.print(2 * i + 1);
sum += 2 * i;
}
System.out.printf("Sum: %d%n", sum);
10
 …
 …
 …
Summary
58
 Declaring variables
 Reading from / printing to the console
 Conditional statements allow implementing
programming logic
 Loops repeat code block multiple times
 Using the debugger
 …
 …
 …
Next Steps
 Join the SoftUni "Learn To Code" Community
 Access the Free Coding Lessons
 Get Help from the Mentors
 Meet the Other Learners
https://softuni.org
 …
 …
 …
Join the Learn-to-Code Community
softuni.org

More Related Content

What's hot

20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
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
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Edureka!
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Java arrays
Java    arraysJava    arrays
Java arrays
Mohammed Sikander
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 
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
 
JDBC
JDBCJDBC
JDBC
Sunil OS
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Threads V4
Threads  V4Threads  V4
Threads V4
Sunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
C Basics
C BasicsC Basics
C Basics
Sunil OS
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 

What's hot (20)

20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
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
 
JDBC
JDBCJDBC
JDBC
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Threads V4
Threads  V4Threads  V4
Threads V4
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
C Basics
C BasicsC Basics
C Basics
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Collection v3
Collection v3Collection v3
Collection v3
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Similar to Java Foundations: Basic Syntax, Conditions, Loops

00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
HongAnhNguyn285885
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
AkashdeepBhattacharj1
 
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
 
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
 
Python programing
Python programingPython programing
Python programing
hamzagame
 
AP COmputer Science Review if and else condition
AP COmputer Science Review if and else conditionAP COmputer Science Review if and else condition
AP COmputer Science Review if and else condition
ssuser8f59d0
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
kavitamittal18
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
shivanka2
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
Ashwani Kumar
 
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
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
ExcellenceAcadmy
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
ExcellenceAcadmy
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
Panimalar Engineering College
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
Mahyuddin8
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
ghoitsun
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
Karwan Mustafa Kareem
 

Similar to Java Foundations: Basic Syntax, Conditions, Loops (20)

00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
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
 
Python programing
Python programingPython programing
Python programing
 
AP COmputer Science Review if and else condition
AP COmputer Science Review if and else conditionAP COmputer Science Review if and else condition
AP COmputer Science Review if and else condition
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
 
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...
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Ch4
Ch4Ch4
Ch4
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 

More from Svetlin Nakov

Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
Svetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
Svetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
Svetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
Svetlin Nakov
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
Svetlin Nakov
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
Svetlin Nakov
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
Svetlin Nakov
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
Svetlin Nakov
 

More from Svetlin Nakov (20)

Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
 

Recently uploaded

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 

Recently uploaded (20)

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 

Java Foundations: Basic Syntax, Conditions, Loops

  • 1. Java Foundations Basic Syntax, I/O, Conditions, Loops and Debugging
  • 3. The Judge System Sending your Solutions for Automated Evaluation
  • 4. Testing Your Code in the Judge System  Test your code online in the SoftUni Judge system: https://judge.softuni.org/Contests/3294
  • 5. Basic Syntax, I/O, Conditions, Loops and Debugging Java Introduction
  • 6. Table of Contents 1. Java Introduction and Basic Syntax 2. Comparison Operators in Java 3. The if-else / switch-case Statements 4. Logical Operators: &&, ||, !, () 5. Loops: for, while, do-while 6. Debugging and Troubleshooting 7
  • 8. Java – Introduction  Java is modern, flexible, general-purpose programming language  Object-oriented by nature, statically-typed, compiled  In this course will use Java Development Kit (JDK) 12  Later versions will work as well 9 static void main(String[] args) { // Source Code } Program entry point
  • 9.  IntelliJ IDEA is powerful IDE for Java and other languages  Create a project Using IntelliJ Idea 10
  • 10. Declaring Variables  Defining and Initializing variables  Example: 11 {data type / var} {variable name} = {value}; int number = 5; Data type Variable name Variable value
  • 11. Console I/O Reading from and Writing to the Console
  • 12. Reading from the Console  We can read/write to the console, using the Scanner class  Import the java.util.Scanner class  Reading input from the console using 13 import java.util.Scanner; … Scanner sc = new Scanner(System.in); String name = sc.nextLine(); Returns String
  • 13. Converting Input from the Console  scanner.nextLine() returns a String  Convert the string to number by parsing: 14 import java.util.Scanner; … Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); double salary = Double.parseDouble(sc.nextLine());
  • 14.  We can print to the console, using the System class  Writing output to the console:  System.out.print()  System.out.println() Printing to the Console 15 System.out.print("Name: "); String name = scanner.nextLine(); System.out.println("Hi, " + name); // Name: George // Hi, George
  • 15.  Using format to print at the console  Examples: 16 Using Print Format Placeholder %s stands for string and corresponds to name Placeholder %d stands for integer number and corresponds to age String name = "George"; int age = 5; System.out.printf("Name: %s, Age: %d", name, age); // Name: George, Age: 5
  • 16.  D – format number to certain digits with leading zeros  F – format floating point number with certain digits after the decimal point  Examples: int percentage = 55; double grade = 5.5334; System.out.printf("%03d", percentage); // 055 System.out.printf("%.2f", grade); // 5.53 Formatting Numbers in Placeholders 17
  • 17.  Using String.format to create a string by pattern  Examples: String name = "George"; int age = 5; String result = String.format( "Name: %s, Age: %d", name, age); System.out.println(result); // Name: George, Age 5 Using String.format(…) 18
  • 18.  You will be given 3 input lines:  Student name, age and average grade  Print the input in the following format:  "Name: {name}, Age: {age}, Grade {grade}"  Format the grade to 2 decimal places Problem: Student Information 19 John 15 5.40 Name: John, Age: 15, Grade: 5.40
  • 19. import java.util.Scanner; … Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); double grade = Double.parseDouble(sc.nextLine()); System.out.printf("Name: %s, Age: %d, Grade: %.2f", name, age, grade); Solution: Student Information 20
  • 20. Comparison Operators ==, !=, <, >, <=, >= ==
  • 21. Comparison Operators 22 Operator Notation in Java Equals == Not Equals != Greater Than > Greater Than or Equals >= Less Than < Less Than or Equals <=
  • 22.  Values can be compared: Comparing Numbers 2 3 int a = 5; int b = 10; System.out.println(a < b); System.out.println(a > 0); System.out.println(a > 100); System.out.println(a < a); System.out.println(a <= 5); System.out.println(b == 2 * a); // true // true // false // false // true // true
  • 24.  The simplest conditional statement  Test for a condition  Example: Take as an input a grade and check if the student has passed the exam (grade >= 3.00) The if Statement 25 double grade = Double.parseDouble(sc.nextLine()); if (grade >= 3.00) { System.out.println("Passed!"); } In Java, the opening bracket stays on the same line
  • 25.  Executes one branch if the condition is true and another, if it is false  Example: Upgrade the last example, so it prints "Failed!", if the mark is lower than 3.00: The if-else Statement 26 The else keyword stays on the same line, after the } if (grade >= 3.00) { System.out.println("Passed!"); } else { // TODO: Print the message }
  • 26.  Write a program that reads hours and minutes from the console and calculates the time after 30 minutes  The hours and the minutes come on separate lines  Example: Problem: I Will be Back in 30 Minutes 27 23 59 0:29 1 46 2:16 0 01 0:31 11 32 12:02 11 08 11:38 12 49 13:19
  • 27. Solution: I Will be Back in 30 Minutes (1) 28 int hours = Integer.parseInt(sc.nextLine()); int minutes = Integer.parseInt(sc.nextLine()) + 30; if (minutes > 59) { hours += 1; minutes -= 60; } // Continue on the next slide
  • 28. Solution: I Will be Back in 30 Minutes (2) 29 if (hours > 23) { hours = 0; } if (minutes < 10) { System.out.printf("%d:%02d%n", hours, minutes); } else { System.out.printf("%d:%d", hours, minutes); } %n goes on the next line
  • 30.  Works as sequence of if-else statements  Example: read input a number and print its corresponding month: The switch-case Statement 31 int month = Integer.parseInt(sc.nextLine()); switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; // TODO: Add the other cases default: System.out.println("Error!"); break; }
  • 31.  By given country print its typical language:  English -> England, USA  Spanish -> Spain, Argentina, Mexico  other -> unknown Problem: Foreign Languages 32 England English Spain Spanish
  • 32. Solution: Foreign Languages 33 // TODO: Read the input switch (country) { case "USA": case "England": System.out.println("English"); break; case "Spain": case "Argentina": case "Mexico": System.out.println("Spanish"); break; default: System.out.println("unknown"); break; }
  • 33. Logical Operators Writing More Complex Conditions &&
  • 34.  Logical operators give us the ability to write multiple conditions in one if statement  They return a boolean value and compare boolean values Logical Operators 35 Operator Notation in Java Example Logical NOT ! !false -> true Logical AND && true && false -> false Logical OR || true || false -> true
  • 35.  A theatre has the following ticket prices according to the age of the visitor and the type of day. If the age is < 0 or > 122, print "Error!": Problem: Theatre Promotions 36 Weekday 42 18$ Error! Day / Age 0 <= age <= 18 18 < age <= 64 64 < age <= 122 Weekday 12$ 18$ 12$ Weekend 15$ 20$ 15$ Holiday 5$ 12$ 10$ Holiday -12
  • 36. Solution: Theatre Promotions (1) 37 String day = sc.nextLine().toLowerCase(); int age = Integer.parseInt(sc.nextLine()); int price = 0; if (day.equals("weekday")) { if ((age >= 0 && age <= 18) || (age > 64 && age <= 122)) { price = 12; } // TODO: Add else statement for the other group } // Continue…
  • 37. Solution: Theatre Promotions (2) 38 else if (day.equals("weekend")) { if ((age >= 0 && age <= 18) || (age > 64 && age <= 122)) { price = 15; } else if (age > 18 && age <= 64) { price = 20; } } // Continue…
  • 38. Solution: Theatre Promotions (3) 39 else if (day.equals("holiday")){ if (age >= 0 && age <= 18) price = 5; // TODO: Add the statements for the other cases } if (age < 0 || age > 122) System.out.println("Error!"); else System.out.println(price + "$");
  • 40.  A loop is a control statement that repeats the execution of a block of statements.  Types of loops:  for loop  Execute a code block a fixed number of times  while and do…while  Execute a code block while given condition is true Loop: Definition 41
  • 41. For-Loops Managing the Count of the Iteration
  • 42.  The for loop executes statements a fixed number of times: For-Loops 43 Initial value Loop body for (int i = 1; i <= 10; i++) { System.out.println("i = " + i); } Increment Executed at each iteration The bracket is again on the same line End value
  • 43.  Print the numbers from 1 to 100, that are divisible by 3  You can use "fori" live template in Intellij Example: Divisible by 3 44 for (int i = 3; i <= 100; i += 3) { System.out.println(i); } Push [Tab] twice
  • 44.  Write a program to print the first n odd numbers and their sum Problem: Sum of Odd Numbers 45 5 1 3 5 7 9 Sum: 25 3 1 3 5 Sum: 9
  • 45. Solution: Sum of Odd Numbers 46 int n = Integer.parseInt(sc.nextLine()); int sum = 0; for (int i = 1; i <= n; i++) { System.out.println(2 * i - 1); sum += 2 * i - 1; } System.out.printf("Sum: %d", sum);
  • 46. While Loops Iterations While a Condition is True
  • 47.  Executes commands while the condition is true: int n = 1; while (n <= 10) { System.out.println(n); n++; } While Loops 48 Loop body Condition Initial value Increment the counter
  • 48.  Print a table holding number*1, number*2, …, number*10 Problem: Multiplication Table 49 int number = Integer.parseInt(sc.nextLine()); int times = 1; while (times <= 10) { System.out.printf("%d X %d = %d%n", number, times, number * times); times++; }
  • 49. Do…While Loop Execute a Piece of Code One or More Times
  • 50.  Like the while loop, but always executes at least once: int i = 1; do { System.out.println(i); i++; } while (i <= 10); Do ... While Loop 51 Loop body Condition Initial value Increment the counter
  • 51.  Upgrade your program and take the initial times from the console Problem: Multiplication Table 2.0 52 int number = Integer.parseInt(sc.nextLine()); int times = Integer.parseInt(sc.nextLine()); do { System.out.printf("%d X %d = %d%n", number, times, number * times); times++; } while (times <= 10);
  • 52. Debugging the Code Using the InteliJ Debugger
  • 53.  The process of debugging application includes:  Spotting an error  Finding the lines of code that cause the error  Fixing the error in the code  Testing to check if the error is gone and no new errors are introduced  Iterative and continuous process Debugging the Code 5 4
  • 54.  Intellij has a built-in debugger  It provides:  Breakpoints  Ability to trace the code execution  Ability to inspect variables at runtime Debugging in IntelliJ IDEA 5 5
  • 55.  Start without Debugger: [Ctrl+Shift+F10]  Toggle a breakpoint: [Ctrl+F8]  Start with the Debugger: [Alt+Shift+F9]  Trace the program: [F8]  Conditional breakpoints Using the Debugger in IntelliJ IDEA 56
  • 56.  A program aims to print the first n odd numbers and their sum Problem: Find and Fix the Bugs in the Code 57 Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); int sum = 1; for (int i = 0; i <= n; i++) { System.out.print(2 * i + 1); sum += 2 * i; } System.out.printf("Sum: %d%n", sum); 10
  • 57.  …  …  … Summary 58  Declaring variables  Reading from / printing to the console  Conditional statements allow implementing programming logic  Loops repeat code block multiple times  Using the debugger
  • 58.  …  …  … Next Steps  Join the SoftUni "Learn To Code" Community  Access the Free Coding Lessons  Get Help from the Mentors  Meet the Other Learners https://softuni.org
  • 59.  …  …  … Join the Learn-to-Code Community softuni.org

Editor's Notes

  1. Hello, I am Svetlin Nakov from SoftUni (the Software University). Together with my colleague George Georgiev, we shall teach this free Java Foundations course, which covers important concepts from Java programming, such as arrays, lists, methods, strings, classes, objects and exceptions, and prepares you for the "Java Foundations" official exam from Oracle. This lesson aims to review the basic Java syntax, console-based input and output in Java, conditional statements in Java (if-else and switch-case), loops in Java (for loops, while loops and do-while loops) and code debugging in IntelliJ IDEA. Your trainer George will explain and demonstrate all these topics with live coding examples and will give you some hands-on exercises to gain practical experience with the mentioned coding concepts. Let's start!
  2. Before the start, I would like to introduce your course instructors: Svetlin Nakov and George Georgiev, who are experienced Java developers, senior software engineers and inspirational tech trainers. They have spent thousands of hours teaching programming and software technologies and are top trainers from SoftUni. I am sure you will like how they teach programming.
  3. Most of this course will be taught by George Georgiev, who is a senior software engineer with many years of experience with Java, JavaScript and C++. George enjoys teaching programming very much and is one of the top trainers at the Software University, having delivered over 300 technical training sessions on the topics of data structures and algorithms, Java essentials, Java fundamentals, C++ programming, C# development and many others. I have no doubt you will benefit greatly from his lessons, as he always does his best to explain the most challenging concepts in a simple and fun way.
  4. Before we dive into the course, I want to show you the SoftUni judge system, where you can get instant feedback for your exercise solutions. SoftUni Judge is an automated system for code evaluation. You just send your code for a certain coding problem and the system will tell you whether your solution is correct or not and what exactly is missing or wrong. I am sure you will love the judge system, once you start using it!
  5. // Solution to problem "01. Student Information". import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); double grade = Double.parseDouble(sc.nextLine()); System.out.printf("Name: %s, Age: %d, Grade: %.2f", name, age, grade); } }
  6. This first lesson aims to briefly go over the material from the Java basics course and revise the key concepts from Java coding. If you have basic experience in another programming language, this is the perfect way to pick up on Java. If not, you'd better go through the "Java Basics Full Course": https://softuni.org/code-lessons/java-basics-full-course-free-13-hours-video-plus-74-exercises We will go over Java's basic syntax, input and output from the system console, conditional statements (if-else and switch-case), loops (for, while and do-while) and debugging and troubleshooting Java code. If you are well familiar with all of these concepts and you don't need a revision, feel free to skip this section and go to the next one, where we talk about data types and type conversions in Java. If you don't have significant experience in writing Java code, please solve the hands-on exercises in the Judge system. Learning coding is only possible through coding!
  7. Did you like this lesson? Do you want more? Join the learners' community at softuni.org. Subscribe to my YouTube channel to get more free video tutorials on coding and software development. Get free access to the practical exercises and the automated judge system for this coding lesson and many others. Get free help from mentors and meet other learners. Join now! It's free. SOFTUNI.ORG
  8. Did you like this lesson? Do you want more? Join the learners' community at softuni.org. Subscribe to my YouTube channel to get more free video tutorials on coding and software development. Get free access to the practical exercises and the automated judge system for this coding lesson and many others. Get free help from mentors and meet other learners. Join now! It's free. SOFTUNI.ORG