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)

20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 
JDBC
JDBCJDBC
JDBC
Sunil OS
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
Sunil OS
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
Sunil OS
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
Sunil OS
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Log4 J
Log4 JLog4 J
Log4 J
Sunil OS
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"
KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"
KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"
용근 권
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
Sunil OS
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
Sunil OS
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"
KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"
KSUG 스프링캠프 2019 발표자료 - "무엇을 테스트할 것인가, 어떻게 테스트할 것인가"
용근 권
 

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
HongAnhNguyn285885
 
java programming language part-2 decision making .pdf
java programming language part-2 decision making .pdfjava programming language part-2 decision making .pdf
java programming language part-2 decision making .pdf
AbhishekSingh961152
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
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
 
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
JAVA CLASS PPT FOR ENGINEERING STUDENTS  BBBBBBBBBBBBBBBBBBBJAVA CLASS PPT FOR ENGINEERING STUDENTS  BBBBBBBBBBBBBBBBBBB
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
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
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
kavitamittal18
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
DrPriyaChittibabu
 
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
 
Ch4
Ch4Ch4
Ch4
Uğurcan Uzer
 
java programming language part-2 decision making .pdf
java programming language part-2 decision making .pdfjava programming language part-2 decision making .pdf
java programming language part-2 decision making .pdf
AbhishekSingh961152
 
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
 
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
JAVA CLASS PPT FOR ENGINEERING STUDENTS  BBBBBBBBBBBBBBBBBBBJAVA CLASS PPT FOR ENGINEERING STUDENTS  BBBBBBBBBBBBBBBBBBB
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
shivanka2
 
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
 
Ad

More from Svetlin Nakov (20)

AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024
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
 
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024
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
 
Ad

Recently uploaded (20)

Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
Software Risk and Quality management.pptx
Software Risk and Quality management.pptxSoftware Risk and Quality management.pptx
Software Risk and Quality management.pptx
HassanBangash9
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
War Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona ToolkitWar Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona Toolkit
Sveta Smirnova
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Scalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple DevicesScalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple Devices
Scalefusion
 
Custom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdfCustom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdf
Digital Aptech
 
Top 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdfTop 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdf
LL Technolab
 
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
Nacho Cougil
 
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONAI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
miso_uam
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
UberEats clone app Development TechBuilder
UberEats clone app Development  TechBuilderUberEats clone app Development  TechBuilder
UberEats clone app Development TechBuilder
TechBuilder
 
Intranet Examples That Are Changing the Way We Work
Intranet Examples That Are Changing the Way We WorkIntranet Examples That Are Changing the Way We Work
Intranet Examples That Are Changing the Way We Work
BizPortals Solutions
 
Optimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing SystemsOptimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing Systems
Insurance Tech Services
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROIAutoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Udit Goenka
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
Software Risk and Quality management.pptx
Software Risk and Quality management.pptxSoftware Risk and Quality management.pptx
Software Risk and Quality management.pptx
HassanBangash9
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
War Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona ToolkitWar Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona Toolkit
Sveta Smirnova
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Scalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple DevicesScalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple Devices
Scalefusion
 
Custom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdfCustom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdf
Digital Aptech
 
Top 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdfTop 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdf
LL Technolab
 
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
Nacho Cougil
 
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONAI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
miso_uam
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
UberEats clone app Development TechBuilder
UberEats clone app Development  TechBuilderUberEats clone app Development  TechBuilder
UberEats clone app Development TechBuilder
TechBuilder
 
Intranet Examples That Are Changing the Way We Work
Intranet Examples That Are Changing the Way We WorkIntranet Examples That Are Changing the Way We Work
Intranet Examples That Are Changing the Way We Work
BizPortals Solutions
 
Optimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing SystemsOptimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing Systems
Insurance Tech Services
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROIAutoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Udit Goenka
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 

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

  • #2: 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!
  • #3: 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.
  • #4: 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.
  • #5: 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!
  • #6: // 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); } }
  • #7: 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!
  • #60: 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
  • #61: 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