SlideShare a Scribd company logo
Java Syntax
Data Types, Variables, Operators,
Expressions, Statements, Console
I/O, Conditional Statements
Svetlin Nakov
Technical Trainer
www.nakov.com
Software University
http://softuni.bg
2
1. Primitive Data Types
2. Variables
3. Operators
4. Expressions
5. Statements
6. Console-Based Input and Output
7. Conditional Statements
 if-else, switch-case, …
Table of Contents
3
 The "Java Basics" course is NOT for absolute beginners
 Take the "C# Basics" course at SoftUni first:
https://softuni.bg/courses/csharp-basics
 The course is for beginners, but with previous coding skills
 Requirements
 Coding skills – entry level
 Computer English – entry level
 Logical thinking
Warning: Not for Absolute Beginners
Primitive Data Types in Java
5
 Computers are machines that process data
 Data is stored in the computer memory in variables
 Variables have name, data type and value
 Example of variable definition and assignment in Java
 When processed, data is stored back into variables
How Computing Works?
int count = 5;Data type
Variable name
Variable value
6
 A data type:
 Is a domain of values of similar characteristics
 Defines the type of information stored in the
computer memory (in a variable)
 Examples:
 Positive integers: 1, 2, 3, …
 Alphabetical characters: a, b, c, …
 Days of week: Monday, Tuesday, …
What Is a Data Type?
7
 A data type has:
 Name (Java keyword, e.g. int)
 Size (how much memory is used)
 Default value
 Example:
 Integer numbers in C#
 Name: int
 Size: 32 bits (4 bytes)
 Default value: 0
Data Type Characteristics
int: sequence of 32
bits in the memory
int: 4 sequential
bytes in the memory
8
 byte (-128 to 127): signed 8-bit
 short (-32,768 to 32,767): signed 16-bit
 int (-2,147,483,648 to 2,147,483,647): signed 32-bit
 long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807):
signed 64-bit
Integer Types
byte b = 1;
int i = 5;
long num = 3L;
short sum = (short) (b + i + num);
Integer Types
Live Demo
10
 Floating-point types are:
 float (±1.5 × 10−45 to ±3.4 × 1038)
 32-bits, precision of 7 digits
 double (±5.0 × 10−324 to ±1.7 × 10308)
 64-bits, precision of 15-16 digits
 The default value of floating-point types:
 Is 0.0F for the float type
 Is 0.0D for the double type
Floating-Point Types
11
Floating-Point Types – Examples
float f = 0.33f;
double d = 1.67;
double sum = f + d;
float fSum = f + d; // This will not compile
double infinity = 3.14 / 0;
System.out.println(f); // 0.33
System.out.println(d); // 1.67
System.out.println(sum); // 2.000000013113022
System.out.println(infinity); // Infinity
12
 The floating-point arithmetic sometime works incorrectly
 Don't use float and double for financial calculations!
 In Java use the BigDecimal class for financial calculations:
BigDecimal
import java.math.BigDecimal;
…
BigDecimal bigF = new BigDecimal("0.33");
BigDecimal bigD = new BigDecimal("1.67");
BigDecimal bigSum = bigF.add(bigD);
System.out.println(bigSum); // 2.00
Floating-Point and
BigDecimal Types
Live Demo
14
 Boolean
Other Primitive Data Types
boolean b = true;
System.out.println(b); // true
System.out.println(!b); // false
 Character
ch = 'ю';
System.out.println(ch);
ch = 'u03A9';  Ω
System.out.println(ch);
Enable Unicode in
the Eclipse console
Boolean and
Character Types
Live Demo
16
 The String data type:
 Declared by the String class
 Represents a sequence of characters
 Has a default value null (no value)
 Strings are enclosed in quotes:
 Strings can be concatenated
 Using the + operator
The String Data Type
String s = "Hello, Java";
17
 Concatenating the names of a person to obtain the full name:
 We can concatenate strings and numbers as well:
Saying Hello – Example
String firstName = "Ivan";
String lastName = "Ivanov";
System.out.println("Hello, " + firstName);
String fullName = firstName + " " + lastName;
System.out.println("Your full name is: " + fullName);
int age = 21;
System.out.println("Hello, I am " + age + " years old");
String Type
Live Demo
19
 The Object type:
 Is declared by the java.lang.Object class
 Is the base type of all other types
 Can hold values of any type
