What does the return keyword do in a void method in Java?

后端 未结 7 1571
Happy的楠姐
Happy的楠姐 2020-11-28 21:34

I\'m looking at a path finding tutorial and I noticed a return statement inside a void method (class PathTest, line 126):



        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 22:22

    See this example, you want to add to the list conditionally. Without the word "return", all ifs will be executed and add to the ArrayList!

        Arraylist list =  new ArrayList<>();
    
        public void addingToTheList() {
    
        if(isSunday()) {
            list.add("Pray today")
            return;
        }
    
        if(isMonday()) {
            list.add("Work today"
            return;
        }
    
        if(isTuesday()) {
            list.add("Tr today")
            return;
        }
    }
    

提交回复
热议问题