Java basics – part 2

Tram Ho

A. Data type

1. Primitive types

The primitive types in java include.

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

Primive types are all lowercase.

For primive types, there are a few notes:

  • Number type is always signed (signed)
  • Real numbers can be written in scientific form
  • By default java understands a real number value as double , if you want to use it for a variable of type float, just add the suffix f , for example float a = 3.14f
  • The char type supports escape sequences (such as n , t , …)
  • Characters in single quotes '' , while string in double quotes ""

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

2. Operators

The operators in java are similar to C ++:

  • Increment and decrement operators: a++ , ++a , a-- , --a
  • The pros and cons (position, negation): +a , -a
  • Arithmetic operator: a + b , a - b , a * b , a / b (integer division), a % b (remainder)
  • Tri-operator (ternary): a > b ? a : b and can be nested like (a > 0) ? "Dương" : (a < 0) ? "Âm" : "Số không"
  • Assignment operator: a = 5 assignment and combination assignment like a += 5 , a -= 3
  • Relational operator: Compare with a == 5 , different from a != 5 , big a > 5 , small a < 5 , greater than or equal to a >= 5 , less than or equal to a <= 5 .
  • Boolean operators: operations and a && b , or a || b and not !a
  • The bitwise operator: includes and 10 & 3 , or 10 | 3 and not !10 . Bitwise operations are performed on integers, and the symbol consists of only 1 character.
  • Bit shifting operator: left shift x << y (multiply 2 ^ y), right shift fill with the same x >> y (divide whole 2 ^ y) and right shift fill 0 (zero filled – divide) The integer is the absolute value for 2 ^ y) x >>> y .

3. Math class

The java.lang.Math class has many constants and static functions, which can be used directly from the Math class.

4. Type casting

Type casting is the conversion of data from one type to another. Below is a simple comparison of the number of types (integer and real).

byte <short <int <long <float <double

In the above order, we have two types of casting:

  • From small to large (widening casting): also called implicit casting (implicit casting), java automatically performs appropriate casting in the expression.
  • From big to small (narrowing casting – pressed compact type): also called explicit casting (explicit casting). This type of cast is unsafe and can cause data loss, so java doesn’t do it automatically, you have to cast it manually.

Narrowing casting is insecure, because forcing data from a large type to a smaller type can cause data loss or inaccuracy, because the smaller type may not contain enough data.

The above casting syntax is also used for classes and objects, named upcasting and downcasting, which will be discussed later.

B. Control statements

1. Conditional statement

If else statement

The if else similar to that in C ++. If the condition in if true then execute the statement, otherwise go ahead or execute the statement in the else (if any).

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

If there are 2 or more commands, they need to be placed in {} .

if else blocks can be nested, make sure to put them in clear brackets for easier reading.

Ternary operator

The Ternary operator is a triadic operator, used to replace if conditions in some simple cases, to return values ​​based on conditions. For example, look for even or odd numbers as follows.

Note that the ternary operator selects only one of the two values ​​based on the condition, and does not execute commands like if . As the following example is false.

Switch case

Switch case similar to C ++, no difference.

2. Loop statement

While loop

The while loop checks the condition, if true then execute the command, then return to check the condition again, … until the condition is false then stop.

Do while loop

Loop do while little different from while , is do while will execute the command first and then check the condition. Therefore, the command is always executed at least once.

Both do while and while loops need to avoid endless loops.

For loop

The for loop consists of 3 parts in brackets:

  • The init part used to initialize the variable
  • The condition section specifies the next loop condition
  • The increment is used to increase or decrease the count variable, so that at some point the condition becomes false.

First, the init part executes only once. Then, to check the condition, if true, then execute the command, finally increment. Then come back to check the next condition, and so on until condition is false.

Foreach loop

Java has a different loop, called foreach but still uses the for keyword, but with a different syntax.

This loop loops through each element of an iterable object (array, string, collection, …), from beginning to end. For each iteration, the value of the counter is equal to the value of the pointing element.

Break & continue

The two words break and continue often used in loops:

  • break stops the entire loop running
  • continue stops the current iteration, and advances to the next iteration

Label & goto

Do not use anymore because it messes with the code logic.

C. Basic method

1. Overview

Java is pure OOP language, so everything in java must belong to a class. The concepts of functions and procedures when in a class are called methods. Therefore, methods can be understood as functions in the class.

The method declaration syntax is quite similar to the function in C ++, including:

  • The first part contains modifiers , return types, method names, and parameter lists in ()
  • The method body in the {} pair contains the commands to be executed

Java’s method declaration is slightly different from C ++ in that there are more modifiers, simply understood as keywords attached to the beginning of the method, to transform the function of the method. This section will be explored later.

Call the method

In the above example, we declare the methods as static , so they can be called together for easy understanding. The static method part will be discussed later.

Basically, there are 2 cases to calling the method:

  • The method to be called is in the same class: calling directly by name and passing arguments
  • Method in another class: if the method is normal, then enclose the name of the object containing it in front of it, in the form obj.method() . If it is a static method then call the class name MyClass.method() .

Return value

Java also has the return keyword, to return a value inside the method.

2. Params & args

Parameters & arguments

Parameters (parameters – abbreviated param) are variables that store the value passed to the method. The parameters are considered equivalent to the local variable in the method.

Arguments (arg) are values ​​actually passed to the method, each call of a different method may have a different argument.

Parameters are abstract, they have no specific value depending on what is the argument passed to the method. The new arguments are the actual values, passed to the method and turned into parameters.

See the following example for a better understanding.

3. Arguments passing

In C ++, there are many types of argument passing (arg passing) like values, references, and pointers. In java, all arguments are passed by pass by value:

  • The argument is primitive: a copy of the argument is created and passed as a parameter, so the method manipulating this copy should not change the original data.
  • The argument is wrapper: because the wrapper is immutable, they are similar to primitive types, so they are also passed by value.
  • Object argument: Can be assumed to be passed by reference, since the original data may be changed after the method executes. Actually it is still pass by value, but the copy created is the reference copy of the object, so it is still pointing to the same object, so the method has the ability to change the original data.

Note, java is always pass by value, and there is no pass by reference. For details, please refer to the 3rd item above.

4. Method overloading

Method overloading is a method but it has many different versions. In other words, there are many methods with the same name but different parameters.

When calling the overloaded method, depending on how the argument is passed, the version with the corresponding parameter is called.

As in the following example, there are two methods hello() , but when calling with different arguments, one of the two methods will be called.

The overloaded methods have the same name, but the difference is in:

  • Number of parameters
  • Order of parameters
  • Parameter data type

Just one of the three different declarations is a new overloaded version.

Note, two methods with the same name but different return type are not counted as overload, because java will not understand which version to run (ambiguous error).

5. Main method

In java program can have many classes, each such class has many methods. However, there is a special class marked public class , whose name is the same as the .java file name. In that public class there is a method named main as follows.

This main() method is the starting point of every java program. It is called first when running the program.

The main() method takes a string array called args as an argument, to store command line arguments. main() has no return type, but when an error occurs it returns a number and stops.

The main() has two important modifiers, their functions are as follows:

  • public (access modifier): Allows the main() method to be called from the outside. When the program runs, the JVM will be the one that calls for main() , and the JVM is an external object, so the main() must be public .
  • static : When the program first runs, no objects are created. Therefore main() must be a static method for the JVM to call it from the App.main() class, not from the object.
Share the news now

Source : Viblo