Java Introduction for Beginners
© luv2code LLC
Course Development Team
Eric Roby
Coding with Roby Chád
Darby
www.codingwithroby.com
www.luv2code.com © luv2code LLC
Course Topics
1. Java Fundamental 6. Object-Oriented Programmin
2. Conditional 7. Java Collections Framewor
s
3. Loop 8. Exception Handlin
s
4. Method 9. File Input/Outpu
s
5. Arrays 10.Lambdas and Streams
www.luv2code.com © luv2code LLC
Prerequisites
• Helpful to have previous programming experience in any language
www.luv2code.com © luv2code LLC
Source Code and PDFs
All source code is available for download
All PDFs of slides are available for download
www.luv2code.com © luv2code LLC
Questions / Help
If you have questions or need help
Post the question in the classroom discussion foru
www.luv2code.com © luv2code LLC
What is Java?
© luv2code LLC
What is Java?
General-Purpose Language Platform Independent
Enterprise API and Frameworks Large Community Support
www.luv2code.com © luv2code LLC
What Can You Build with Java?
Web Applications Mobile / Android Apps
Banking, eCommerce, Social Media, … Uber, WhatsApp, Instagram, …
Desktop UI Enterprise Apps
IntelliJ, OpenOffice, … Finance, Insurance, eCommerce, …
Embedded Systems
Automotive, network routers, Games
medical devices, … Minecraft, Runescape, …
www.luv2code.com © luv2code LLC
Java Resources
• Tutorial
s
• Documentatio
n
• News
https://dev.java
www.luv2code.com © luv2code LLC
Java Development Environment
© luv2code LLC
Java Development
• Java Integrated Development Environment (IDE
• Helps you to write, test, and run your Java cod
• Simpli es coding with syntax checking and code completio
fi
n
• IntelliJ is a popular Java IDE
www.luv2code.com © luv2code LLC
About IntelliJ Super Amazing IDE!!!
Super Amazing IDE!!!
Super Amazing IDE!!!
• In this course, we will use the free version of Intelli
• Known as IntelliJ Community Edition
• Download from: https://www.jetbrains.com/idea/download
• Select Community Edition
• You can also use the Ultimate Edition ($) ... free trial version is available
www.luv2code.com © luv2code LLC
Installing IntelliJ Super Amazing IDE!!!
Super Amazing IDE!!!
Super Amazing IDE!!!
• IntelliJ is available fo
• Microsoft Window
• Ma
c
• Linux
www.luv2code.com © luv2code LLC
Java Development Kit (JDK)
• Low-level utility to compile and execute Java program
• IntelliJ uses the JDK behind the scene
• We’ll show how to con gure the JDK for IntelliJ in upcoming videos
fi
www.luv2code.com © luv2code LLC
Development Steps
1. Install Intelli
2. Con gure Java Development Kit (JDK) in IntelliJ
fi
www.luv2code.com © luv2code LLC
Basic Java Program
© luv2code LLC
Basic Java Program
• Program Structur
• main metho d
• Displaying Tex t
• Java Keywords
www.luv2code.com © luv2code LLC
Program Structure
Name of the class A class is a blueprint
Can give custom name for data and methods
public class Demo
public static void main(String[] args)
// add your code here
}
www.luv2code.com © luv2code LLC
Program Structure Curley braces are used
to define code blocks
Must have balanced curley braces
(open/close)
public class Demo
public static void main(String[] args)
// add your code here
}
www.luv2code.com © luv2code LLC
Program Structure main is the starting entry point
of your program.
Must always have signature:
public static void main
public class Demo
public static void main(String[] args)
// add your code here
public: code can be called from any class
}
} static: methods belongs to class instead of an instance
void: does not return a value
main: special name recognized by Java as starting point
www.luv2code.com © luv2code LLC
File Name File name must have same
name as public class
File: Demo.java
In this example: Demo.java
public class Demo File extension is always .java
public static void main(String[] args)
// add your code here
Java is ALWAYS case-sensitive
}
}
Even on operating systems that are
not case-sensitive
www.luv2code.com © luv2code LLC
Displaying Text
System.out.println(" … ");
File: Demo.java
public class Demo
public static void main(String[] args)
System.out.println("Hello World!")
}
Hello World!
www.luv2code.com © luv2code LLC
Java Keywords
• A Java program can use Java keyword
• Keywords are reserved words that have a prede ned meaning
fi
www.luv2code.com © luv2code LLC
Java Keywords
Category Keywords
Access Modifiers public, protected, private
final, static, abstract, synchronized, volatile,
Class, Method and Variable Modifiers transient
int, char, byte, short, long, float, double,
Primitive Types boolean
if, else, while, do, for, break, continue,
Control Flow Statements return, switch, case, default
Exception Handling try, catch, finally, throw, throws
class, interface, extends, implement, package,
Class Definition import, record
Objects new, this, super, instanceof
void, enum, assert, native, others …
Others goto, const
goto and const are reserved … but not used
www.luv2code.com © luv2code LLC
Strings in Java
© luv2code LLC
Displaying Text
System.out.println(" … ");
File: Demo.java
public class Demo
public static void main(String[] args)
System.out.println("Hello World!")
}
Hello World!
www.luv2code.com © luv2code LLC
Assign Strings
• var is a simpli ed way of assigning a value to a variable
fi
Assign a String to a variable
var message = "Hello World!"
System.out.println(message);
Display the text
Hello World!
www.luv2code.com © luv2code LLC
Naming Conventions in Java Not a hard requirement, just a convention.
You will see this convention followed
on real-time projects.
• Variables start with a lower case letter
• For example: message, grade, account, age, city, etc
• For multiple words, use camel case: messageVolume, customerAccount, etc …
• Classes start with a capital letter
• For example: Demo, Customer, File etc
• For multiple words, use camel case: GameController, FileUploadUtil, etc …
www.luv2code.com © luv2code LLC
Concatenate / Join Strings
The + symbol is used to
concatenate / join the Strings
var message = "Hello World!"
var extra = "I love to code!"
System.out.println(message + " " + extra)
Display the text Hello World! I love to code!
www.luv2code.com © luv2code LLC
String
• Another common approach is specifying the class/type directly
class / type variable name
String message = "Hello World!"
String extra = "I love to code!";
www.luv2code.com © luv2code LLC
Concatenate / Join Strings
Assign the Strings to variables
String message = "Hello World!"
String extra = "I love to code!"
System.out.println(message + " " + extra)
Display the text Hello World! I love to code!
www.luv2code.com © luv2code LLC
The String class
• A class is a blueprint for data and methods / function
• The Java documentation lists the methods / functions that are available for the String class
Method Description
length() returns the length of the String
toUpperCase() returns an upper case version of the String
toLowerCase() returns a lower case version of the String
… …
https://docs.oracle.com/en/java/javase
www.luv2code.com © luv2code LLC
Calling methods / functions on Strings
String message = "Hello World!"
String extra = "I love to code!"
System.out.println("Length of " + message + " is " + message.length())
System.out.println("Upper case version of " + message + " is " + message.toUpperCase())
System.out.println("Lower case version of " + message + " is " + message.toLowerCase())
Length of Hello World! is 12
Upper case version of Hello World! is HELLO WORLD!
Lower case version of Hello World! is hello world!
www.luv2code.com © luv2code LLC
Reading User Input with Strings
© luv2code LLC
Earlier Example
File: Demo.java
public class Demo
public static void main(String[] args) color and hobby
is hard coded
System.out.println("My favorite color is blue")
System.out.println("My hobby is coding");
}
}
My favorite color is blue
My hobby is coding
www.luv2code.com © luv2code LLC
Refactor and add support for Variables
File: Demo.java
public class Demo
public static void main(String[] args) color and hobby
is hard coded
String theColor = "blue"
… but a little bit better
String theHobby = "coding"
System.out.println("My favorite color is " + theColor)
System.out.println("My hobby is " + theHobby)
My favorite color is blue
}
My hobby is coding
www.luv2code.com © luv2code LLC
Read User Input from the User
• Ideally, we want to prompt the user and have them type in their answer.
Typed in by the user
What is your favorite color? purpl
What is your hobby? travelin Typed in by the user
Your favorite color is purple
Your hobby is traveling
Output is no longer
hard coded
Based on input from the user
www.luv2code.com © luv2code LLC
Read User Input from the User
• Java provides a helper class to read input from the user: Scanner
Class variable
// Create a scanner for reading input from the use
Scanner scanner = new Scanner(System.in);
Create a new instance that Configure the scanner to read user input
we can use in our app typically from the keyboard
www.luv2code.com © luv2code LLC
Prompt the user and Read Input Note: we use
System.out.print(…)
to keep input cursor
on the same line
// Create a scanner for reading input from the use as the prompt
Scanner scanner = new Scanner(System.in)
// prompt the use
System.out.print("What is your favorite color? ") Prompt the user
// read the input from the use
String color = scanner.nextLine(); Read user input
What is your favorite color? <blinking cursor>
www.luv2code.com © luv2code LLC
Display the output
// Create a scanner for reading input from the use
Scanner scanner = new Scanner(System.in)
// prompt the use
System.out.print("What is your favorite color? ")
// read the input from the use
String theColor = scanner.nextLine()
System.out.println("Your favorite color is " + theColor); Display the output
What is your favorite color? <blinking cursor>
Your favorite color is <whatever user entered>
www.luv2code.com © luv2code LLC
Pulling It All Together
// Create a scanner for reading input from the use
Scanner scanner = new Scanner(System.in)
// prompt the use
r
System.out.print("What is your favorite color? ") Favorite color
// read the input from the use
String theColor = scanner.nextLine()
// prompt the use
r
System.out.print("What is your hobby? ") Hobby Output is no longer hard coded
// read the input from the use
r
String theHobby = scanner.nextLine() ;
Based on input from the user :-)
System.out.println("Your favorite color is " + theColor)
System.out.println("Your hobby is " + theHobby)
Close to release resources
// close to release resources and prevent resource/memory leak
Prevent resource/memory leaks
scanner.close();
Best practice
www.luv2code.com © luv2code LLC
Primitive Data Types
© luv2code LLC
Primitive Data Types
• A primitive data type is a basic type provided by Jav
• Not a class or objec
• Data is stored directly in memory allocated for the data typ
• Data types are de ned with a xed size and data range
fi
fi
www.luv2code.com © luv2code LLC
Primitive Data Types
Name Description
byte 8-bit, signed integer. Range -128 to 127
short 16-bit, signed integer. Range -32,768 to 32,767
int 32-bit, signed integer. Range -2^31 to 2^31 - 1
long 64-bit, signed integer. Range -2^63 to 2^63 - 1
Single-precision 32-bit IEEE 754 floating point.
float Approx ±3.40282347E+38F (6-7 significant decimal digits).
Single-precision 64-bit IEEE 754 floating point.
double Approx ±1.79769313486231570E+308 (15 significant decimal digits)
char Single 16-bit Unicode character. `\u0000` to `\uffff` Unicode is a
superset of ASCII
See unicode.org
boolean true or false No other values
are valid
www.luv2code.com © luv2code LLC
byte, short, int and long byte: 8-bit
short: 16-bit
int: 32-bit
long: 64-bit
byte data = 102 L: specify a long number
short info = 13000
int stockCount = 2147483646
long cosmicDistance = 9223372036854775807L
System.out.println("data = " + data)
System.out.println("info = " + info)
System.out.println("stockCount = " + stockCount)
System.out.println("cosmicDistance = " + cosmicDistance);
data = 10
2
info = 1300
0
stockCount = 214748364
6
cosmicDistance = 9223372036854775807
www.luv2code.com © luv2code LLC
Wrapper Classes
• For each data type, there is an associated “Wrapper Class
• Utility methods for working with primitive data types: for example, convert String to in
• Contains constant values for MIN and MAX
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
www.luv2code.com © luv2code LLC
byte, short, int and long: min and max values
byte: 8-bit
// use special wrapper classes to display min and max value short: 16-bit
int: 32-bit
System.out.println("byte: min value=" + Byte.MIN_VALUE)
long: 64-bit
System.out.println("byte: max value=" + Byte.MAX_VALUE)
System.out.println("short: min value=" + Short.MIN_VALUE)
System.out.println("short: max value=" + Short.MAX_VALUE)
System.out.println("int: min value=" + Integer.MIN_VALUE)
System.out.println("int: max value=" + Integer.MAX_VALUE)
System.out.println("long: min value=" + Long.MIN_VALUE)
System.out.println("long: max value=" + Long.MAX_VALUE); byte: min value=-12
byte: max value=12
short: min value=-3276
short: max value=3276
int: min value=-214748364
int: max value=214748364
long: min value=-922337203685477580
long: max value=922337203685477580
www.luv2code.com © luv2code LLC
Values outside of range: Compilation Errors
byte: 8-bit
short: 16-bit
// these values are outside the range of the primitive data typ int: 32-bit
// this results in a compilation error long: 64-bit
byte otherValue = 129;
short otherNum = 33000; Compilation Errors
int otherCount = 2147483700
byte: min value=-12
byte: max value=12
short: min value=-3276
short: max value=3276
int: min value=-214748364
int: max value=2147483647
www.luv2code.com © luv2code LLC
float, double float: 16-bit floating point number
double: 32-bit floating point number
f: specify floating point number
defaults to double
float interestRate = 7.95f
double prizeWinning = 9982342452.45
System.out.println("interestRate=" + interestRate)
System.out.println("prizeWinning=" + prizeWinning);
interestRate=7.9
prizeWinning=9.98234245245E9
Scientific e-notation
www.luv2code.com © luv2code LLC
Formatting Floating Point Numbers
%.2f: number should be formatted as a
(f) floating point number
with (2) digits to right of decimal point
double prizeWinning = 9982342452.45
String formattedNum = String.format("%.2f", prizeWinning)
System.out.println("Formatted prizeWinning: " + formattedNum);
Formatted prizeWinning: 9982342452.4
www.luv2code.com © luv2code LLC
char and boolean
char stage = 'Q'
boolean alive = true
boolean found = false
System.out.println("stage=" + stage)
System.out.println("alive=" + alive)
System.out.println("found=" + found );
stage=
alive=tru
found=false
www.luv2code.com © luv2code LLC
Math Operations
double gradeExam1 = 87.5
double gradeExam2 = 100.0
double gradeExam3 = 66.50
double gradeAverage = (gradeExam1 + gradeExam2 + gradeExam3) / 3
System.out.println("Grade exam 1: " + gradeExam1)
System.out.println("Grade exam 2: " + gradeExam2)
System.out.println("Grade exam 3: " + gradeExam3)
System.out.println("Grade average: " + gradeAverage)
Grade exam 1: 87.
Grade exam 2: 100.
Grade exam 3: 66.
Grade average: 84.66666666666667
www.luv2code.com © luv2code LLC
Formatting output
double gradeExam1 = 87.5
double gradeExam2 = 100.0
double gradeExam3 = 66.50
double gradeAverage = (gradeExam1 + gradeExam2 + gradeExam3) / 3
%.2f: number should be formatted as a
String formattedAvg = String.format("%.2f", gradeAverage) (f) floating point number
System.out.println("Formatted average: " + formattedAvg); with (2) digits to right of decimal point
Formatted average: 84.67
www.luv2code.com © luv2code LLC
Reading User Input with Numbers
© luv2code LLC
Earlier Example
grades are
double gradeExam1 = 87.5
hard coded
double gradeExam2 = 100.0
double gradeExam3 = 66.50
double gradeAverage = (gradeExam1 + gradeExam2 + gradeExam3) / 3
System.out.println("Grade exam 1: " + gradeExam1)
System.out.println("Grade exam 2: " + gradeExam2)
System.out.println("Grade exam 3: " + gradeExam3)
System.out.println("Grade average: " + gradeAverage)
Grade exam 1: 87.
Grade exam 2: 100.
Grade exam 3: 66.
Grade average: 84.66666666666667
www.luv2code.com © luv2code LLC
Read User Input from the User
• Ideally, we want to prompt the user and have them type in their answer.
Enter grade exam 1: 9
Enter grade exam 2: 5 Typed in by the user
Enter grade exam 3: 7
Grade exam 1: 90. 0
Output is no longer
Grade exam 2: 54. hard coded
0
Grade exam 3: 70. Based on input from the user
0
Grade average: 71.33
www.luv2code.com © luv2code LLC
Prompt the user and Read Input
// Create a scanner for reading input from the use
Scanner scanner = new Scanner(System.in)
// prompt the use
System.out.print("Enter grade exam 1: ") Prompt the user
// read the input from the user
double gradeExam1 = scanner.nextDouble(); Read user input
Enter grade exam 1: <blinking cursor>
repeat for gradesExam2 and 3
www.luv2code.com © luv2code LLC
Primitive Data Type
Casting and Conversion
© luv2code LLC
Casting and Conversion
• You may need to convert a oating point number to an intege
fl
r
• or vice-versa
• Java support
s
• Implicit Casting (Widening Conversion
• Explicit Casting (Narrowing Conversion)
www.luv2code.com © luv2code LLC
Implicit Casting (Widening Conversion)
• Converting a number of smaller (narrow) type to a larger (wider) typ
• Relates to number of bits and precisio
byte: 8-bit
• Floating point numbers are more precise than integer numbers short: 16-bit
int: 32-bit
long: 64-bit
• For example
:
• byte is smaller than short in terms of byte
• int is narrower (less precise) than floa
• for example 8 is less precise than 8.001
www.luv2code.com © luv2code LLC
Implicit Casting (Widening Conversion)
• Converting a number of smaller (narrow) type to a larger (wider) typ
• No special syntax is required since conversion is saf byte: 8-bit
short: 16-bit
int: 32-bit
• Analogy: smaller items can ALWAYS t inside larger box long: 64-bit
fi
byte data = 102
;
short info = data; // byte to shor
int stockCount = 2147483646
long bigBox = stockCount; // int to long
www.luv2code.com © luv2code LLC
Explicit Casting (Narrowing Conversion)
• Converting a larger (wider) type to a smaller (narrow) typ
• Be careful: can lead to over ow or data loss/truncatio
fl
n
• Requires special syntax
// convert double to in
double theDoubleGradeAvg = 89.70
int theIntGradeAvg = (int) theDoubleGradeAvg
System.out.println("theDoubleGradeAvg=" + theDoubleGradeAvg)
System.out.println("theIntGradeAvg=" + theIntGradeAvg);
theDoubleGradeAvg=89.
Data loss / truncation theIntGradeAvg=89
www.luv2code.com © luv2code LLC
Explicit Casting (Narrowing Conversion)
Data loss / truncation
// convert float to byt
float theFloatDistance = 123.60f
byte theByteDistance = (byte) theFloatDistance theFloatDistance=123.
theByteDistance=123
System.out.println("theFloatDistance=" + theFloatDistance)
System.out.println("theByteDistance=" + theByteDistance)
// convert int to cha
r
int theCharacterCode = 65
;
char theChar = (char) theCharacterCode
System.out.println("theCharacterCode=" + theCharacterCode)
System.out.println("theChar=" + theChar);
theCharacterCode=6
Convert character code theChar=A
to a character based on unicode
See unicode.org
www.luv2code.com © luv2code LLC