Debuting the Debugger3:03 with Ben Deitch
In this video we'll see how to use the debugger to investigate our code while it's running!
When writing a program, 0:00 figuring out what's going on behind the scenes can be pretty difficult. 0:02 One way to figure out what's going on is to use print statements like we have here. 0:06 If you're not sure what some variable is set to, you can just print it out and 0:11 investigate. 0:16 Using print statements is a great way to debug an app. 0:17 However, IntelliJ also comes with a debugger 0:20 which lets us walk through our code one step at a time. 0:24 So instead of running our app like we have been, let's try using the debugger. 0:28 But first, before we use the debugger, we need to set a breakpoint in our code. 0:33 A breakpoint is a point in our code where the debugger will break out of normal 0:39 computation and then wait for instructions from us on how to proceed. 0:44 It's a stopping point where we can take our time to look at the current state of 0:49 our app. 0:53 Then, if we want, we can continue processing the code step by step or 0:54 resume running the app. 0:59 Let's set our first breakpoint on the first line of the main method. 1:01 We can add breakpoints in a few different ways. 1:06 First, let's click on the line we want to add a breakpoint, 1:09 then click on the Run menu, and select Toggle Line Breakpoint. 1:14 Notice that a little red circle representing the breakpoint appears 1:20 to the left of this line of code, this area is known as the gutter. 1:25 To delete the breakpoint, make sure that the line is still selected and 1:31 then select Run > Toggle Line Breakpoint to toggle it back off. 1:36 We can also click in the gutter next to a line of code to add or 1:41 delete a breakpoint, like this. 1:45 We can add breakpoints all over our code to stop anywhere we like. 1:48 But let's stop with just this one. 1:54 Now to run our app with the debugger, we want to use the Debug button at the top, 1:57 which is just to the right of the Run button, and looks kind of like a bug. 2:01 Click it, and once the program starts it should stop at this breakpoint, 2:08 and open the debug perspective. 2:14 We now have a new debug view at the bottom of our screen. 2:17 And the line where we inserted our breakpoint is now highlighted in blue to 2:21 show that this is where the program stopped. 2:26 Our program is in a paused state at this point. 2:29 And while it's paused, we can look at all sorts of things about our code. 2:32 Right now, there's not much to look at. 2:37 This line hasn't been run yet, so the only variable we have is the args array. 2:40 But if we hover over it, or look to the right, or even look to the bottom, 2:46 we can see pretty clearly that args is just an empty array. 2:52 In the next video, we'll step through our code one line at a time and 2:57 get more comfortable with the debugger. 3:01
You need to sign up for Treehouse in order to download course files.Sign up