[Java] Summary of knowledge required to pass Java SE8 Silver

18 minute read

Introduction

I had to use Java for my work and for the time being decided to get Java Silver in order to systematically learn, so I’ll briefly summarize what I learned there by keyword.

Java basics

Class declaration

The class declaration consists of fields and methods. The constructor is part of the method

Package purpose

  • Providing namespaces and avoiding name collisions
  • Provides access control function in combination with access modifier
  • Enable class classification

Package declaration

  • Make sure the package declaration is on the first line of the source code.
  • Only comments can be written before the package declaration

Import class

  • java.lang package is a package in which basic classes are collected, and import declaration can be omitted.
  • Classes belonging to the specified package are imported, but subpackages are not imported

Packages and access control

Classes belonging to a package can only be accessed by classes in the same package. Classes belonging to anonymous packages can only be accessed by classes belonging to the same anonymous package

static import format

Originally, it is necessary to clearly indicate which class a static field or method belongs to in the format of class name.field name (method name). Static import is used to abbreviate them by name only

import static package name.class name.field name (method name)

Do not add parentheses or arguments to the method name in the static import declaration of the method

static import specifications

  • If the imported class has the same name as the imported method or field, the import will be ignored.
  • If you import multiple fields with the same name or method, a compile error will occur.

main method

You can define multiple methods in the class, but the method to start the process, the description of the entry point and the rules are as follows.

public static void main(String[] args) {

}
  • Be public (Public)
  • What you can do without creating an instance (Static)
  • Return value cannot be returned (Void)
  • Method name is main
  • Argument must receive one String array type

java command

The java command is a command for starting the JVM. The syntax is

java fully qualified class name [argument argument...]

Manipulating Java data types

Java data type

Java data types include primitive types (integer, floating point number, boolean, character) and reference types (object type, enumeration type, array type). The data types of the primitive types are as follows no bool type

Data type value
boolean true,false
char 16-bit Unicode character
short 16-bit integer
int 32-bit integer
long 64-bit integer
float 32-bit single-precision floating-point number
double 64-bit single precision floating point number

integer literal

A literal is a value described in the source code.In Java, integer values are handled as int type, floating point values are handled as double type, boolean values are handled as boolean type, and characters are handled as char type. Be seen.

suffix, prefix

By adding suffixes and prefixes, it is possible to specify the data type and notation other than decimal numbers.

  • Suffix example long type・・・L, float type・・・f

・Example of prefix 0…octal 0x…hexadecimal 0b…binary number

underscore

Numerical notation using underscore is used for the purpose of improving readability of numeric literals with many digits, and has the following rules.

  • Cannot be written at the beginning and end of literals Cannot be written before or after the + sign

Character literal, string literal

char is a data type that represents a character The following can be assigned to chara type

  • Characters enclosed in single quotes (character literals)
  • Unicode number starting with \u enclosed in single quotes (character literal)
  • Numeric value from 0 to 65535 (numeric literal)

Enclose character literals in single quotes Enclose string literals in double quotes

Identifier naming convention

An identifier is the name of a variable, method, class, etc. Basics can be freely decided, but there are the following rules

  • Reserved words cannot be used (context expressions such as int, if)
  • Only underscore and currency symbol ($) can be used
  • Don’t start with a number (after the second letter)

null

null is a literal to express that the reference type variable does not hold a reference. Not the empty string (“”)

How to call the method

The method to call is as follows

  • Method name (argument)-method defined in the same instance
  • Variable.method name (argument)… In case of method defined in instance
  • Class name.method name (argument)… In case of static method

Signature

A signature is a set of method name and argument list. Java has a mechanism called overloading, and there may be multiple methods with the same name. Therefore, use signatures to identify the methods.

Garbage collection

In C language etc., it is necessary to write a code to secure or release memory in a program, but Java has an automatic memory management function. Garbage collection means that the garbage collector finds unnecessary instances and discards them. The target of garbage collection is an instance that is no longer referenced from anywhere, and when null is assigned to a variable as a typical timing.

Using the # operator and decision structure

Assignment operator

The types and meanings of assignment operators are as follows

Operator Usage example Meaning  
= a = 10; Substitute 10 for a
Substitute a+10 for += a += 10 a
Substitute a-10 for -= a -= 10 a
Substitute a*10 for *= a *= 10 a
Substitute a/10 for /= a /= 10 a

