Java basics – part 1

Tram Ho

A. Introduction

1. Java introduction

a. What is Java?

Java is a high-level programming language and a platform for running programs written in Java.

Java can create many different types of applications:

  • Standalon application: software commonly used
  • Web application: run server side, create dynamic web pages
  • Enterprise application: For businesses, banks, … need security, safety and high load
  • Mobile application

Currently there are about 3 billion devices running Java, which means that Java is very popular today.

b. History

James Gosling and his colleagues created the Java language, originally called Greentalk, then Oak (oak) and used only in electronic, embedded devices. After 1995 the name was changed to Java (island in Indonesia).

Java undergoes various versions, the latest of which is SE 14.

Java is currently owned by Sun Microsystems (of Oracle).

c. Editions

There are 4 major versions of Java, for different purposes:

  • Java Card: for smart cards (ATM, SIM, etc.)
  • Java ME (Micro edition): compact version for mobile and embedded devices
  • Java SE (Standard edition): the standard version, the core platform of Java
  • Java EE (Enterprise edition): Enterprise version, large system

d. Features

Java has many features and features that are superior to other languages, below presents some of the most important features of Java.

Platform independent

Platform independence is the most important feature of Java. Java compiles the source code into platform-independent bytecode, which runs on any hardware, OS that Java supports (java platform).

Write once, run anywhere – Java’s criteria

Simple

Java is a simple language, the syntax is easy to learn and close to C ++, and removes unnecessary, cumbersome features such as pointers (pointers), operator overloading (operator overloading), …

Besides, Java has GC that helps clean up memory automatically without manual management.

Object oriented

Java is pure object-oriented language (OOP).

Multi threaded

The java program may have multiple threads, so the speed and performance will be better.

Secure

Java is a safe language, minimizing potential security issues. Java does not use insecure pointers, strict cast, strict code verification.

Besides, the program runs in the JVM so it is easy to control errors.

Robust

Java is strong in its automatic memory management, exception handling, and error checking.

Portable

Java’s compiled Bytecode can take on many different platforms and still work well, so java is portable.

2. Java concepts

a. Components

Java platform

Platform is a type of hardware or software that can run a program.

Thus, java platform is the platform that allows running java programs on it. Java platform includes libraries, compilers and many other support tools for running programs.

Java Virtual Machine (JVM)

The Java Virtual Machine (JVM) is an executable environment preparation program for Java applications. It can be viewed as a virtual machine (abstract) to run the program inside it.

JVM has 4 functions:

  • Upload bytecode from .class file to memory (class loader)
  • Verify bytecode valid (verifier)
  • Translate bytecode to machine code (intepreter) and execute
  • Provide execution environment

Java Runtime Environment (JRE)

Including JVM, running libraries and supporting programs to run applications written in Java. Can be compared to .NET framework installed on the computer.

JRE for users, required if you want to run applications written in java. Without JRE, it will not work.

Java Development Kit (JDK)

Including JRE and java programming tools (compilers, interpreters, archives, docs, …). This is a toolkit for programmers, to write java programs.

Garbage collection (GC)

A component of the JVM, which is used to collect unused memory and return it to the OS, saves memory.

b. IDE

Should choose Eclipse when learning Java because it is simple, light and convenient. Other IDEs like NetBean or IntelliJ IDEA are heavier and more difficult to configure, only suitable for complex projects.

Link https://www.eclipse.org/downloads .

c. Build commands

Although IDEs support build and run programs, or have build tools like Maven or Grade, you should know how to compile manually using the command line.

Compile the Test.java file into Test.class containing bytecode.

Execute bytecode in Test.class file and run the program. Note there is no need to add the .class extension to the file name.

The javac.exe program is in the JDK (programmer), and java.exe is in the JRE and the JDK (because the JDK contains the JRE).

d. Naming conventions

In order for java code to be clearer, more readable and consistent, some naming conventions (java naming conventions) should be followed. This is not required, but is recommended to write cleaner code.

Basic naming conventions:

  • Lower case: all lowercase java.util
  • Snake case: all lowercase letters, between words with underscore your_name
  • Pascal case: capitalize the first letter of each word, the rest lowercase PascalCase
  • Upper case: full capitalization, between words with underscore SQRT_2
  • Camel case (camel): the first letter is lowercase, the second word is the uppercase letter, the rest is lowercase yourName , myRedCar

Different entities have their own naming conventions:

  • Package name: Lower case or snake case java.util
  • Class name: Pascal case, is the noun MyClass
  • Interface name: Pascal case, is an adjective Flyable
  • Object name: Camel case obj , otherObject
  • Variable name: Camel case or snake case myName , your_name
  • Constant name: Upper case PI_NUMBER
  • Method name: Camel case, starting with the verb getName , toString

B. Java basic

1. Java basic

a. Simple program

Structure a basic Java program

Source code stored in the Test.java file, Test is the name of the program and is the same as the name of the public class (case sensitive). Note that the public class name must be the same as the file name plus the .java extension.

For each java program, there should be a public class with the same name as the file name as above, other classes, if any, only the class is declared as a class .

Inside the public class , there is a public static void main() . This method takes array of String as args command line parameters.

b. Comment

There are 2 types of comments in java:

  • Single line comment: From the end of the two lines, // comment
  • Block comment: enclose a piece of code in the /* */ folder

Comments are ignored when compiling.

c. Import

Use the import keyword to import one or more classes into the program:

If you do not import the above, then in the program, when you want to use, you need to specify package.class , such as java.util.Scanner sc = new java.util.Scanner() instead of importing will use Scanner sc = new Scanner() .

d. Variables & constants

Variables

