Java Grammar
Module 1: Java Fundamentals
Variables: store data
Conditionals: control how your code runs
Arrays: store and work with many values
Loops: control how many times a piece of code needs to run
Functions: perform tasks
Module 2: Object Oriented Programming
objects、immutable objects、list collections、map collections、exception handling、
package and import、static and final、enums、unit test、inheritance and polymorphism、
higher order functions、big decimal、interface、concurrency and multithreading
Reasons to learn Java
Java is general-purpose, which means that Java powers a wide range of applications.
As a Java developer,
- you can build web applications using Spring boot,
- you can build applications on Android,
- you can automate tasks using Selenium,
- you can develop cloud native applications,
- you can integrate microservices,
- you can …
Java can run on any machine, it’s well known for its “write once, run anywhere”
- This is because the Java Virtual Machine, the JVM, which is responsible for executing compiled Java code, can be installed on any platform
Java is the No.1 language for developing enterprise applications
To run Java code, you need
A Java Compiler - to compile your code.
A Java Runtime - to run the compiled code.
So, this is why JDK provides a Compiler、a Runtime、and a lot of other things.
Roadmap
Install a JDK(Java Development Kit) on your machine => from Amazon Corretto is recomended.
Amazon Corretto is just a distribution which once installed, does the work of setting up a JDK on your machine.
Basically all you need to do is install it and it’s going to do the heavy lifting.1
2javac -version # check compiler
java -version # check runtimeFinished ! you’ve just installed a JDK, now your computer can compile and run Java code.
Download a text editor to write code
I use vim & vscode(the extension pack for java is must).
Now you have everything you need to start building Java applications!
Write & Run your first Java code
1
2Every java file needs to follow the naming convention -> CamelCase
touch HelloJava.java1
2
3
4
5// In java, you must write all of your code in a class.
// And the ClassName needs to be the same as your FileName.
// So here we create a class.
class HelloJava {
}All right, so what’s next is the
main()
method, which is the entry point of a Java application.And inside main, we’re going to print the message “Hello Java”
1
2
3
4
5
6
7
8
9
10
11
12class HelloJava {
// not understand this line is doesn't matter now.
public static void main(String[] args) {
System.out.println("Hello Java");
}
}
/* Notice:
the semicolon is really important, which means end of statement.
every statement in Java, every line of code, needs a semicolon at the end.
so if you forget your semicolon, your code is not gonna run.
*/Now we’re ready to compile and run our Java code.
1
2
3
4
5The javac command compiles your javaCode into byteCode
javac <FileName>.java
The java command executes the compiled code
java <FileName>For example
See you in workbook 1.1
Variable
Store data inside variable.
Java is strongly typed
which means that variables can only store values of their type.
Java is case sensitive
eg: people
is not the same as People
The convention to naming a variable
lowerCamelCase
eg: int peopleOnBus = 20;
Update the value inside a variable
Just set it equal to a new value, or use +=
、-=
、…
See you in workbook 2.1
Use variables to store numeric data
Types: int and long
We can use int
and long
variables to store whole numbers.
You should know the difference between int
and long
and when to use int
vs long
.
1 | int numberOfFans = 5000; |
为什么要在 7000000000 这个数后面加个 L ?
如果你不加 L,那么 Java 就只会看到这是一个很大的数,它并不知道你这个傻乎乎的开发者要将这个数存到什么地方,所以 Java 就慌了
因此,你只需在这个数后面加个 L 来告诉 Java:“放松啦~ 咱们要存的地方存得下这个数的。”,然后 Java 就平静了
Type: double
We can use double
variables to store decimal numbers, which are given so much size in memory that a double value can reach 15 significant digits.
1 | double percentage = 55.7; |
Be careful !!!
Avoid just using integers for math calculations,
because if you multiply or divide two integers, the result will always be an integer,
because Java’s going to cut off all the decimals.
1 | integer * integer => integer |
eg
1 | int people = 3; |
Golden Rule
If precision is important, use double
for math calculations.
Type: String
We can use the type String
to store text.
1 | String sentence = "Hello world !"; |
String unlike int
in memory,
no matter what you store in the integer variable, it’s always 4 bytes,
but with String, empty text alone takes up 24 bytes, and the more text that you add to a string, the more memory it takes up.
You can use the +
operator to join two String values.
1 | String sentence = "His name is: "; |
You can use the +
operator to blend values into a string.
1 | double points = 50; |
Type: char
We can use the char
type to store single characters.
1 | char gender = 'F'; |
We can join a String value with a char value using the +
operator.
1 | System.out.println("Gender: " + 'F'); |
1 | String gender = "F"; |
It seems that String is more flexible than char,
so why not always use String ?
The answer is【memory】and【performance】!
char consumes less memory, and char is faster than String !
Summarize
There are 6 core data types (we didn’t cover boolean
yet).
Data Type | Value | Amount of Memory (Bytes) | Valid Range of Values |
---|---|---|---|
int | Whole numbers | 4 | From: -2147483648 To: 2147483647 |
long | Very large whole numbers | 8 | From: -9223372036854775808 To: 9223372036854775807 |
double | Decimals | 8 | Decimal can reach 15 significant digits |
String | Text | Varies, 24 bytes for empty text. | - |
char | A single character | 2 | - |
平时开发我基本不使用 byte, short, float
See you in workbook 2.2
补充知识
在以二进制存储数据的计算机中,浮点数存在误差 !=> https://liupj.top/2021/08/31/01/
Math operators
So far you’ve learned about: int
、long
、double
、String
and char
.
Now, you can use math operators shown as below to play with these values.
+, -, *, /, %, ++, --, +=, -=, ...
Pattern
An operation between whole numbers returns a whole number.
An operation between decimals will always perserve the decimal.
Think about that why do we care about the remainder ?
It’s very useful if you want to identify odd or even numbers.
1 | int remainder = 10 % 2; // 0 |
See you in workbook 2.3
Type casting
In Java, we can cast variables from one type to another.
1 | // Cast double to int |
See you in workbook 2.4
Scanner
Scanner contains many methods that we can use to scan for user input.
method | scan for | explaination |
---|---|---|
nextInt() | integers | skips the whiteSpace and picks up the next Integer |
nextLong() | integers | skips the whiteSpace and picks up the next Long |
nextDouble() | decimals | skips the whiteSpace and picks up the next Double |
next() | text | skips the whiteSpace and picks up the next String |
nextLine() | text | picks up a line of data |
… | … | … |
The default delimiter is white space.
Usage
1、Create an instance of Scanner which can receive input from the System.in
.
1 | import java.util.Scanner; |
2、Use Scanner’s methods to pick up (integers、decimals、text、…) from user input.
1 | int coffeeAmount = sc.nextInt(); |
3、Once you are done with Scanner, always close it, otherwise you’re going to get a resource leak.
1 | sc.close(); |
Debugging
Fixing bugs in your code is called debugging, which is a must have skill for any programmer.
Debugging involves tracing the runTime step by step.
Please do not clutter your code with print statements to understand what’s going on,
use breakpoints instead !
the trap of nextLine()
recap
method | scans for | explaination |
---|---|---|
next() | text | skips the whiteSpace and picks up the next String |
nextLine() | text | picks up a line of data |
表面现象
nextLine()
gets skipped when placed after nextInt()
、nextLong()
、nextDouble()
and next()
看清本质
这不就是我在大一学 C 语言的时候,那个曾经让我头疼万分的所谓“没有吃回车”的问题嘛
当时我还浅浅了解了一下什么是 Shell,什么是 Shell 的缓冲区
解决方案
显而易见,用 nextLine()
“吃一下残留在 Shell 的缓冲区中的回车”呗~
即:place a throwaway nextLine before the ‘real’ nextLine
请阅读
See you in workbook 2.5
Booleans and Conditionals
In this section, you will gain full control over how your code runs.
Roadmap
Use conditions to control which parts of your code run.
Execute code by comaring a [value] against a list of [cases].
boolean
1 | boolean bool1 = true; |
Summarize
Data Type | Value | Amount of Memory (Bytes) | Valid Range of Values |
---|---|---|---|
int | Whole numbers | 4 | From: -2147483648 To: 2147483647 |
long | Very large whole numbers | 8 | From: -9223372036854775808 To: 9223372036854775807 |
double | Decimals | 8 | a decimal can reach 15 significant digits |
String | Text | Varies, 24 bytes for empty text. | - |
char | A single character | 2 | - |
boolean | 1 | true or false |
Comparison Operators
>
, Greater than, returns true
if the value on the left is greater than the value on the right.
<
, Less than, returns true
if the value on the left is less than the value on the right.
>=
, Greater than or equal to, returns true
if the value on the left is greater than or equal to the value on the right.
<=
, Less than or equal to, returns true
if the value on the left is less than or equal to the value on the right.
==
, returns true
if two values are equal.
!=
, returns true
if two values are not equal.
Comparing Strings
Do not use ==
or !=
to compare strings.
Instead, you can compare one string to another by calling equals()
from one of them.
1 | String str1 = "hello"; |
You should know about how memory is being allocated. but 目前老师并没有讲
See you in workbook 3.1
if - else
Goal: Use if - else to run specific code blocks based on various conditions.
1 | if (condition) { |
The condition is usually the result of a comparison that returns true or false.
See you in workbook 3.2
Not only can we test only one condition, but also many conditions by embedding a series of else if (condition)
statements.
1 | if (condition) { |
See you in workbook 3.3 and 3.4
Logical Operators
We can use logical operators to make our conditionals a little more complex.
There are 3 types of logical operators,
&&
returns true only if both comparisons are true.
( comparison1 && comparison2 )
||
returns true if either one of the comparison is true.
( comparison1 || comparison2 )
!
reverses the value of a boolean expression.
See you in workbook 3.5
Switch Statements
whenever you’re comparing one variable against a long list of values, such as
1 | if (weather.equals("sunny")) { |
you should avoid having a long list of else if
statements, because this looks so disgusting !
Instead, you should favor using a switch
statement which was designed to compare one variable against a list of cases.
1 | switch (weather) { |
Then you might be asking that when to use if
vs switch
?
The only thing you can really do with switch
is compare one variable against a list of values.
if
statement is more flexible so that suitable for complex conditions, such as when you need to compare multiple variables, they give you the flexibility to evaluate compound conditions using logical operators.
1 | if (temperature >= 80 && humidity >= 60) { |
See you in workbook 3.6 and 3.7
As you write more and more code inside main()
, you’ll notice that it becomes increasingly cluttered and messy.
And the more code you write, the more unreadable that it becomes.
Functions
A function is a grouping of code, it performs a task, and obviously it’s reusable.
Some functions rely on parameters to perform their task.
Some functions will return a final value.
Instead of writing all of your code inside of a single code block,
you can split it up into functions and call them as needed.
Let’s begin organizing your code using functions!
Define functions and call them
See video on udemy.
Notice
Functions’ name needs to represent the task it’s performing.
Notice
public
means the function can be publicly accessed from any package or subfolder,
but because we’ve got only one package with a single class in it,
it doesn’t really matter what level of access you specify.
Notice
You can notice that main()
is also a function, it has a very similar signature to our functions.
Every function has a specific task that it performs, the main()
function performs the task of running our application.
The main()
function has a very specific signature that the JVM looks for when you run your app, when it finds main()
function, it executes it.
Parameters
Functions with parameters expect to receive values.(these functions rely on parameters to perform their task)
Functions【without】parameters【do not expect】to receive values.
Parameters are essentially just variables.
Arguments
A value that you pass into a function is known as an argument.
Parameters and Arguments makes functions completely reusable!
Notice
When a function defines parameters, then in order to call it,
you need to pass in a matching number of arguments based on the position of these parameters.
Return Values
You can return values from a function.
Notice
Bad practice: Your function handles the final result.
Good practice: Your function return the final result.
Notice
Whenever you specify a return type,
you need to make sure that something gets returned no matter what gets passed in.
Terminate the runTime
1 | System.exit(0); |
See you in workbook 4.3
Doc Comments
Can be used to describe what a function does.
If you’re working in a team of developers, you should have a document for every function.
How to write Doc Comments ?
See udemy
See you in workbook 4.4
Scope
The scope of a variable determines its life span.
The take home message is:
You can never access a variable outside the scope that it was defined in.
Global Scope
Please against using global variables,
instead, you should keep everything local and use parameters,
because when you have too many global variables, you start losing track of what’s really going on(such as from your debugger in vscode).
Please watch the video on udemy.
Built-in Functions
The JDK provides so many built-in functions that you can call out of the box.
But to be honest, a good developer never memorizes code!
Instead, a good developer uses the internet!
to read documentation.
to find resources.
See you in workbook 4.5
Loops
For Loops: designed to run code a specific number of times.
While Loops: designed to run code an unknown number of times.
You will use the break
and continue
keywords to gain full control over your loops.
For Loops
1 | for (int i = 0; i < 3; i ++) { |
While Loops
What is a while loop ?
A while loop keeps running while a condition is true.
1 | while (condition) { |
See you in workboook 5.8 ~ 5.10
continue
The continue
keyword skips a run in the loop and continues with the next one.
break
The break
keyword when invoked, breaks the loop entirely.
Nested Loops
A nested loop is a loop inside of another loop.
eg: useful when working with 2D arrays.
1 | for (int i = 0; i < 3; i++) { |
Arrays、2D_Arrays
Looping Arrays、Updating Arrays
Arrays
Sometimes values can be closely related and creating one variable after another can be very messy such as below.
1 | double price1 = 5.99; |
So what we can do is to store all of these values at the same time in an organized way which is called an array.
1 | double[] prices = { 5.99, 6.99, 7.99, 8.99, 9.99 }; |
Although an array can hold many values, all of them have to share the same type.
For example as below, integers
points to an array of integer values.
1 | int[] integers = { 1, 2, 3 }; |
Talk is cheap
1 | String[] kindoms = { "qwe", "asd", "zxc" }; |
The truth is:
the variable kingdoms
doesn’t store the array directly
instead
it stores a [reference] that points to it
1 | // You can try to compile and run this line of code, |
and each element is stored at an index
what will happen if I try to access an element outside the range of the array ?
1 | System.out.println(kingdoms[3]); |
Java throws an ArrayIndexOutOfBoundsException, in essence, crashing our application, telling us that we have an error in our code —— “Index 3 is out of bounds”
Preparing to loop arrays
The length
of an array indicates the number of items it contains.
1 | String[] items = { "apple", "banana", "cherry" }; |
So we can use the length
property to loop arrays.
Looping arrays
Arrays and loops are like siblings.
1 | String[] numbers = { 1, 2, 3, 4, 5, 6 }; |
1 | // Print the elements of an integer array using a loop |
for 循环
1 | // autoComplete a for loop in vscode: fori<ENTER> |
foreach 循环
foreach simplifies looping through an array without the need for a counter or a counter increment or anything.
1 | // autoComplete a foreach loop in vscode: fore<ENTER> |
It just automatically iterates through every single number inside of the numbers array.
So as you can see, foreach is much cleaner and concise than the traditional for loop,
but the traditional for loop is more flexible because the counter i
give us more control over the looping process.
I’m a bit tired of using loops to print an array,
Java has a function called toString
, it takes your array as an argument, and it returns a string that we can print.
Updating Arrays
It’s time to learn how to update arrays.
1 | String[] flavours = { "Sweet", "Sour", "Bitter" }; |
Is it possible to change the array length ?
NO.
Once you create an array, you cannot resize it.
1 | String[] menu = { "Espresso", "Iced Coffee", "Latte" }; |
1 | for (int i = 0; i < menu.length; i++) { |
The reference trap
I told you earlier that a variable cannot store an array, it stores a reference that points to it.
Because of this, another variable can actually store a reference that points to the same array.
1 | int[] numbers = { 1, 2, 3 }; |
Do not set array variables equal to each other!
Instead, create a new array, then, copy every value using a for loop.
A better solution
Arrays.copyOf(a, b);
a
means that the array you want to copy.
b
means that how much of it you want to copy.
2D Arrays
1 | int[][] grades = { |
When to work with 2D arrays ?
2D arrays is perfect for data in the form of a table.
1 | int[][] integers = new int[3][4]; // 3 行 4 列 |
arrays and loops are like siblings
nested loops
- outer loop runs through every row (i)
- inner loop runs through every item in that row
1
2
3
4
5for (int i = 0; i < grades.length; i++) {
for (j = 0; j < grades[i].length; j++) {
// ...
}
}