Minus operator

There are two types of minus operator (-): subtraction and positive/negative inversion.

Type conversion

Explicit cast is required when assigning a large range of values to a small variable

int a = 15;
short b = (short) a;

Numeric literals for integers are basically int type, and in the case of floating point, double type is basic, so when you put the value in a small variable, you must cast explicitly in principle. In the case of a variable literal that is assigned to a byte type or short type variable, if the value is within that range, no compilation error occurs.

・Byte type and short type range

Model name Range
byte -128~127
short -32768~32767

increment and decrement

Increment (++) and decrement (–) are operators for adding or subtracting 1 to the value of a variable. When combined with other operators, when pre-positioned, they are incremented (decremented) and then assigned, and when they are post-positioned, they are assigned and then incremented (decremented).

int a = 10
int b = 10
int c = ++a // increment a and then assign to c a=11,c=11
int d = b++ //substitute b and then increment d=10,b=11

Relational operators

The relational operator is an operator that compares the values on the left and right and returns a boolean value.

Operator Example Meaning  
== a == b true if a and b are equal  
!= a != b true if a and b are not equal  
> a> b true if greater than b
>= a >= b true if a is greater than or equal to b  
instanceof a instanceof b true if b is an instance of the same class as b or a subclass of b  

, >= can only compare numerical values

Logical operator

Logical operators are used to combine multiple relational operators and specify complex conditions.

Operator Example Meaning        
& a>10 & b>10 true if the expressions on both sides are true        
&& a>10 && b>10 true if the expressions on both sides are true        
    a>10 b>10 true if either expression on both sides is true    
      a>10   b>10 true if either expression on both sides is true
! !a>0 false if expression is true, true if false        
&& and   are called shortcut operators. If the expression on the left side is false, false is decided as a whole, so the expression on the right side is not evaluated. If the expression on the right side contains a process that changes the value, such as increment, the result is different from & or .

Operator precedence

Operators have priorities, and if the operators have the same priority, objects having different priorities are calculated from the left in descending order of priority.

Priority Operator
1 [array]. (argument) a++ a–
2 ++a –a +a ~ !
3 new (type)
4 * / %
5 + -
6 « » »>
7 <> <= >= instanceof
8 == !=
9 &
10 ^
11
12 &&
13 ?:
14 = += *= /= %= &= ^= != «= »= »>=

Identity, equivalency

The same instance is called the same value, and the same value is called the same value. Identity is judged by the == operator

Object a = new Object;
Object b = a; // Assign a copy of the reference of variable a to b
System.out.println(a == b); //true

Equivalence is the property that the instances have different values but have the same value. Use the equals method to see if they are equal. The eauals method of Object class receives Object type as an argument and returns a boolean return value. It is common to bar ride.

//Equals method of Object class
Public boolean equals(Object obj){
    return(this == obj);
}

The equals method is described in the API document. For any non-null reference value x, x.equals(null) returns false. Document of class Object

Character literal identity

An instance of String only describes a string, and true is returned when different references are compared with == and the same character literal is used. This is a mechanism for reducing the processing load called the constant pool.```java String a = “test”; String b = “test”; System.out.print(a == b); //reference is different, but is displayed as true

The constant pool is valid only when using a string literal, and each time you create a new instance using the new operator, an instance is created and has a different reference. In case of equals method, check that only the character strings are the same.

```java
String a = new String("test");
String b = "text";
System.out.print(a == b); // becomes false
Syttem.out.println(a.equals(b)); // becomes true

if statement

The syntax of the if statement is as follows.

if (conditional expression) {
  // write the process when the condition is met
}

If {} of if statement is omitted, only the first sentence is processed by if syntax. When I run the following code, only b is printed.

public class Main{
    public static void main(String[] args){
        int a = 1;
        int b = 2;
        if (a = b)
        System.out.println("a")
        System.out.println("b")
    }
}

if-else statement

The syntax of the if-else statement is as follows.

if (conditional expression) {
    // Processing when the condition is matched
} else {
    // Processing when the conditions are not met
}

if-else if-else statement

if-else The syntax of the if-else statement is as follows. As a caveat, if you break the line between else and if, the syntax becomes that if statement is included in else statement.

