Java tips, tips

Overview

Just try to spell it out as it is. I don't know if it will be useful. Also, I don't think it's necessarily Java-specific.

Contents

Multiple assignment

You can assign the same value to multiple variables.

int x, y;
x = y = 10;
System.out.println(x); // 10
System.out.println(y); // 10

This seems to be interpreted as follows. 10 is assigned to y, but in Java, the value of the assignment expression is also returned, so it means that the entire evaluation value of (y = 10) is assigned to x.

x = (y = 10);

How to write the main method

I think that the main method is generally written as follows.

public static void main(String[] args) {
    System.out.println("Hello world!");
}

If it is Java 5 or later, you can write as follows.

public static void main(String... args) {
    System.out.println("Hello world!");
}

The only difference is String [] or String .... The former is an array and the latter is a variadic argument, but the main method seems to be either.

Just a scope

A new scope is created by using an if statement or for statement, but you can also create a simple scope that does not perform conditional branching or loops.

{
    int x = 10;
    System.out.println(x);  // 10
}

{
    int x = 100;
    System.out.println(x); // 100
}

// System.out.println(x); //Compile error

x is defined twice, but it doesn't cause a compile error because it has a different scope. Also, since the scope of x is only the range enclosed by the brace, it is a compile error if you try to refer to x outside the brace.

Implementation of HashSet

HashSet is a class that just wraps HashMap as an implementation. (* This is a detailed implementation, so it may change in the future.)

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

AbstractStringBuilder Although StringBuilder and StringBuffer are written in JavaDoc as if they were subclasses directly under the Object class, they are actually subclasses of ʻAbstractStringBuilder. ʻAbstractStringBuilder is package private (not a public API) and may not be written in JavaDoc. (* This is a detailed implementation, so it may change in the future.)

public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, Comparable<StringBuilder>, CharSequence
{
//Omission
 public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, Comparable<StringBuffer>, CharSequence
{
//Omission

Define a method within a method

Normally, you cannot define a method inside a method in Java. But you can do that with the var introduced in Java 10. (I wrote it in another article)

Main.java


public class Main {
    public static void main(String[] args) {
        // func.capitalize()Can be called with
        //func is a local variable and cannot be called from outside this method
        var func = new Object() {
            private String capitalize(String s) {
                return s.substring(0, 1).toUpperCase() + s.substring(1, s.length()).toLowerCase();
            }
        };

        System.out.println(func.capitalize("tokyo")); // => Tokyo
        System.out.println(func.capitalize("TOKYO")); // => Tokyo
    }
}

Run Java source code without compilation

I wrote this in another article, but since Java 11, you can execute it by specifying the source file with the java command without using javac. It may be useful for a little operation check. Well, I don't think it really runs without compilation, but it's compiling behind the scenes.

Embed processing in method of existing class

In Java, you can use anonymous classes to embed processing in existing methods.

List<String> list = new ArrayList<>() {
    @Override
    public boolean add(String s) {
        System.out.println("add called. arg: " + s);
        return super.add(s);
    }
};
list.add("hello"); // add called. arg: hello
list.add("world"); // add called. arg: world
System.out.println(list); // [hello, world]

Use ʻinstanceof for null`

You can use ʻinstanceof for null`.

System.out.println(null instanceof Object); // false

Of course, it doesn't become true, but I think the point of interest is that NullPointerException is not thrown. The same result is obtained for variables to which null is assigned, so it is not necessary to check null before ʻinstanceof`.

throw`` null

If the exception type variable contains null, throw will throw NullPointerException regardless of the variable type.

RuntimeException e = null;
throw e; // NullPointerException

Cast null

It doesn't make much sense, but I can't throw any exceptions for the time being.

Object obj = null;
String str = (String)obj;
System.out.println(str); // null

Type determination that does not allow subclasses

If you use ʻinstanceof, it will be true` even if the instance type is a subclass of the specified class.

System.out.println("str" instanceof Object); // true

For subclasses, if you want to make it false, you can compare the Class types with ʻequals` as shown below.

System.out.println(new Object().getClass().equals(Object.class)); // true
System.out.println("str".getClass().equals(Object.class)); // false

Arrays are not type safe

Arrays are assignment compatible with arrays of a type and arrays of subclasses of that type. Therefore, the following code will be compiled and an error will occur at runtime.

Object[] array = new String[3];
array[0] = new Integer(10); // ArrayStoreException

If it is a List using generics, the above problem does not occur because a compile error occurs.

List<Object> list = new ArrayList<String>(); // incompatible types: ArrayList<String> cannot be converted to List<Object>

Detect overflow

If an overflow occurs during the calculation, the calculation result will be incorrect without any error. There is a utility method in the Math class that throws an exception when an overflow occurs, so you can detect the overflow by catching the exception.

System.out.println(Integer.MAX_VALUE + 1); // -2147483648
Math.addExact(Integer.MAX_VALUE, 1); // ArithmeticException: integer overflow

Well, I feel like I should use BigInteger from the beginning.

At the end

I would be happy if there is any item that can be used as a reference. If you come up with something else, you may or may not add it.

Recommended Posts

Java tips, tips
Java Tips
Java code TIPS
Play Framework2.5 (Java) Tips
Java
Java
Java tips --StaticUtility class modifier
Java tips --Spring execution Summary
[Java] Tips for writing source
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
Java array
Studying Java ―― 9
Java scratch scratch
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
Java High Level REST Client Tips
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes