Summary of knowledge required to pass Java SE8 Silver

Introduction

I needed to use Java at work, and I decided to take Java Silver for systematic learning, so I will briefly summarize what I learned there by keyword.

Java basics

Class declaration

Class declarations consist of fields and methods. The constructor is part of the method

Purpose of the package

Package declaration

Class import

Package and access control

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

Static import format

Originally, static fields and methods need to be specified in the class name.field name (method name) format. Static import to make them abbreviated only by name

import static package name.name of the class.Field name (method name)

Do not add parentheses or arguments to method names in method static import declarations

Static import specifications

main method

Multiple methods can be defined in the class, but the methods and entry point descriptions and rules for starting processing are as follows.

public static void main(String[] args) {

}

java command

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

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

Manipulating Java data types

Java data type

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

Data type value
boolean true,false
char 16-bit Unicode characters
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

Literals are values described in the source code. In Java, integer values are handled as int type, double type for floating point numbers, boolean type for boolean values, and char type for characters. Will be.

Suffix, prefix

By adding a suffix or prefix, the data type can be specified and notation other than decimal numbers is possible.

・ Example of suffix long type ・ ・ ・ L, float type ・ ・ ・ f

・ Example of prefix 0 ・ ・ ・ octadecimal 0x ・ ・ ・ hexadecimal 0b ・ ・ ・ binary number

underscore

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

Character literals, string literals

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

Character literals are enclosed in single quotes Enclose string literals in double quotes

Identifier naming convention

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

null null is a literal to represent that a variable of reference type does not hold a reference. Different from the empty string ("")

How to call a method

How to call the method is as follows

Signature

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

Garbage collection

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

Use of operators and decision structures

Assignment operator

The types and meanings of assignment operators are as follows

operator Example of use meaning
= a = 10; Substitute 10 for a
+= a += 10 a to a+Substitute 10
-= a -= 10 a to a-Substitute 10
*= a *= 10 a to a*Substitute 10
/= a /= 10 a to a/Substitute 10

Minus operator

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

Type conversion

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

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

Numeric literals of integers are basically int type, and in the case of floating point, double type, so if you put that value in a small variable, you have to cast it 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 the range, a compile error does not occur.

・ 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, if it is prefaced, it is incremented (decremented) and then assigned, and if it is postfixed, it is 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 operator

A relational operator is an operator that compares left and right values 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 a is greater than b
>= a >= b true if a is greater than or equal to b
instanceof a instanceof b true if a is an instance of the same class as b or a subclass of b

,> = Can only compare large and small numbers

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 either side is true
|| a>10 || b>10 True if either expression on either side is true
! !a>0 False if the expression is true,true if false

&&、||Is called a shortcut operator, and if the expression on the left side is false, false is fixed as a whole, so the expression on the right side is not evaluated. If the expression on the right side contains processing that changes the value, such as incrementing,&Or|The result is different from.

Operator precedence

Operators have priorities, and if they have the same priority, items with 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 (Mold)
4 * / %
5 + -
6 << >> >>>
7 < > <= >= instanceof
8 == !=
9 &
10 ^
11
12 &&
13 ?:
14 = += *= /= %= &= ^= != <<= >>= >>>=

Identity, equivalence

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

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

Equivalence is the property that instances are different but have the same value. Use the equals method to see if they are equivalent. The eauals method of the Object class takes an Object type as an argument and returns a boolean type 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 documentation. For non-null reference values x, x.equals (null) returns false. Document of class Object

Character literal identity

An instance of String only describes a string, and when comparing different references with ==, true is returned if the same character literal is used. This is a mechanism called a constant pool to reduce the processing load.

String a = "test";
String b = "test";
System.out.print(a == b); //The reference is different, but it is displayed as true

Constant pools are only valid when using string literals, and each time you create a new instance using the new operator, the instance is created and has a different reference. In the case of the equals method, only the character string is the same, but it is confirmed.

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

if statement

The syntax of the if statement is as follows.

if (Conditional expression) {
  //Write the process when the conditions are met
}

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

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 conditions are met
} else {
    //Processing when the conditions are not met
}

if-else if-else statement

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

if (Conditional expression A) {
    //Processing when conditional expression A is met
} else if (Conditional expression B){
    //Processing when conditional expression B is matched
} else if (Conditional expression C) {
    //Processing when 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 types of values that conditional expressions can return, and the types that can be returned are limited to integer types and wrapper classes of int type and below, characters and character strings, and enumeration types. Double, float, boolean, etc. cannot be returned.

The values that can be used for the case value are also limited, as follows

After the process that matches the case value, describe a break and exit the process, but if there is no break, all the processes are 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 value to be returned depending on whether the condition is met, and the syntax is as follows.

Boolean expression? Expression for true: expression for false

Ternary operators are hard to see when nested, but hard to see when written on one line. As for the syntax,? And: appear alternately, and if it ends with: at the end, the correct syntax

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

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

Array

Array instance generation

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

int[] array = new int[4]

The println method is a method that prints the value passed as an argument to the console. If you pass an object reference to this method, it will call the toString method of the referenced instance and display the result. Passing an array reference to this method calls the array instance's toString method and returns a combination of the class name and the hash code to uniquely identify the instance.

Array declaration

Array variables are declared using []. [] Can be written after the variable name as well as after the data type.

int[] array;
int array2[];

Arrays can handle multidimensional arrays such as two-dimensional arrays and three-dimensional arrays, and the positions of [] do not need to be described together at once.

int[][] array2;  //Two-dimensional array
int[] array22[]; //A two-dimensional array

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

For an array, if you define the number of elements when creating an instance and specify the number of elements when declaring variables in the array, a compile error will occur.

int[2] array; //Compile error

How to create an array instance

When creating an array instance, there are the following rules.

Examples of compilation errors

int[] array = new int[]; //No number of elements 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 an array instance, you need to assign a value to the element.

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

The default values of the elements of the array are determined as follows

Mold Default value
Integer type 0
Floating point type 0.0
Authenticity type false
Character type ¥u0000
Object type null

You can also use the initialization operator to initialize the elements of an array.

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

Array elements

The number of elements is specified when the array is instantiated, 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 not be referenced anywhere.

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); //Displayed as nullBC
        }
    }
}

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