if (conditional expression A) {
    //Process when condition A matches
} else if (conditional expression B) {
    // Processing when the conditional expression B is matched
} else if (conditional expression C) {
    // Processing when the conditional expression C is matched
} else {
//Processing when all conditions are not met
}

switch statement

The syntax of the switch statement is as follows

switch (conditional expression) {
    case value: processing
        break;
    case value: processing
        break;
    default: processing
        break;
}

There is a limit to the type of the value that can be returned by the conditional expression. The types that can be returned are limited to the integer type below int type and wrapper class, character and string, and enumeration type. Double, float, boolean, etc. cannot be returned.

  • char
  • byte
  • short
  • int
  • Character
  • Byte
  • Integer
  • String
  • enum

The value that can be used for case value is also limited, as follows

  • The same type or compatible type as the value returned by the conditional expression
  • Is a constant or can be determined at compile time (final variables and literals)
  • not null

After processing that matches the case value, write a break and exit the processing. If there is no break, all processing is executed until the next break appears. In the following process, a, b, c, d are displayed

int num = 1;
switch (num) {
    case(1): System.out.println("a")
    case(2): System.out.println("b")
    case(3): System.out.println("c")
    default: System.out.println("d")
}

Ternary operator

The ternary operator is an operator that changes the returned value depending on whether the condition is met. The syntax is as follows.

Boolean expression ?expression for true :expression for false

Ternary operators are hard to see when nested, but harder to write on a single line. The correct syntax is that if? And: appear alternately and end with :.

Variable = expression A? Expression when expression A is true
: Expression B? Expression when expression B is true
    : Expression C? Expression when expression C is true
    : Process when all are false

Variable = Expression A? Expression when expression A is true: Expression B? Expression when expression B is true: Expression C? Expression when expression C is true: Processing when all are false

Array

Creating an array instance

To use an array, you need to declare an instance of the array using the new keyword. The array has the following features.

  • Can only use values of the same type or compatible types
  • The number of elements that can be handled is determined when the instance is created. The number of elements cannot be changed later.
int[] array = new int[4]

The println method prints the value passed to the argument on the console. When an object reference is passed to this method, the toString method of the referenced instance is called and the result is displayed. If you pass an array reference to this method, it will call the toString method of the array instance and return a value that combines the class name with a hash code to uniquely identify the instance.

array declaration

Array type variables are declared using []. [] can be written not only after the data type but also after the variable name.

int[] array;
int array2[];

The array can handle multi-dimensional array such as 2-dimensional array and 3-dimensional array, and it is not necessary to describe the positions of [] at once.

int[][] array2; // two-dimensional array
int[] array22[]; // 2D array

int array3[][][]; //3-dimensional array
int[][] array33[]; // 3D array

An array causes a compilation error if the number of elements is defined when an instance is created and the number of elements is specified when the array variable is declared.

int[2] array; // compilation error

How to create an array instance

There are the following rules when creating an array instance.

  • Specify the number of elements that can be handled.
  • The number of elements is specified as an int type, not as a floating point number.
  • The number of elements in the first dimension cannot be omitted when creating an instance of a two-dimensional array. The number of elements in the second dimension can be described separately
  • Be sure to match the number of dimensions between variables and instances.

Compile error example

int[] array = new int[]; // number of elements is not specified
int[] array = new int[1.5]; // floating point
int[][] array = new int[][3]; //The number of elements in the first dimension is not specified

OK example

int[][] array = new int[3][];
array[0] = new int[2];
array[1] = new int[2];
array[2] = new int[2];
// Declare the number of elements in the second dimension separately

Array instance and element values

After creating the array instance, it is necessary to assign the value to the element.

int[] array = new int[3]
array[0] = 10;
array[1] = 15;
array[2] = 20;

The default values of array elements are determined as follows

Type default value
integer type 0
Floating point type 0.0
Boolean type false
Character type \u0000
Object type null

You can also use initialization operators to initialize array elements.

int[] array = {10,20,30};

array elements

The number of elements is specified when the instance of the array is created, and the array instance has variables for the specified number of elements inside. Each variable is accessed using a subscript. If you assign null to an element, that element will never reference anything.

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        String[] array = {"A","B","C"};
        array[0] = null;
        for(String str: array){
            System.out.print(str); // is displayed as nullBC
        }
    }
}

Array instance creation and initialization, array type variable declaration and reference assignment

