An Incomplete Guide For Java Beginner
Basic Terminology
- Program – a sequence of instructions (called statements), which are executed one after another in a predictable manner. Sequential flow is the most common and straightforward sequence of statements, in which statements are executed in the order that they are written – from top to bottom in a sequential manner;
- Statement – a single action (like print a text) terminated by semi-colon (
;
); - Block – a group of zero, one or more statements enclosed by a pair of braces
{...}
; There are two such blocks in the program above. - Method – a sequence of statements that represents a high-level operation (also known as subprogram or procedure).
- Syntax – a set of rules that define how a program needs to be written in order to be valid; Java has its own specific syntax that we will learn;
- Keyword – a word that has a special meaning in the programming language (
public
,class
, and many others). These words cannot be used as variable names for your own program; - Identifier or name – a word that refers to something in a program (such as a variable or a function name);
- Comment – a textual explanation of what the code does. Java comments start with
//
. - Whitespace – all characters that are not visible (space, tab, newline, etc.).
What Do Matter …
- Public Class: A class can have any name, such as
App
,Main
, orProgram
, but it must not start with a digit. A set of braces{...}
encloses the body of a class.
1 | public class Main { |
- Main Method : we put a method named
main
inside a class. It is the entry point for a Java program. The name of this method (main
) is predefined and should always be the same.
1 | public static void main(String[] args) { |
1 | System.out.println("Hello, World!"); // each statement has to end with ; |
Printing Data …
The
println
method displays the passed string followed by a new line on the screen (print-line).Print an empty line:
1 | System.out.println(); // prints empty line |
- The
print
method displays the passed value and places the cursor (the position where we display a value) after it. As an example, the code below outputs all strings in a single line.
1 | System.out.print("I "); |
Declaring and initializing
Declaration
1
DataType variableName = initialization
The **type (**or data type) of a variable determines what possible operations can be performed on the variable and which values can be stored in it. Here we use a non-existing data type (DataType) to demonstrate the general form of declaration.
The **name (**or identifier) distinguishes the variable from others. The name of a variable cannot start with a digit; it usually starts with a letter. Always try to choose meaningful and readable names for variables to make your code easy to understand.
The assignment operator denoted as
=
is used to assign a single value or a result of an expression to a variable.The initialization is a value or a result of an expression that is assigned to the variable.
Some Examples:
1 | String language = "java"; |
Accessing the value of a variable
you can only assign a value of the same type as the type of the initial variable.
Alternative forms of declaration
Declaring several variables of the same type as a single statement:
1
String language = "java", version = "8 or newer";
Separating declaration and initialization into statements:
1
2int age; // declaration
age = 35; // initialization
What’s new?
Type inference
Since Java 10, you can write var instead of a specific type to force automatic type inference based on the type of assigned value:
1
var variableName = initialization;
Here are two examples below:
1
2var language = "Java"; // String
var version = 10; // int
Comments
End-of-line comments
The java compiler ignores any text from
//
to the end of the line.1
2
3
4
5
6
7
8class Program {
public static void main(String[] args) {
// The line below will be ignored
// System.out.println("Hello, World");
// It prints the string "Hello, Java"
System.out.println("Hello, Java"); // Here can be any comment
}
}Multi-line comments
The compiler ignores any text from /*
and the nearest */
. It can be used as multiple and single-line comments.
1 | class Program { |
Naming
- names are case-sensitive;
- a name can include Unicode letters, digits, and two special characters (
$
,_
);- Since Java 9 the single character
_
is an invalid name for a variable, but_a
and__
(double_
) are legal names.
- Since Java 9 the single character
- a name cannot start with a digit;
- a name must not be a keyword (
class
,static
,int
are illegal names).
Note that to keep backward compatibility the word "var" can be used as a variable name even after Java 10 was released.
- if a variable name is a single word it should be in lowercase (for instance:
number
,price
); - if a variable name includes multiple words it should be in
lowerCamelCase
, i.e. the first word should be in lowercase and each word after the first should have its first letter written in uppercase (for instance:numberOfCoins
); - variable names should not start with
_
and$
characters, although they are allowed; - choose a name that makes sense, e.g.
score
makes more sense thans
, although they are both valid.
Standard Input (Scanner)
- Read single-line input
The simplest way to obtain data from the standard input is to use the standard class Scanner
. It allows a program to read values of different types (string, numbers, etc) from the standard input.
1 | import java.util.Scanner; |
Do not forget the
;
in the end of thois Statement
Then construct an object of Scanner
class.
1 | Scanner scanner = new Scanner(System.in); |
To read the input data, use:
scanner.next()
for a single word or an integer number (will read the input till the whitespace)scanner.nextLine()
for any string with whitespace, tab,non-printing characters or whateverInput will be processed as string
Read multiline input
nextLine()
will read input from the position of the cursor till the new line (and again, if there is such a line in your input). If there is no anything left to read in the current line, thenextLine()
method will return an empty line (“”) and place the cursor at the beginning of a new line.
For example, the content below will be processed by Java like this:
Content:
1 | |This is a simple |
Code:
1 | import java.util.Scanner; |
Arithmetic operations
- Binary arithmetic operators
- addition
+
- subtraction
-
- multiplication
*
- integer division
/
- remainder
%
- addition
The /
operator returns the integer part of the division of two integer numbers, and any fractional part is discarded.
1 | System.out.println(8 / 3); // prints 2 |
The %
returns the remainder of the division of two numbers. When the dividend is less than the divisor, the quotient is zero and the remainder equals the dividend.
1 | System.out.println(10 % 3) // prints 1, because 10 divided by 3 leaves a remainder of 1 |
Unary operators
- The unary plus operator indicates a positive value. It’s an optional operator.
1
System.out.println(+5); // prints 5
- The unary minus operator negates a value or an expression.
1
2System.out.println(-8); // prints -8
System.out.println(-(100 + 4)); // prints -104Precedence Order
- parentheses
- unary plus/minus
- multiplication, division
- addition, subtraction
Integer types and operations
If a number ends with the letter L
or l
it is considered as long
, otherwise, it is int
. It is recommended to use the uppercase letter L
.
Use =
, /=
, %=
+=
to make operation concise
Read numbers from standard input
1
2
3
4
5
6
7
8
9
10
11
12
13
14import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum = a + b;
System.out.println(sum);
}
}long
can be used in replace ofint
.1
2
3long a = scanner.nextLong();
long b = scanner.nextLong();
long sum = a + b;
Increment and decrement
1 | int n = 10; |
prefix (
++n
or--n
) increases/decreases the value of a variable before it is used;postfix (
n++
orn--
) increases/decreases the value of a variable after it is used.
1 | int a = 4; |
The value of a has been incremented and then assigned to b. So, b is 5.
1 | int a = 4; |
Postfix operator has higher precedence than the assignment operator.
When assigning a++
to b
, we actually assign 4, while a
itself has already been incremented. So, b
is 4 and a
is 5.
1 | int a = 4; |
Characters
1 | char lowerCaseLetter = 'a'; |
Initializing with unicode
1
2char ch = '\u0040'; // it represents '@'
System.out.println(ch); // @Any
char
variable may be considered as an unsigned integer value in the range from 0 to 65535.1
2char ch = 64;
System.out.println(ch); // @Subsequent characters
1
2
3
4
5
6
7
8
9
10char ch = 'b';
ch += 1; // 'c'
ch -= 2; // 'a'
// --------------------- //
char ch = 'A';
ch += 10;
System.out.println(ch); // 'K'
System.out.println(++ch); // 'L'
System.out.println(++ch); // 'M'
System.out.println(--ch); // 'L'Escape sequences
'\n'
is the newline character;'\t'
is the tab character;'\r'
is the carriage return character;'\\'
is the backslash character itself;'\''
is the single quote mark;'\"'
is the double quote mark.
1
2
3
4System.out.print('\t'); // makes a tab
System.out.print('a'); // prints 'a'
System.out.print('\n'); // goes to the new line
System.out.print('c'); // prints 'c'Code above will be phrased as :
1
2a
c
String
immutable type: it’s impossible to change a character in a string;
it has methods for getting individual characters and extracting substrings;
individual characters can be accessed by indexes, the first character has the index 0, the last one – the length of the string – 1;
non-primitive type.
A string can be
null
. It means no value assigned.1
String nullString = null; // it is null
Another way to create a variable of String is by using the keyword new.
1 | String str = new String("my-string"); // it creates an object and assigns it to the variable |
Methods
Documentation here.
Any string has two useful methods:
length()
returns the number of characters in the string;charAt(int index)
returns a character by its index;
1 | String s = "Hi, all"; |
isEmpty()
returnstrue
if the string is empty, otherwise –false
;toUpperCase()
returns a new string in uppercase;toLowerCase()
returns a new string in lowercase;startsWith(prefix)
returnstrue
if the string starts with the given string prefix, otherwise,false
;endsWith(suffix)
returnstrue
if the string ends with the given string suffix, otherwise,false
.contains(...)
returnstrue
if the string contains the given string or character;substring(beginIndex, endIndex)
returns a substring of the string in the range:beginIndex
,endIndex - 1
;replace(old, new)
returns a new string obtained by replacing all occurrences ofold
withnew
that can be chars or strings.trim()
returns a copy of the string obtained by omitting the leading and trailing whitespace. Note that whitespace includes not only space character, but mostly everything that looks empty: tab, carriage return, newline character, etc.
1 | String text = "The simple text string"; |
Concatenation
Two strings can be concatenated using the “+” operator or the concat
method.
1 | String firstName = "John"; |
Append
1 | String str = "str" + 10 + false; // the result is "str10false" |
1 | String shortString = "str"; |
Compare
only addresses will be compared, but not actual values.
1 | String first = "first"; |
Logical operators
- NOT is a unary operator that reverses the Boolean value. It is denoted as
!
.
1 | boolean f = false; // f is false |
- AND is a binary operator that returns
true
if both operands aretrue
, otherwise, it isfalse
. It is denoted as&&
.
1 | boolean b1 = false && false; // false |
- OR is a binary operator that returns
true
if at least one operand istrue
, otherwise, it returnsfalse
. It is denoted as||
.
1 | boolean b1 = false || false; // false |
- XOR (exclusive OR) is a binary operator that returns
true
if boolean operands have different values, otherwise, it isfalse
.
1 | boolean b1 = false ^ false; // false |
The XOR operator is used less often than others. Just remember that Java has it. If you really need it, you can use it.
Priority:
!
(NOT) >^
(XOR) >&&
(AND) >||
(OR).
Relational operators
==
(equal to)!=
(not equal to)>
(greater than)>=
(greater than or equal to)<
(less than)<=
(less than or equal to)
Priority: Logical operators < Relational operators < arithmetic operators.
Conditional Statement
1 | if (b) { // or !b (Condiction in the bracket is true) |
Ternary operator
Conditional Statement:
1 | int a = ...; |
Ternary Operator:
1 | int max = a > b ? a : b; |
that is to say:
1 | result = condition ? trueCase : elseCase; |
Another sample to judge even or odd number:
1 | int num = ...; // it's initialized by a value |
For-loop
Basic framework:
1 | for (initialization; condition; modification) { |
- initialization statement is executed once before the loop begins; usually, loop variables are initialized here;
- condition is a Boolean expression that determines the need for the next iteration; if it’s
false
, the loop terminates;- modification is a statement that changes the value of the loop variables; it is invoked after each iteration of the loop; usually, it uses increment or decrement to modify the loop’s variable.
it is also possible to write an infinite loop without these parts at all:
1 | for (;;) { |
An example…
1 | for (int i = 1; i < 10; i++) { |
Which will print:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Switch Statement
1 | switch (variable) { |
An example:
1 | int val = ...; |
It is highly recommended to add a break
after each case.
If a case meets the according condition, the following case will be executed directly from the entry point without judgement
Since Java 14, switch can be treated as an expression, returning a value from the statement. To achieve that a new switch**-**related keyword yield was introduced which works as a return statement.
1 | int count = switch (day) { |
Unit of information
The smallest unit of information is the bit (b). 1
and 0
.
A byte (B) means 8 bits
bit numbers use the lowercase letter “b” while the bytes are capital “B”.
SI metric | Symbol | Powers of ten | IEC metric | Symbol | Powers of two |
---|---|---|---|---|---|
Kilobyte | kB | 10^3 B (1000 B) | Kibibyte | KiB | 2^10 B (or 1024 B) |
Megabyte | MB | 10^6 B (1000 kB) | Mebibyte | MiB | 2^20 B (or 1024 KiB) |
Gigabyte | GB | 10^9 B (1000 MB) | Gibibyte | GiB | 2^30 B (or 1024 MiB) |
Terabyte | TB | 10^12 B (1000 GB) | Tebibyte | TiB | 2^40 B (or 1024 GiB) |
Petabyte | PB | 10^15 B (1000 TB) | Pebibyte | PiB | 2^50 B (or 1024 TiB) |
Datatype in Java (number)
byte
: size 8 bits (1 byte), range from -128 to 127short
: size 16 bits (2 bytes), range from -32768 to 32767int
: size 32 bits (4 bytes), range from −(231) to (231)−1long
: size 64 bits (8 bytes), range from −(263) to (263)−1- Floating-point types:
double
(64 bits) andfloat
(32 bits).
Note, that when we declare and initialize a float
variable, we should mark the assigned value with the special letter f. It is often a good practice to mark a long
value with l as well.
Casting
Implicit casting
Transformation will be automatically completed by compiler and there is no loss in most cases when transforming.
The direction of implicit casting:
- from
int
tolong
:
1 | int num = 100; |
- from
long
todouble
:
1 | long bigNum = 100_000_000L; |
- from
short
toint
:
1 | short shortNum = 100; |
- from
char
toint
: (Will get the ASCII code of the according character)
1 | char ch = '?'; |
However, the loss could exist in some cases: int
to float
, or a long
to float
nor to double
1 | long bigLong = 1_200_000_002L; |
Explicit casting
Usage:
1 | (targetType) source |
1 | double d = 2.00003; |
Branching Statements
Break
Statement
- it terminates the current loop of any type (for, while, do-while);
- it terminates a case in the switch statement (if-else);
1 | int i = 10; |
Another trick using break
to print pyramid:
1 | for (int i = 0; i < 10; i++) { |
The output will be printed like:
1 | 0 |
Continue
statement
It causes a loop to skip the current iteration and go to the next one.
- inside the for-loop, the continue causes control to immediately move to the increment/decrement statement;
- inside the while or do-while loop, control immediately moves to the condition.
1 | int n = 10; |
The output will be like:
1 | 0 2 4 6 8 |
Which is in fact another realization of the counter condition:
1 | int n = 10; |
An interesting code for practice:
1 | for (int i = 0; i < 5; i++) { |
The visualized result can be accessed below:
Defining methods
A method has…. (bolded elements are compulsory)
- a set of modifiers (
public
,static
, etc.); - a type of the return value;
- a name;
- a list of parameters (as well known as formal parameters) in parenthesis
()
; - a list of exceptions;
- a body containing statements to perform the operation.
An example:
1 | public static int sum(int a, int b) { |
The combination of the name of a method and its parameter types is called the signature. It doesn’t include the returning type, modifiers, and names of parameters.
The considered method sum
has the following signature sum(int, int)
.
Naming Methods
a method name should be a legal identifier with following attributes:
- identifiers are case-sensitive;
- an identifier can include Unicode letters, digits, and two special characters (
$
,_
); - an identifier can’t start with a digit;
- identifiers must not be a keyword.
Setting returning value type and parameters
1 | public static void printSum(int a, int b) { |
The code above prints the sum and returns no value due to void
.
When you call a method with a value of a primitive type then a copy of the value is created. Inside a method, you can process this copy. If you change it, the passed argument is not changed.
1 | public static void main(String[] args) { |