Java fun sharing: try & finally

Consider the following four test methods, and what do they output?

public class Test {

    public static void main(String\[\] args) {

        System.out.println(test1());

        System.out.println(test2());

        System.out.println(test3());

        System.out.println(test4());

    }

    private static int test1() {

        int i = 1;
        try {
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            i = 0;
        }

        return i;

    }

    private static int test2() {

        int i = 1;
        try {
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            i = 0;
            return i;
        }

    }

    private static User test3() {

        User user = new User("u1");
        try {
            return user;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            user = new User("u2");
        }

        return null;

    }

    private static User test4() {

        User user = new User("u1");
        try {
            return user;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            user.setName("u2");
        }

        return null;

    }

}

public class User {

    public User(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

}

The answer is as follows:

1

0

u1

u2

conclusion

1. No matter try,finally will execute;

2. return in try, the result will be saved before finally executing. Even if there is modification in finally, the value saved in try will prevail. However, if it is a reference type, the modified property will be subject to the modified property;

3. If try/finally has return, return the return in finally directly.

Recommend to my blog to read more:

1.Java JVM, collection, multithreading, new features series

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Latest interview questions of Java, backend, architecture, Alibaba and other large factories

Feel good, don't forget to like + forward!

Tags: Java Spring jvm Maven

Posted on Fri, 08 May 2020 10:31:52 -0400 by fredyap1234