The Object Type
object dataContainer = 5;
System.out.print("The value of dataContainer is: ");
System.out.println(dataContainer);
dataContainer = "Five";
System.out.print("The value of dataContainer is: ");
System.out.println(dataContainer);
Objects
Live Demo
Variables, Identifiers, Literals
22
 When declaring a variable we:
 Specify its type
 Specify its name (called identifier)
 May give it an initial value
 The syntax is the following:
 Example:
Declaring Variables
<data_type> <identifier> [= <initialization>];
int height = 200;
23
 Identifiers may consist of:
 Letters (Unicode)
 Digits [0-9]
 Underscore "_"
 Examples: count, firstName, Page, брояч, 计数器
 Identifiers
 Can begin only with a letter or an underscore
 Cannot be a Java keyword (like int or class)
Identifiers
24
 Literals are the representations of values in the source code
Literals in Java
int dec = 5; // decimal value 5
int hex = 0xFE; // hexadecimal value FE -> 254
int bin = 0b11001; // binary value 11001 -> 25
int bigNum = 1_250_000; // decimal value 1250000
long num = 1234567890123456789L;
long hexNum = 0x7FFF_FFFF_FFFF_FFFFL;
boolean bool = true;
float floatNum = 1.25e+7f; // 12500000
double doubleNum = 6.02e+23; // 602000000000000000000000
char newLine = 'n'; // Character <new line>
char unicodeChar = 'u00F1'; // Character: ñ
long fourBytes = 0b11010010_01101001_10010100_10010010; // -764832622
String str = "Hello,nI'm Java.";
25
 Each primitive type in Java has a corresponding wrapper:
 int  java.lang.Integer
 double  java.lang.Double
 boolean  java.lang.Boolean
 Primitive wrappers can have a value or be null (no value)
Nullable Types: Integer, Long, Boolean, …
Integer i = 5; // Integer value: 5
i = i + 1; // Integer value: 6
i = null; // No value (null)
i = i + 1; // NullPointerException
Operators and Expressions in Java
27
 Operator is an operation performed over data at runtime
 Takes one or more arguments (operands)
 Produces a new value
 Example of operators:
 Operators have precedence
 Precedence defines which will be evaluated first
 Expressions are sequences of operators and operands that are
evaluated to a single value, e.g. (a + b) / 2
What is an Operator?
a = b + c;
Operator "+"
Operator "="
28
Category Operators
Arithmetic + - * / % ++ --
Logical && || ^ !
Binary & | ^ ~ << >> >>>
Comparison == != < > <= >=
Assignment
= += -= *= /= %= &= |= ^= <<=
>>= >>>=
String concatenation +
Other instanceof . [] () ?: new
Operators in Java
29
Precedence Operators
Highest () [] .
++ -- (postfix) new typeof
++ -- (prefix) + - (unary) ! ~
* / %
+ -
<< >> >>>
< > <= >=
== !=
&
Lower ^
Operators Precedence
30
 Parenthesis operator always has the highest precedence
 Note: prefer using parentheses to avoid ambiguity
Operators Precedence (2)
Precedence Operators
Higher |
&&
||
?:
= *= /= %= += -= <<= >>= >>>= &= ^= |=
Lowest ,
31
 Expressions are sequences of operators, literals and variables
that are evaluated to some value (formulas)
 Examples:
Expressions
int r = (150-20) / 2 + 5; // r=70
// Expression for calculating a circle area
double surface = Math.PI * r * r;
// Expression for calculating a circle perimeter
double perimeter = 2 * Math.PI * r;
32
Operators and Expressions – Examples
int x = 5, y = 2;
int div = x / y; // 2 (integral division)
float divFloat = (float)x / y; // 2.5 (floating-point division)
long num = 567_972_874; // 567972874
long mid3Digits = (num / 1000) % 1000; // 972
int z = x++; // z = x = 5; x = x + 1 = 6
boolean t = true;
boolean f = false;
boolean or = t || f;
boolean and = t && f;
boolean not = !t;
33
Operators and Expressions – Examples (2)
System.out.println(12 / 3); // 4
System.out.println(11 / 3); // 3
System.out.println(11.0 / 3); // 3.6666666666666665
System.out.println(11 / 3.0); // 3.6666666666666665
System.out.println(11 % 3); // 2
System.out.println(11 % -3); // 2
System.out.println(-11 % 3); // -2
System.out.println(1.5 / 0.0); // Infinity
System.out.println(-1.5 / 0.0); // -Infinity
System.out.println(0.0 / 0.0); // NaN
int zero = 0;
System.out.println(5 / zero); // ArithmeticException
34
Operators and Expressions – Examples (3)
short a = 3; // 00000000 00000011
short b = 5; // 00000000 00000101
System.out.println( a | b); // 00000000 00000111 --> 7
System.out.println( a & b); // 00000000 00000001 --> 1
System.out.println( a ^ b); // 00000000 00000110 --> 6
System.out.println(~a & b); // 00000000 00000100 --> 4
System.out.println( a << 1); // 00000000 00000110 --> 6
System.out.println( a >> 1); // 00000000 00000001 --> 1
System.out.println(a < b ? "smaller" : "larger");
Operators
Live Demo
36
 Type conversion and typecasting change one type to another:
