Stack trace

Java Syntax
Level 9 , Lesson 1
Available
Stack trace - 1

"Hi! Today I'll tell you what a stack trace is. But first I need to tell you what a stack is."

"Imagine a pile of papers – directives for a certain employee. You can put a new task on top of the pile, or you can take a task from the top. This means that tasks won't be executed in the order they were received. The task placed on the pile most recently will be the first to be executed. Structuring the elements of a collection this way forms a stack."

"Java has a special collection for that – Stack. It's a collection that has methods to 'add an element' and 'take (get) an element'. As you may have guessed, the element that was added last will be the first to be taken."

"Sounds rather straightforward."

"Great. Now I'll explain what a stack trace is."

"Imagine that in a Java program method A called method B, which called method C, which in turn called method D. To exit method B, we must first exit method C, and to do that – we must first exit method D. This behavior resembles a stack."

"Why do you say it resembles it?"

"To get to some task in the middle of our stack of papers, for example, you first need to execute all the tasks lying on top of it."

"There's some similarity, but I'm not sure I understand everything correctly."

"Look. A stack is a set of elements. Like pieces of paper in a pile. To take the third piece of paper from the top, you first need to take the second, and for that, you need to take the first. You can always put and take pieces of paper, but you always have to take the top paper first."

"The same is true for function calls. Method A calls method B, which calls method C. To exit A, you must first exit B, and to do that, you need to exit C."

"Wait. If I understand what you're saying, the entire concept of a stack boils down to 'take the piece of paper that was added last' and 'you can only exit the method you most recently entered'. Is that accurate?"

"Yes. The sequence of function calls is known as the ‘call stack' or simply the ‘stack'. The last function called is the first function to end. Let's dig into an example."

Get and display the current call stack:
public class ExceptionExample
{
  public static void main(String[] args)
  {
    method1();
  }

  public static void method1()
  {
    method2();
  }

  public static void method2()
  {
    method3();
  }

  public static void method3()
  {
     StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    for (StackTraceElement element : stackTraceElements)
    {
       System.out.println(element.getMethodName());
    }
  }
}
Result:
getStackTrace
method3
method2
method1
main
9
Task
New Java Syntax, level 9, lesson 1
Locked
Integer literals
Four public fields, corresponding to the four integer types, are declared in the Solution class. When declared, these fields are initialized with various values stored in integer literals. But the program doesn't compile, and you need to fix it. To do this, make the fewest possible changes to the va

"OK. I get everything about function calls. But what is this StackTraceElement?"

"The Java Machine keeps track of all function calls. For that, it has a special collection – the stack. When one function calls another, the Java Machine puts a new StackTraceElement object onto the stack. When a function finishes, that element is removed from the stack. This means that the stack always stores up-to-date information about the current state of the 'stack of function calls'."

"Each StackTraceElement object contains information about the called method. In particular, you can get the method name using the getMethodName method."

"You can see how this works in the example above:

1) We get the call stack.

2) We use a for-each loop to go through it. I hope you haven't forgotten what that is.

3) We output the method names to System.out."

"Fascinating! And not too complicated either. Thank you, Rishi!"

9
Task
New Java Syntax, level 9, lesson 1
Locked
Floating point literals
Seven public fields are declared and initialized in the Solution class. They are initialized with various values stored in floating point literals. But the program doesn't compile, and you need to fix it. To do this, change the field types so they match the values. Do not change the field names or v
9
Task
New Java Syntax, level 9, lesson 1
Locked
String literals
A public string field is declared and initialized in the Solution class. But the string is too long and difficult to read. For better readability, you need to split it into 5 substrings and concatenate them with the "+" (string concatenation) operator, like this: - first line: "Always write code as
9
Task
New Java Syntax, level 9, lesson 1
Locked
Character literals
Four public character fields are declared in the Solution class. Some values have been assigned to them. The program doesn't compile. You need to fix this without changing the character values. All the fields are static — this is necessary in order to access them in the main() method. You can see th
Comments (29)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
OBINNA Level 16, Texas, United States
2 June 2021
In other words.. STACK - FILO (First In Last Out) OR - LIFO (Last In First Out)
Naughtless Level 41, Olympus Mons, Mars
28 May 2021
If you come from an economic Background, Stack is IDENTICAL in principle to LIFO (Last In First Out).
Russell Level 9, Galmpton, Brixham , United Kingdom
28 January 2021
Yeah im sorry but this lesson made me give up for months. In the end I had to do the excercises by copy pasting. They are not inas intuitive as previous exercises. Also I was not taught this :

