SlideShare una empresa de Scribd logo
1 de 59
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

Más contenido relacionado

La actualidad más candente

20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Svetlin Nakov
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
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 Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handoutsjhe04
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 

La actualidad más candente (20)

20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
Threads V4
Threads  V4Threads  V4
Threads V4
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Java naming conventions
Java naming conventionsJava naming conventions
Java naming conventions
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
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
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
enums
enumsenums
enums
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 

Similar a 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 abstractionIntro 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 IAbdul Rahman Sherzad
 
Python programing
Python programingPython programing
Python programinghamzagame
 
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 conditionssuser8f59d0
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptxshivanka2
 
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
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptMahyuddin8
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptghoitsun
 

Similar a 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
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
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
 

Más de 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 2024Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and StartupsSvetlin 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 EntrepreneursSvetlin 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 2023Svetlin 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 LifeSvetlin 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 FutureSvetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023Svetlin 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 DeveloperSvetlin 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 FutureSvetlin 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 JobSvetlin 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
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Svetlin Nakov
 

Más de Svetlin Nakov (20)

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)
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
 

Último

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 

Último (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

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

Notas del editor

  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