Type Conversion
long lng = 5;
int intVal = (int) lng; // Explicit type conversion
float heightInMeters = 1.74f; // Explicit conversion
double maxHeight = heightInMeters; // Implicit
double minHeight = (double) heightInMeters; // Explicit
float actualHeight = (float) maxHeight; // Explicit
//float maxHeightFloat = maxHeight; // Compilation error!
// Explicit type conversion with data loss
byte dataLoss = (byte)12345; // 57
Type Conversions
Live Demo
Console Input and Output
Scanner and Formatted Printing
39
 The java.util.Scanner class reads strings and numbers
 The numbers can be separated by any sequence of whitespace
characters (e.g. spaces, tabs, new lines, …)
 Exception is thrown when non-number characters are entered
Reading from the Console
import java.util.Scanner;
…
Scanner input = new Scanner(System.in);
int firstNum = input.nextInt();
int secondNum = input.nextInt();
3
-5
Sample Inputs
3 -5
40
 A more complex example:
 Read two words from the first line
 Integer and two doubles from the second line
 A string from the third line
Reading from the Console (2)
Scanner input = new Scanner(System.in);
String firstWord = input.next("w+");
String secondWord = input.next("w+");
int numInt = input.nextInt();
double numDouble1 = input.nextDouble();
double numDouble2 = input.nextDouble();
input.nextLine(); // Skip to the line end
String str = input.nextLine();
41
 Never open more than one Scanner for the same source!
Scanner: Typical Incorrect Usage
int firstInt = readInt();
String secondLine = readLine();
private static int readInt() {
Scanner input = new Scanner(System.in);
return input.nextInt();
}
private static String readLine() {
Scanner input = new Scanner(System.in);
return input.nextLine();
}
Don't open a new Scanner, pass
existing Scanner as parameter!
Don't open a
new Scanner!
Reading from the Console
Live Demo
43
 Using System.out.print() and System.out.println():
Printing to the Console
String name = "SoftUni";
String location = "Sofia";
double age = 0.5;
System.out.print(name);
System.out.println(" is " + age +
" years old organization located in " + location + ".");
// Output:
// SoftUni is 0.5 years old organization located in Sofia.
44
Formatted Printing
 Java supports formatted printing by System.out.printf()
 %s – prints a string argument
 %f – prints a floating-point argument
 %.2f – prints a floating-point argument with 2 digits precision
String name = "SoftUni";
String location = "Sofia";
double age = 0.5;
System.out.printf(
"%s is %.2f years old organization located in %s.",
name, age, location);
45
Formatted Printing (2)
 %td / %tm / %tY – prints day / month / year from a date
 %1$f – prints the first argument as floating-point number
 %2$d – prints the second argument as integer number
System.out.printf(
"Today is %1$td.%1$tm.%1$tYn",
LocalDate.now());
// Today is 10.05.2014
System.out.printf("%1$d + %1$d = %2$dn", 2, 4);
// 2 + 2 = 4
 Learn more at http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
Printing to the Console
Live Demo
Regional Settings
Regional Settings and the Number Formatting
48
 Locales in Java define the country and language specific
formatting rules
 Reading / printing to the console is locale-dependent
 The Bulgarian locale uses "," as decimal separator, e.g. 1,25
 The United States locale uses "." as decimal separator, e.g. 1.25
 Changing the System locale (for the entire VM)