return Thread.currentThread().getStackTrace()[2].getMethodName();
this line of code is not self-explanatory for me. Stack overload results from google are snippy and not always plesant to read. I couldn't think how to present the stack traces in the following excercises because the explanation of why i was calling element 2 specifically of the stacktrace function is not explained. I have come back now and to my horror have had to C/P a lot of answers and then try to work through the code given to figure out what the goddamn hell is going on. This lesson is truly poor show. Lets hope the rest of the lessons are more helpful and don;t simply rely on you googling the problem and then trying to work your way through the quagmire of passive-aggressive stackoverflow posts to find the ultimate answer presented in a way thats understandable for beginners. Poor Poor Show Codegym
Jonaskinny Level 25, Redondo Beach, United States
20 February 2022
that line says return [get the current Thread running this code from the globally available static Thread class, get the stack trace from that Thread, which is an array of StackTraceElement objects, and call getMethodName() on the StackTraceElement in the returned array at position 2 (the third item)
Andrei Level 41
11 November 2020
For everybody that will struggle with the next exercises: I know the information provided in this lesson is scarce and doesn't talk about other elements that will be needed in the following exercises, BUT, try and do them, research about Stack trace, try the exercises, THINK about the exercises (what does this mean? what does this do? how does this work?), allow yourself a day or two for the information to settle and you will see that the next time you visit them it will make more sense until you finally grasp the concept. Just keep trying to understand and eventually you will! :)
Norbert Level 9, Krakow, Poland
13 July 2020
Useful video for beginners: https://www.youtube.com/watch?v=lg_WYR5gBQI
Aakankasha Sharma Level 19, Chandigarh, India
23 June 2020
In the example given above, currentThread() is also a method, bur why is it not getting printed?
Andrei Level 41
10 November 2020
Hmm.. good question. Maybe because it does not call or is not directly related to other methods?
Daniel Walbolt Level 22, Waterville, United States
21 May 2020
Contrary to what people are saying below, the following tasks are all possible with understanding of the elements of coding that we have worked with before. In other terms, if you understand how to declare an array (StackTraceElement[] elements = ...) and set up a for-each loop, then you will be fine. All other methods are given to you. I do suggest you print out "debug" messages before you turn in your program though; by running your program and displaying the output to console you can essentially see what your program sees and hopefully understand what needs to be done to get the desired result instead (like how a stack trace read from earliest to oldest instead of oldest to newest).
jake taylor Level 17, Lisbon, Portugal
17 May 2020
how was we expected to finish the tasks in the next page from the information, enlighten me...
Johannes Level 27, Centurion, Pretoria, South-Africa
13 March 2020
Please give more examples of the different functions that one has to use that differ WAY from the above example, for the upcoming tasks in the next page ? I could not find it in google, and had to copy and paste code from other students due to a lack of explanation on this topic. This was extremely frustrating, but the rest of the course (so far) is brilliant ;)
Andrea Level 20, United States
7 August 2019
So what would be the benefit of implementing a stack trace on a real world application? Is a stack track useful if something would go wrong within the application and we can examine the output of a stack track to get specific information?
Andrei Level 41
10 November 2020
Yes, I think basically to back track your steps, easier finding of the error and recoding.