I tried to summarize what was asked at the site-java edition-

Why did you decide to write this article

It's been 5 months since I joined the current site, In conversations with people in the field, there are many things like "why is this happening" and "what is this description doing?" Sometimes I looked it up together and said "I see!".

It's not good to end it on the spot, so I wanted to leave it as a memorandum for myself.

If you have similar questions, I hope you find this article useful.

Main subject

Why can I assign a primitive type value to a wrapper class?

Question

One day conversation

Mr. A "What is this(int)?" I "** cast ** is the one. ** will change the type **." Mr. A "Thank you very much." ~ A few days later ~ Mr. A "I have a question, is it possible to assign to an Integer type variable ** without casting an int type value?" I "I can do it. ** Auto boxing ** or ** Unboxing **, it seems that it was a function with that name ..."

public class Sample {

  public void sample(long l) {
    int i = (int) l;
    Integer integer = i;
    log.info("int=[{}], Integer=[{}]", i, integer);
  }
}

answer

java has a function that implicitly performs type conversion when assigning from a primitive type (int) to a wrapper class (Integer), which is called autoboxing **. Contrary to autoboxing, ** the function that implicitly converts the type from the wrapper class (Integer) to the primitive type (int) is called unboxing **. Be careful with unboxing </ font>, ** Wrapper class can handle null because it is an object, but when I try to assign it to a primitive type, I get a NullPointerException **. Let's check the value in advance.

  • List of primitive types and wrapper classes
Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short

There is a () after the try, what is this doing?

Question

One day conversation

Mr. A "I think there is a ** try-catch statement **, but what is the argument after this try?" I "What's that ... Let's find out ..."

public void Sample {

  public void sample(Strin url) {
    try (BufferedReader br = new BufferedReader(new FileReader(url))) {
      String line = null;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();

    } catch (IOException e) {
      e.printStackTrace();

    }
  }
}

answer

This is a description called ** try-with-resources syntax ** that can be used in javaSE7 and later. Before javaSE6, it was necessary to describe the resource to be close () whenever accessing a file or database. ** Try-with-resources will automatically close () resources when exiting the try clause **.

  • Execution order (execution from top to bottom)
  • try-with-resources part (try () part)
  • In the try clause
  • The close () method of try-with-resources
  • In the catch clause
  • finally in the clause
  • Other notes, etc.
  • If an exception occurs in the try clause, and an exception also occurs in close (), ** the exception that occurred in the try clause is thrown **.
  • If you want to use the exception raised by close (), you can get an array of Throwables with ** ʻex.getSuppressed ()` **.
  • The execution order of close () is the reverse order in which the resources are declared.
  • If you write the finally clause, the finally clause will be executed. ** However, exceptions thrown by try-with-resources cannot be used **.
  • If you want to use your own resources, you can do so by implementing the ʻAutoClosable interface`.

Why do some exceptions require throws and some do not?

Question

One day conversation

Mr. A "I'd like to ask about this source, what is ** throws ?" I " I'm just explicitly writing the exceptions that the method might throw ** Isn't it **? ** The compilation will pass without it ...? **" Mr. A "I get angry when I erase ** throws AAAException, right? ... Why?" I "... why? ** I don't have to write a BBBException ** ..."

python


public class Sample {

  public Object sample(String url, Request request) throws AAAException {

    XXXClient client = new XXXClient();

    try {
      return client.request(url, reuqest);

    } catch (AAAException ex) {
      log.error("Some kind of log", ex);
      throw ex;

    } catch (BBBException ex) {
      log.error("Some kind of log", ex);
      throw ex;

    }
  }
}

answer

There are two types of exceptions in Java called ** checked exceptions (checked exceptions) ** and ** unchecked exceptions (unchecked exceptions) **. (Strictly speaking, there is ** error **, but it is omitted here) ** Need throws for methods that can raise checked exceptions **. In this example, ** AAAException was a checked exception, so throws were required, and BBBException was an unchecked exception, so it was not necessary to add throws **.

  • Inspection exception

  • Exception that is thrown even if you write it correctly and behave as expected (≒ nothing can be done in the implementation program)

  • This is a predictable error, so you need to force the caller to handle it (throws required)

  • Subclass of java.lang.Exception

  • IOException… I / O error

  • FileNotFoundException… File not found

  • SQLException ... SQL error ... etc.

  • It seems to be a concept that only java has </ font>

  • Unchecked exception

  • Exceptions thrown for various reasons (≒ can be avoided by the implementation program)

  • Since it is difficult to predict all the patterns that can occur, the caller is not forced to handle and the execution is stopped.

  • A subclass of java.lang.RuntimeException

  • NullPointerException… Value is NULL

  • NumberFormatException… Value cannot be converted to a number

  • ArrayIndexOutOfRangeException… It is out of the range of the list or array …… etc

  • Other languages basically have only unchecked exceptions </ font>

  • Simple class diagram 無題.png

Finally

Outputting to someone is an opportunity to see if you really understand yourself. When I re-examined it, my understanding deepened and I learned a lot. We will continue to update it from time to time!

Until the end Thank you for reading!

Recommended Posts