Locale
Locale.setDefault(Locale.ROOT); // Language-neutral locale
Locale.setDefault(new Locale("BG", "BG")); // Bulgarian
Locale.setDefault(Locale.US); // United States
49
Locale-Specific Input and Output
int age = 0.5;
Locale.setDefault(Locale.ROOT);
System.out.printf("%fn", age); // 0.500000
System.out.println(age); // 0.5
Scanner inputRoot = new Scanner(System.in);
double d = inputRoot.nextDouble(); // Expects 1.25
Locale.setDefault(new Locale("BG", "BG"));
System.out.printf("%fn", age); // 0,500000
System.out.println(age); // 0.5
Scanner inputBG = new Scanner(System.in);
d = inputBG.nextDouble(); // Expects 1,25
Regional Settings
Live Demo
if and if-else
Implementing Conditional Logic
52
 Java implements the classical if / if-else statements:
Conditional Statements: if-else
Scanner scanner = new Scanner(System.in);
int number = Integer.parseInt(scanner.nextLine());
if (number % 2 == 0) {
System.out.println("This number is even.");
}
else {
System.out.println("This number is odd.");
}
if and if-else
Live Demo
switch-case
Checking Multiple
Conditions
55
 Java implements the classical switch-case statements:
Conditional Statements: switch-case
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid day!"); break;
}
switch-case
Live Demo
57
 Java supports limited set of primitive
data types: byte, short, int, long,
float, double, boolean, object
 Java supports the classical operators,
expressions and statements
 Like in C#, C++, JavaScript, PHP, …
 Scanner and System.out.printf()
provide formatted input / output
 Java supports the classical if-else and switch-case
Summary
?
https://softuni.bg/courses/java-basics/
Java Syntax
59
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from
 "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license
 "C# Basics" course by Software University under CC-BY-NC-SA license
License
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

More Related Content

What's hot

10. Recursion
10. Recursion10. Recursion
10. Recursion
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
 
06.Loops
06.Loops06.Loops
06.Loops
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
Intro C# Book
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
Java Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedJava Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting Started
Svetlin Nakov
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Sreedhar Chowdam
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 

What's hot (20)

10. Recursion
10. Recursion10. Recursion
10. Recursion
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
06.Loops
06.Loops06.Loops
06.Loops
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
Java Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedJava Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting Started
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 

Similar to 03 and 04 .Operators, Expressions, working with the console and conditional statements

C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
maznabili
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
Hossein Zahed
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
gitesh_nagar
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
WondimuBantihun1
 
Python basics
Python basicsPython basics
Python basics
Manisha Gholve
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
vijayapraba1
 
02basics
02basics02basics
02basics
Waheed Warraich
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
Rasan Samarasinghe
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
RujanTimsina1
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 

Similar to 03 and 04 .Operators, Expressions, working with the console and conditional statements (20)

C tutorial
C tutorialC tutorial
C tutorial
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Python programming
Python  programmingPython  programming
Python programming
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Python basics
Python basicsPython basics
Python basics
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
 
02basics
02basics02basics
02basics
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
Intro C# Book
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
Intro C# Book
 

More from Intro C# Book (17)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 

Recently uploaded

Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
TristanJasperRamos
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
Himani415946
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
ShahulHameed54211
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 

Recently uploaded (16)

Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 

03 and 04 .Operators, Expressions, working with the console and conditional statements

  • 1. Java Syntax Data Types, Variables, Operators, Expressions, Statements, Console I/O, Conditional Statements Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg
  • 2. 2 1. Primitive Data Types 2. Variables 3. Operators 4. Expressions 5. Statements 6. Console-Based Input and Output 7. Conditional Statements  if-else, switch-case, … Table of Contents
  • 3. 3  The "Java Basics" course is NOT for absolute beginners  Take the "C# Basics" course at SoftUni first: https://softuni.bg/courses/csharp-basics  The course is for beginners, but with previous coding skills  Requirements  Coding skills – entry level  Computer English – entry level  Logical thinking Warning: Not for Absolute Beginners
  • 5. 5  Computers are machines that process data  Data is stored in the computer memory in variables  Variables have name, data type and value  Example of variable definition and assignment in Java  When processed, data is stored back into variables How Computing Works? int count = 5;Data type Variable name Variable value
  • 6. 6  A data type:  Is a domain of values of similar characteristics  Defines the type of information stored in the computer memory (in a variable)  Examples:  Positive integers: 1, 2, 3, …  Alphabetical characters: a, b, c, …  Days of week: Monday, Tuesday, … What Is a Data Type?
  • 7. 7  A data type has:  Name (Java keyword, e.g. int)  Size (how much memory is used)  Default value  Example:  Integer numbers in C#  Name: int  Size: 32 bits (4 bytes)  Default value: 0 Data Type Characteristics int: sequence of 32 bits in the memory int: 4 sequential bytes in the memory
  • 8. 8  byte (-128 to 127): signed 8-bit  short (-32,768 to 32,767): signed 16-bit  int (-2,147,483,648 to 2,147,483,647): signed 32-bit  long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807): signed 64-bit Integer Types byte b = 1; int i = 5; long num = 3L; short sum = (short) (b + i + num);
  • 10. 10  Floating-point types are:  float (±1.5 × 10−45 to ±3.4 × 1038)  32-bits, precision of 7 digits  double (±5.0 × 10−324 to ±1.7 × 10308)  64-bits, precision of 15-16 digits  The default value of floating-point types:  Is 0.0F for the float type  Is 0.0D for the double type Floating-Point Types
  • 11. 11 Floating-Point Types – Examples float f = 0.33f; double d = 1.67; double sum = f + d; float fSum = f + d; // This will not compile double infinity = 3.14 / 0; System.out.println(f); // 0.33 System.out.println(d); // 1.67 System.out.println(sum); // 2.000000013113022 System.out.println(infinity); // Infinity
  • 12. 12  The floating-point arithmetic sometime works incorrectly  Don't use float and double for financial calculations!  In Java use the BigDecimal class for financial calculations: BigDecimal import java.math.BigDecimal; … BigDecimal bigF = new BigDecimal("0.33"); BigDecimal bigD = new BigDecimal("1.67"); BigDecimal bigSum = bigF.add(bigD); System.out.println(bigSum); // 2.00
  • 14. 14  Boolean Other Primitive Data Types boolean b = true; System.out.println(b); // true System.out.println(!b); // false  Character ch = 'ю'; System.out.println(ch); ch = 'u03A9'; Ω System.out.println(ch); Enable Unicode in the Eclipse console
  • 16. 16  The String data type:  Declared by the String class  Represents a sequence of characters  Has a default value null (no value)  Strings are enclosed in quotes:  Strings can be concatenated  Using the + operator The String Data Type String s = "Hello, Java";
  • 17. 17  Concatenating the names of a person to obtain the full name:  We can concatenate strings and numbers as well: Saying Hello – Example String firstName = "Ivan"; String lastName = "Ivanov"; System.out.println("Hello, " + firstName); String fullName = firstName + " " + lastName; System.out.println("Your full name is: " + fullName); int age = 21; System.out.println("Hello, I am " + age + " years old");
  • 19. 19  The Object type:  Is declared by the java.lang.Object class  Is the base type of all other types  Can hold values of any type The Object Type object dataContainer = 5; System.out.print("The value of dataContainer is: "); System.out.println(dataContainer); dataContainer = "Five"; System.out.print("The value of dataContainer is: "); System.out.println(dataContainer);
  • 22. 22  When declaring a variable we:  Specify its type  Specify its name (called identifier)  May give it an initial value  The syntax is the following:  Example: Declaring Variables <data_type> <identifier> [= <initialization>]; int height = 200;
  • 23. 23  Identifiers may consist of:  Letters (Unicode)  Digits [0-9]  Underscore "_"  Examples: count, firstName, Page, брояч, 计数器  Identifiers  Can begin only with a letter or an underscore  Cannot be a Java keyword (like int or class) Identifiers
  • 24. 24  Literals are the representations of values in the source code Literals in Java int dec = 5; // decimal value 5 int hex = 0xFE; // hexadecimal value FE -> 254 int bin = 0b11001; // binary value 11001 -> 25 int bigNum = 1_250_000; // decimal value 1250000 long num = 1234567890123456789L; long hexNum = 0x7FFF_FFFF_FFFF_FFFFL; boolean bool = true; float floatNum = 1.25e+7f; // 12500000 double doubleNum = 6.02e+23; // 602000000000000000000000 char newLine = 'n'; // Character <new line> char unicodeChar = 'u00F1'; // Character: ñ long fourBytes = 0b11010010_01101001_10010100_10010010; // -764832622 String str = "Hello,nI'm Java.";
  • 25. 25  Each primitive type in Java has a corresponding wrapper:  int  java.lang.Integer  double  java.lang.Double  boolean  java.lang.Boolean  Primitive wrappers can have a value or be null (no value) Nullable Types: Integer, Long, Boolean, … Integer i = 5; // Integer value: 5 i = i + 1; // Integer value: 6 i = null; // No value (null) i = i + 1; // NullPointerException
  • 27. 27  Operator is an operation performed over data at runtime  Takes one or more arguments (operands)  Produces a new value  Example of operators:  Operators have precedence  Precedence defines which will be evaluated first  Expressions are sequences of operators and operands that are evaluated to a single value, e.g. (a + b) / 2 What is an Operator? a = b + c; Operator "+" Operator "="
  • 28. 28 Category Operators Arithmetic + - * / % ++ -- Logical && || ^ ! Binary & | ^ ~ << >> >>> Comparison == != < > <= >= Assignment = += -= *= /= %= &= |= ^= <<= >>= >>>= String concatenation + Other instanceof . [] () ?: new Operators in Java
  • 29. 29 Precedence Operators Highest () [] . ++ -- (postfix) new typeof ++ -- (prefix) + - (unary) ! ~ * / % + - << >> >>> < > <= >= == != & Lower ^ Operators Precedence
  • 30. 30  Parenthesis operator always has the highest precedence  Note: prefer using parentheses to avoid ambiguity Operators Precedence (2) Precedence Operators Higher | && || ?: = *= /= %= += -= <<= >>= >>>= &= ^= |= Lowest ,
  • 31. 31  Expressions are sequences of operators, literals and variables that are evaluated to some value (formulas)  Examples: Expressions int r = (150-20) / 2 + 5; // r=70 // Expression for calculating a circle area double surface = Math.PI * r * r; // Expression for calculating a circle perimeter double perimeter = 2 * Math.PI * r;
  • 32. 32 Operators and Expressions – Examples int x = 5, y = 2; int div = x / y; // 2 (integral division) float divFloat = (float)x / y; // 2.5 (floating-point division) long num = 567_972_874; // 567972874 long mid3Digits = (num / 1000) % 1000; // 972 int z = x++; // z = x = 5; x = x + 1 = 6 boolean t = true; boolean f = false; boolean or = t || f; boolean and = t && f; boolean not = !t;
  • 33. 33 Operators and Expressions – Examples (2) System.out.println(12 / 3); // 4 System.out.println(11 / 3); // 3 System.out.println(11.0 / 3); // 3.6666666666666665 System.out.println(11 / 3.0); // 3.6666666666666665 System.out.println(11 % 3); // 2 System.out.println(11 % -3); // 2 System.out.println(-11 % 3); // -2 System.out.println(1.5 / 0.0); // Infinity System.out.println(-1.5 / 0.0); // -Infinity System.out.println(0.0 / 0.0); // NaN int zero = 0; System.out.println(5 / zero); // ArithmeticException
  • 34. 34 Operators and Expressions – Examples (3) short a = 3; // 00000000 00000011 short b = 5; // 00000000 00000101 System.out.println( a | b); // 00000000 00000111 --> 7 System.out.println( a & b); // 00000000 00000001 --> 1 System.out.println( a ^ b); // 00000000 00000110 --> 6 System.out.println(~a & b); // 00000000 00000100 --> 4 System.out.println( a << 1); // 00000000 00000110 --> 6 System.out.println( a >> 1); // 00000000 00000001 --> 1 System.out.println(a < b ? "smaller" : "larger");
  • 36. 36  Type conversion and typecasting change one type to another: Type Conversion long lng = 5; int intVal = (int) lng; // Explicit type conversion float heightInMeters = 1.74f; // Explicit conversion double maxHeight = heightInMeters; // Implicit double minHeight = (double) heightInMeters; // Explicit float actualHeight = (float) maxHeight; // Explicit //float maxHeightFloat = maxHeight; // Compilation error! // Explicit type conversion with data loss byte dataLoss = (byte)12345; // 57
  • 38. Console Input and Output Scanner and Formatted Printing
  • 39. 39  The java.util.Scanner class reads strings and numbers  The numbers can be separated by any sequence of whitespace characters (e.g. spaces, tabs, new lines, …)  Exception is thrown when non-number characters are entered Reading from the Console import java.util.Scanner; … Scanner input = new Scanner(System.in); int firstNum = input.nextInt(); int secondNum = input.nextInt(); 3 -5 Sample Inputs 3 -5
  • 40. 40  A more complex example:  Read two words from the first line  Integer and two doubles from the second line  A string from the third line Reading from the Console (2) Scanner input = new Scanner(System.in); String firstWord = input.next("w+"); String secondWord = input.next("w+"); int numInt = input.nextInt(); double numDouble1 = input.nextDouble(); double numDouble2 = input.nextDouble(); input.nextLine(); // Skip to the line end String str = input.nextLine();
  • 41. 41  Never open more than one Scanner for the same source! Scanner: Typical Incorrect Usage int firstInt = readInt(); String secondLine = readLine(); private static int readInt() { Scanner input = new Scanner(System.in); return input.nextInt(); } private static String readLine() { Scanner input = new Scanner(System.in); return input.nextLine(); } Don't open a new Scanner, pass existing Scanner as parameter! Don't open a new Scanner!
  • 42. Reading from the Console Live Demo
  • 43. 43  Using System.out.print() and System.out.println(): Printing to the Console String name = "SoftUni"; String location = "Sofia"; double age = 0.5; System.out.print(name); System.out.println(" is " + age + " years old organization located in " + location + "."); // Output: // SoftUni is 0.5 years old organization located in Sofia.
  • 44. 44 Formatted Printing  Java supports formatted printing by System.out.printf()  %s – prints a string argument  %f – prints a floating-point argument  %.2f – prints a floating-point argument with 2 digits precision String name = "SoftUni"; String location = "Sofia"; double age = 0.5; System.out.printf( "%s is %.2f years old organization located in %s.", name, age, location);
  • 45. 45 Formatted Printing (2)  %td / %tm / %tY – prints day / month / year from a date  %1$f – prints the first argument as floating-point number  %2$d – prints the second argument as integer number System.out.printf( "Today is %1$td.%1$tm.%1$tYn", LocalDate.now()); // Today is 10.05.2014 System.out.printf("%1$d + %1$d = %2$dn", 2, 4); // 2 + 2 = 4  Learn more at http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
  • 46. Printing to the Console Live Demo
  • 47. Regional Settings Regional Settings and the Number Formatting
  • 48. 48  Locales in Java define the country and language specific formatting rules  Reading / printing to the console is locale-dependent  The Bulgarian locale uses "," as decimal separator, e.g. 1,25  The United States locale uses "." as decimal separator, e.g. 1.25  Changing the System locale (for the entire VM) Locale Locale.setDefault(Locale.ROOT); // Language-neutral locale Locale.setDefault(new Locale("BG", "BG")); // Bulgarian Locale.setDefault(Locale.US); // United States
  • 49. 49 Locale-Specific Input and Output int age = 0.5; Locale.setDefault(Locale.ROOT); System.out.printf("%fn", age); // 0.500000 System.out.println(age); // 0.5 Scanner inputRoot = new Scanner(System.in); double d = inputRoot.nextDouble(); // Expects 1.25 Locale.setDefault(new Locale("BG", "BG")); System.out.printf("%fn", age); // 0,500000 System.out.println(age); // 0.5 Scanner inputBG = new Scanner(System.in); d = inputBG.nextDouble(); // Expects 1,25
  • 51. if and if-else Implementing Conditional Logic
  • 52. 52  Java implements the classical if / if-else statements: Conditional Statements: if-else Scanner scanner = new Scanner(System.in); int number = Integer.parseInt(scanner.nextLine()); if (number % 2 == 0) { System.out.println("This number is even."); } else { System.out.println("This number is odd."); }
  • 55. 55  Java implements the classical switch-case statements: Conditional Statements: switch-case switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid day!"); break; }
  • 57. 57  Java supports limited set of primitive data types: byte, short, int, long, float, double, boolean, object  Java supports the classical operators, expressions and statements  Like in C#, C++, JavaScript, PHP, …  Scanner and System.out.printf() provide formatted input / output  Java supports the classical if-else and switch-case Summary
  • 59. 59  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license  "C# Basics" course by Software University under CC-BY-NC-SA license License
  • 60. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg

Editor's Notes

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