Variables in JS have three types, each of which has its own position:

  • Instance variable: in class, not of any method. This variable belongs to entities created from the class.
  • Static variables: are in class, do not belong to any method, but have static keyword specifying variables that belong to class, not objects.
  • Local variable: is declared in the method.

Declaring variables in java is similar to C ++. Can declare without initializing the initial value, can declare multiple variables at the same time.

Constants

The previous constant declaration in java uses const , but is replaced by the final keyword.

Variables can assign new values, while constants do not, and constants require an initialization value when declared.

Location declared

As mentioned above, each different declared position, the variable, constant will have different meanings. Below is the summary code.

e. Input & output

Output

Use the System.out.print() group commands to output the output to the console screen (of cmd or eclipse).

The above commands only accept the first parameter is string, for printf() , the following parameters are the values ​​passed. Therefore, writing the following is wrong.

Which must use + string concatenation, java will automatically convert to string and true.

In addition to the output stream, System.out has the same System.err , but only uses the error to output to the screen. The console in eclipse will display the text exported from System.err in red.

Input

To import data, use java.util.Scanner class to import. There are two notes when using this class to avoid unexpected errors:

  • A single Scanner object should be used for the entire program. Two scanners with the same access to the System.in stream will cause a conflict (even if one scanner is closed).
  • When using the scanner, call the close() method to close the input stream.

To read data with the scanner, use different methods of next_() , depending on the data type.

Important note, after using functions like nextInt() , nextFloat() , you should use a command nextLine() immediately after to delete extra characters n in the buffer. The above functions only take numbers, so leaving the n character behind will cause the nextLine() command to enter a string that is drifted (resulting in an empty string, it runs always without waiting for the input).

With the above code, if two lines of input.nextLine() are input.nextLine() , the string input command will be washed away, without waiting for the user to enter.

2. Data types

a. Primitive types

The primitive data types in java are as follows.

TypeSize
boolean1 bit
char2 bytes
bytes1 byte
short2 bytes
int4 bytes
long8 bytes
float4 bytes
double8 bytes

Primitive types are all lowercase.

Some notes about data types:

  • Numbers in java are always signed (signed)
  • Real numbers can be written in scientific form
  • For float real numbers, it is necessary to specify the suffix f such as float a = 3.14f . By default, java interprets a real value as double , so an error will occur when cast, so it is necessary to specify it after the value as above.
  • Char in java supports escape sequense (eg n , t , …)
  • Characters in single quotes '' , and string in double quotes ""

In particular, String type is both primitive and object type.

b. Operators

The same C ++ operators

The operator in java is similar to C ++, and is summarized as below.

The difference between >> and >>> is the number filling in the left blank space. >> fill the bit with the current sign, and >>> always fill 0.

c. Math class

Java has many common mathematical functions in the java.lang.Math class as static methods. Besides this class also contains static constants like pi, e, …

d. Type casting

Use conversion from one data type to another. Below is a simple comparison of the magnitude of the numeric types (both integer and real).

byte <short <int <long <float <double

According to the comparison above, we have two types of casting (type casting):

  • From small to large (widening casting): also called implicit casting (implicit casting), java automatically presses the model accordingly.
  • From narrowing casting (narrowing casting): also known as explicit casting. Because it is unsafe, java is not automatic, you must manually cast it.

Narrowing casting is unsafe because pressing from large to small can result in loss of data and result in inaccurate data.

The following code illustrates the two types of cast.

This type of cast syntax is also used for classes and objects, called up casting and down casting, which will be discussed later.

3. Basic commands

a. Conditional statement

If else statement

Conditional statements in Java are similar to C ++, it will check conditions, execute the command correctly, otherwise execute in else (if any) and continue.

A condition can be anything that returns a boolean, like a boolea variable, a comparison, a logical expression, etc.

If there are two or more commands, execute them in the {} folder.

if else blocks can be nested (should be placed {} for clarity) or consecutively.

Ternary operator

Another way to perform condition checks and return values ​​is to use the ternary operator. The ternary operators can be consecutive as above.

Note that the ternary operator does not support selecting execution instructions, but only chooses one of the two results to return, as in the following example.

Switch case

Java also supports switch case statements to split more branches, handle more cases instead of using multiple if else serial. The switch case , however, is only compared, not other comparisons.

The statement block consists of an expression used to compare cases, and if it matches any case, the commands in that case group will be executed.

After each case there should be a break statement to break, otherwise it will run to the next case group without conditions.

Default is the block that will run when none of the above cases match. The default block can be ignored.

b. Looping

Java’s loop is exactly like C ++, so I won’t say much here.

While loop

Check the condition, if true, execute the command and return to the next test. Just like that until the conditions are wrong then exit.

Do while loop

Execute the command and then check the condition, if the condition is true then execute it again and check again. So on until the conditions are wrong then stop.

Do while bit in contrast to while , do while execute the command at least once, while while may not execute at any time. This is because the order of conditional checking and execution of the two loops is different.

Always check a deep pool before running! – Coder

Gravity will not exist if you do not look down – Cartooner

For loop

The for consists of 3 parts in parentheses:

  • The first part is initializing the variable value, only called 1 time first
  • Part 2 is a continuation condition, which is checked for each iteration, whether or not to continue.
  • Part 3 is to increase or decrease the count variable, to avoid endless iterations. This part is last executed every iteration, even after the command is executed.

Foreach

Often called loop for each but still use the keyword for but in a different syntax.

Iterates through each element of an iterable object (array, string, collection, …). For each iteration, the element in turn is each element.

Break, continue

The two words break and continue often used in loops:

  • break to stop the loop in progress
  • continue stops the current iteration and jumps to the next

c. Label, goto

Not used anymore because it messes up your logic code.

Share the news now

Source : Viblo