It is common to use the initialization operator to create and initialize an array instance, declare an array type variable, and assign a reference.

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

Normally, when instantiating an array using new, specify the number of elements in [], but when using the initialization operator, do not specify the number of elements in []. ..

Creating an array instance with zero elements doesn't make sense, but it's not grammatically wrong.

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

For multidimensional arrays, describe the initialization operators inside the initialization operators, separated by commas.

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

If the number of dimensions of the variable and the number of dimensions of the reference destination do not match, a compile error will occur.

int[][] array = new int[]{}; //Compile error
int[][] array = new int[][]{}; //No error

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

int[][] array = {}; //No compilation error

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

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

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

Multidimensional array

In a multidimensional array, it is not necessary to equalize the number of elements in the array after the second dimension. Arrays with different numbers of elements after the second dimension are called asymmetric multidimensional arrays. The code below has a different number of elements in the second dimension, but does not result in a compile error. However, when counting the number of elements in tmp.length, it is not possible to count the number of null elements that do not have a reference, so an exception is thrown at runtime (runtime error).

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

Behavior of instances of classes and interfaces that are inherited / realized

When a class has an inheritance relationship, a superclass type array variable can handle a set of subclass instances. Array type variables that handle only Object type and array instances that handle only String have different types, but since the String class inherits the Object class, the following code can be compiled and executed without any problem.

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

These relationships can also be applied between interfaces and realization classes, abstract classes and their inherited concrete classes. If you have an interface called A and a class called B that implements it, you can assign a reference to an array instance that only handles B to an array type variable that only handles A.

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

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

Array clone (clone)

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

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

When cloning a multidimensional array, the instances in the first dimension are different, but the instances in the second and subsequent dimensions are shared.

Array copy

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

argument Description
First argument Array to copy from
Second argument From which position in the copy source to start copying(0 beginning)
Third argument Copy destination array
Fourth argument From which position in the copy destination to start copying(0 beginning)
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 iterative syntaxes.

while statement

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

while (Conditional expression) {
  //Iterative processing
}

do-while statement

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

do {
  //Iterative processing
}while (conditional expression);

I am adding it from time to time.

Recommended Posts

Summary of knowledge required to pass Java SE8 Silver
Java SE8 Silver ~ The Road to Pass ~
Java SE8 Silver Pass Experience
[Java Silver] Summary of points related to lambda expressions
How to study Java Silver SE 8
Summary of [Java silver study] package
Road to Java SE 11 Silver acquisition
How to pass Oracle Java Silver
[Java Silver] Summary of access modifier points
Java knowledge summary
[java] Summary of how to handle char
Java SE 8 Silver (Java SE 8 Programmer I) Pass Note
[Java] [Maven3] Summary of how to use Maven3
[java] Summary of how to handle character strings
[Java] Summary of how to abbreviate lambda expressions
[Java SE 11 Silver] Arrays class method summary [Java beginner]
[Qualification Exam] Java SE 8 Silver Learning Method Summary
Passed Java SE8 Silver
Summary of Java support 2018
Aiming to acquire Java Oracle Silver, point memo (pass)
Summary of Java communication API (1) How to use Socket
Introduction to Java for beginners Basic knowledge of Java language ①
Summary of Java communication API (3) How to use SocketChannel
Summary of Java communication API (2) How to use HttpUrlConnection
Summary of how to implement default arguments in Java
Story of passing Java Silver SE8 (Oracle Certified Java Programmer, Silver SE 8)
A study method for inexperienced people to pass Java SE 8 Silver in one month
[Experience] Passed Java SE 8 Silver
[Java] Summary of regular expressions
[Java] Summary of operators (operator)
Summary of Java language basics
[Java] Summary of for statements
Summary of Java Math class
Knowledge required to display tweets
[Java] Summary of control syntax
Summary of java error processing
[Java] Summary of design patterns
[Java] Summary of mathematical operations
[Java Silver] Things to be aware of regarding switch statements
Time taken to acquire Java SE11 Silver, teaching materials used
[For beginners] Summary of java constructor
[Note] Java Silver SE8 qualification acquired
[Java] Input to stdin of Process
Java Silver Repo (Failure & Pass Experience)
Java "pass by reference" problem summary
Summary of object-oriented programming using Java
Diary for Java SE 8 Silver qualification
[Basic knowledge of Java] Scope of variables
[Qualification] Java Silver SE11 Passing Experience
What you did to get the Oracle Certified Java Programmer, Silver SE 8
I was able to obtain OCJP Silver SE 11 safely, so a summary
Summary of in-house newcomer study session [Java]
How to make a Java calendar Summary
How to use submit method (Java Silver)
Oracle Certified Java Silver SE 8 Passing Experience
Summary of how to write annotation arguments
[Java] Personal summary of conditional statements (basic)
Knowledge required to bring Rails apps to AWS
Summary of going to JJUG CCC 2019 Spring
Inexperienced learning methods to get Java Silver 11
[Basic knowledge of Java] About type conversion