Generally, an initialization operator is used to create and initialize an array instance, declare an array type variable, and assign a reference.

int[] array = {1,2};
// the following code has the same meaning
int[] array = new int[]{1,2};

Normally, when creating an array instance using new, specify the number of elements in [], but if you use the initialization operator, do not specify the number of elements in []. ..

Generating an array instance with 0 elements is meaningless, but it is not syntactically wrong.

int[] array = {};
int[] array = new int[0];

In case of multi-dimensional array, write the initialization operators in the initialization operator separated by commas.

int[][] array = {{1,2,},{3,4} };

If the number of dimensions of the variable does not match the number of dimensions of the reference destination, a compile error occurs.

int[][] array = new int[]{}; // compilation error
int[][] array = new int[][]{}; // no error

In addition, if you write only the initialization operator without using new, no compilation error will occur. This is because the initialization operator automatically calculates the required number of dimensions and performs the necessary initialization.

int[][] array = {}; // no compile error

The function of the initialization operator that automatically calculates the required number of dimensions can be used only at the same time as the variable declaration. When the variable declaration and the instance generation of the array are described separately on two lines, the initialization operator cannot be used, and when used, the number of dimensions must be explicitly described.

int[][] array;
array = new int[][]{}; // no compilation error

int[] array2;
array2 = {1,2}; // compilation error

Multidimensional array

In a multidimensional array, it is not necessary to make the number of elements in the second and subsequent arrays uniform. Arrays with different number of elements from the second dimension onward are called asymmetric multidimensional arraysThe code below does not cause a compile error although the number of elements in the second dimension is different. However, at the point where the number of elements is counted by tmp.length, the number of null elements that do not have a reference cannot be counted, so an exception is thrown at runtime (runtime error)

public class Main{
    public static void main(String[] args){
        string[][] array = {{"a", "i"}, null, {"uu", "e", "o"} };
        int total = 0;
        for (String[] tmp :array) {
            total += tmp.length;
        }
        System.out.println(total);
    }
}

Behavior of instances of classes and interfaces that have an inheritance/realization relationship

When a class has an inheritance relationship, an array type variable of superclass type can handle a set of subclass instances. The array type variable that handles only Object type and the array instance that handles only String are different types, but since the String class inherits the Object class, the following code can be compiled and executed without problems.

Object[] obj = {"A", "B", "C"};

These relationships can also be applied between interfaces and implementation classes, abstract classes and concrete classes that inherit from them. If there is an interface called A and there is a class called B that implements it, a reference to an array instance that handles only B can be assigned to an array type variable that handles only A.

public interface A {}
public class B implements A {}

A[] array = new B[]{ new B(), new B() };

Array copy (clone)

You can use the clone method to generate a copy of the array. This is just a process of creating a copy, and the reference destination is different.

int[] arrayA = {1,2,3,4};
int[] arrayB = arrayA.clone();
System.out.println(arrayA == arrayB); //Displayed as false because the reference destination is different

When cloning a multi-dimensional array, the first-dimensional instance is different, but the second-dimensional and subsequent instances are shared.

Array copy

To cut out and copy only an arbitrary part of the array, use the arraycopy method of System class. arraycopy method takes 5 arguments

Argument Description
First argument Copy source array
Second argument Which position in the copy source to start copying (starting from 0)
Third argument Copy destination array
Fourth argument From which position to start copying (starting from 0)
Fifth argument How many elements to copy from the position of the second argument
char[] arrayA = {'a','b','c','d','e'};
char[] arrayB = {'f','g','h','i','j'};
System.arraycopy(arrayA,1,arrayB,1,3);
System.out.println(arrayB); //fbcdj is displayed

Loop structure

Java has the following four iteration syntaxes.

  • while statement
  • do-while statement
  • for statement
  • Extended for statement

while statement

The while statement is a syntax for repeating the process while the conditional expression returns true. The conditional expression must always return a boolean value. Only one expression can be described as the repeat condition of the while statement. If literal:true is described in the conditional expression, it will be an infinite loop, and if literal:false is described, it will never be executed.

while (conditional expression) {
  // iteration
}

do-while statement

The do-while statement executes the iterative process and then performs the condition judgment. Therefore, it is executed at least once regardless of the conditions. A; is required after the do-while conditional expression. Do not put () after do

do {
  // iteration
} while (conditional expression);

I am adding as needed.