I'm trying to see what's going on in a chain of recursive calls. Is there some way to set a breakpoint in the middle of a single line to see when the function is being called from each statement?
Example: fibonacci(term - 2) + (want to put a breakpoint here) fibonacci(term - 1)
I don't think it is possible for some of the major IDE's like (Eclipse, Netbeans).
However, you can actually update your codes to such that you can evaluate them :
result1 = fibonacci(term - 2);
result2 = fibonacci(term - 1);
sum = result1 + result2;
The above code might not give you an elegant way of presenting your codes but can actually help you solve your problem.
You can't do this, but in some IDE's (Eclipse, IntelliJ) you can evaluate an expression that you highlight during debugging.
This could be useful if you wanted to see what fibonaci(term-2), for example, produced.
Related
How can I set a breakpoint in a single line lambda?
e.g. I'd like the (eclipse) debugger to halt, when outer.doSth(event) is called:
observable.addCallback(event-> outer.doSth(event));
You can't.
If you refactor it like this:
observable.addCallback(event-> {
return outer.doSth(event);
});
you can.
Well this answer is not for eclipse, but in intellij you can (15.x)
You have an option to set a break point either at the line (which is the first option in the image), or at the first lambda or at second one. And so on.
In Eclipse 4.14.0 when I set a breakpoint into a lambda it works automatically correct and I am able to debug the lambda expression. But be aware that Eclipse also stops at the breakpoint at the "line" itself (that's before the stream operation is executed, since it's lazy):
And here you see that I am able to see the value of the group variable:
So you don't have to reformat your code.
Just making #Holger 's comment on this answer an answer:
It is enough to break line after ->
observable.addCallback(event->
outer.doSth(event) //line break works here!
);
I have the following piece of code called Code1.
http://pastebin.com/tc0Vd8xh
When I run this, the sketch does not work.
However when I replace "i=+50" for "i = i + 50" the code works.
My question is why the "i=+50" bit does not work?
As far as I know "i=+50" is proper Java and Processing is based on Java.
I tried to Google about "i=+50" but Google does not process non-alphanumeric characters.
So I came here and I searched in previous questions before asking here. Anyone, any idea why "i=+50" does not work?
The statement i=+50 is the assignment of positive 50 to i. That is why it compiles, but doesn't add 50 to i on each loop. As #RoelHarbers and #ByoTic mentioned, you actually want i += 50
You're using =+, which is not a java operator (or an operator in any other language I know of)
The proper syntax is:
i+=50
Because it's i+=50 and not i=+50.
i =+ 50 is not going to do what you want, it is going to initialize i with 50. Instead, use i+=50, this going to add the 50 to whatever value that i holds.
In our project we are migrating to java 8 and we are testing the new features of it.
On my project I'm using Guava predicates and functions to filter and transform some collections using Collections2.transform and Collections2.filter.
On this migration I need to change for example guava code to java 8 changes. So, the changes I'm doing are the kind of:
List<Integer> naturals = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10,11,12,13);
Function <Integer, Integer> duplicate = new Function<Integer, Integer>(){
#Override
public Integer apply(Integer n)
{
return n * 2;
}
};
Collection result = Collections2.transform(naturals, duplicate);
To...
List<Integer> result2 = naturals.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
Using guava I was very confortable debugging the code since I could debug each transformation process but my concern is how to debug for example .map(n -> n*2).
Using the debugger I can see some code like:
#Hidden
#DontInline
/** Interpretively invoke this form on the given arguments. */
Object interpretWithArguments(Object... argumentValues) throws Throwable {
if (TRACE_INTERPRETER)
return interpretWithArgumentsTracing(argumentValues);
checkInvocationCounter();
assert(arityCheck(argumentValues));
Object[] values = Arrays.copyOf(argumentValues, names.length);
for (int i = argumentValues.length; i < values.length; i++) {
values[i] = interpretName(names[i], values);
}
return (result < 0) ? null : values[result];
}
But it isn't as straighforward as Guava to debug the code, actually I couldn't find the n * 2 transformation.
Is there a way to see this transformation or a way to easy debug this code?
EDIT: I've added answer from different comments and posted answers
Thanks to Holger comment that answered my question, the approach of having lambda block allowed me to see the transformation process and debug what happened inside lambda body:
.map(
n -> {
Integer nr = n * 2;
return nr;
}
)
Thanks to Stuart Marks the approach of having method references also allowed me to debug the transformation process:
static int timesTwo(int n) {
Integer result = n * 2;
return result;
}
...
List<Integer> result2 = naturals.stream()
.map(Java8Test::timesTwo)
.collect(Collectors.toList());
...
Thanks to Marlon Bernardes answer I noticed that my Eclipse doesn't show what it should and the usage of peek() helped to display results.
I usually have no problem debugging lambda expressions while using Eclipse or IntelliJ IDEA. Just set a breakpoint and be sure not to inspect the whole lambda expression (inspect only the lambda body).
Another approach is to use peek to inspect the elements of the stream:
List<Integer> naturals = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13);
naturals.stream()
.map(n -> n * 2)
.peek(System.out::println)
.collect(Collectors.toList());
UPDATE:
I think you're getting confused because map is an intermediate operation - in other words: it is a lazy operation which will be executed only after a terminal operation was executed. So when you call stream.map(n -> n * 2) the lambda body isn't being executed at the moment. You need to set a breakpoint and inspect it after a terminal operation was called (collect, in this case).
Check Stream Operations for further explanations.
UPDATE 2:
Quoting Holger's comment:
What makes it tricky here is that the call to map and the lambda
expression are in one line so a line breakpoint will stop on two
completely unrelated actions.
Inserting a line break right after map(
would allow you to set a break point for the lambda expression only.
And it’s not unusual that debuggers don’t show intermediate values of
a return statement. Changing the lambda to n -> { int result=n * 2; return result; }
would allow you to inspect result. Again, insert line
breaks appropriately when stepping line by line…
IntelliJ has such a nice plugin for this case as a Java Stream Debugger plugin. You should check it out: https://plugins.jetbrains.com/plugin/9696-java-stream-debugger?platform=hootsuite
It extends the IDEA Debugger tool window by adding the Trace Current Stream Chain button, which becomes active when debugger stops inside of a chain of Stream API calls.
It has nice interface for working with separate streams operations and gives you opportunity to follow some values that u should debug.
You can launch it manually from the Debug window by clicking here:
Debugging lambdas also works well with NetBeans. I'm using NetBeans 8 and JDK 8u5.
If you set a breakpoint on a line where there's a lambda, you actually will hit once when the pipeline is set up, and then once for each stream element. Using your example, the first time you hit the breakpoint will be the map() call that's setting up the stream pipeline:
You can see the call stack and the local variables and parameter values for main as you'd expect. If you continue stepping, the "same" breakpoint is hit again, except this time it's within the call to the lambda:
Note that this time the call stack is deep within the streams machinery, and the local variables are the locals of the lambda itself, not the enclosing main method. (I've changed the values in the naturals list to make this clear.)
As Marlon Bernardes pointed out (+1), you can use peek to inspect values as they go by in the pipeline. Be careful though if you're using this from a parallel stream. The values can be printed in an unpredictable order across different threads. If you're storing values in a debugging data structure from peek, that data structure will of course have to be thread-safe.
Finally, if you're doing a lot of debugging of lambdas (especially multi-line statement lambdas), it might be preferable to extract the lambda into a named method and then refer to it using a method reference. For example,
static int timesTwo(int n) {
return n * 2;
}
public static void main(String[] args) {
List<Integer> naturals = Arrays.asList(3247,92837,123);
List<Integer> result =
naturals.stream()
.map(DebugLambda::timesTwo)
.collect(toList());
}
This might make it easier to see what's going on while you're debugging. In addition, extracting methods this way makes it easier to unit test. If your lambda is so complicated that you need to be single-stepping through it, you probably want to have a bunch of unit tests for it anyway.
Just to provide more updated details (Oct 2019), IntelliJ has added a pretty nice integration to debug this type of code that is extremely useful.
When we stop at a line that contains a lambda if we press F7 (step into) then IntelliJ will highlight what will be the snippet to debug. We can switch what chunk to debug with Tab and once we decided it then we click F7 again.
Here some screenshots to illustrate:
1- Press F7 (step into) key, will display the highlights (or selection mode)
2- Use Tab multiple times to select the snippet to debug
3- Press F7 (step into) key to step into
Intellij IDEA 15 seems to make it even easier, it allows to stop in a part of the line where lambda is, see the first feature: http://blog.jetbrains.com/idea/2015/06/intellij-idea-15-eap-is-open/
Debugging using IDE's are always-helpful, but the ideal way of debugging through each elements in a stream is to use peek() before a terminal method operation since Java Steams are lazily evaluated, so unless a terminal method is invoked, the respective stream will not be evaluated.
List<Integer> numFromZeroToTen = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
numFromZeroToTen.stream()
.map(n -> n * 2)
.peek(n -> System.out.println(n))
.collect(Collectors.toList());
As you can probably understand from the question itself, I'm new to Java.
I was given an exercise to write a Java program which receives a character, prints it and the next character in the Unicode table.
Now, I have the solution to this exercise:
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
I understand basic idea of this code, but I'm trying to run this code in Eclipse I get an annoying error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MainClass.main(MainClass.java:9)
Note: I have yet to run a Java program that actually receives something as a parameter so I guess it's a stupid beginners' mistake... Here is the full code that I tried to compile in Eclipse:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
}
Thanks in advance
Select "Run -> Run Configurations" from the menu.
Search for you project in the list on the left and select it.
Select the "Arguments" tab on the right.
Write the argument you want to pass to the programm in "Programm arguments".
Click "Run"
Right click on your java file in project explorer of your eclipse. Then Run As> Run Configuration
Then you will get a window. Like-
Click on Arguments Tabs, and then write some text there, may be a character.
And then Click on Apply button and Run Button.
The default run configuration in Eclipse runs a Java program without any arguments, hence the ArrayIndexOutOfBoundsException. Your code is trying to get first element of the args array when there aren't any!
You can edit the run configuration to provide the arguments to run your program with. Then it should not throw this exception.
However, a good practice is to check the size of array before accessing it's elements, more so when the array is coming as an argument from outside of your code.
This is a great question with some very good answers. I would like to add some pointers about how to debug your own program. Debugging is as important (if not more important) than writing code.
For one thing, Eclipse has some great debugging features. You can use this debugger to find problems in your code. I suggest that you learn how to use it. In particular, you can set watches for variables to see what value they have as you step through the execution of your code.
Alternatively, you can add calls to System.out.println() to print out the values of any variables. For example, adding the following line at the beginning of your code might help you narrow down the problem:
System.out.println(args[0]);
This would also give an ArrayIndexOutOfBoundsException if no command-line arguments are given. Then you could do something like
System.out.println(args.length);
which would print out 0. This then gives you a clue as to where the problem is.
Of course, even when you get to this point, you still might not know how to solve the problem. This is where sites like StackOverflow come in handy.
Good luck with your Java experience. Please come back when you need more help.
If your Run Configurations are in place (as already shown in above answers):
Shortcut to Run a class is:
Ctrl + F11
Some of our code written a while have unnecessary semi-colon. I wonder whats the easiest way to remove them. For example, the last semi-colon in the following
if(i == 2)
{
System.out.println("if statement");
}
else
{
System.out.println("else statement");
};
You can find them easily enough by going into the Java Compiler / Error and Warnings preferences, then under "Potential Programming Problems" change "Empty Statements" to warning or error. Then it'll just be a matter of going through them. There may be a way of automating it, but I wouldn't bother unless there are loads :)
It is probably too late for you but, you can Analyze your code with Intellij IDEA using the Inspection "Unnecessary semi-colon" then after it has found them all you can apply the Fix.
http://www.jetbrains.com/idea/documentation/inspections.jsp
Eclipse can also do this too but it suffers from a bug that doesn't allow you to apply the Quick Fix in bulk.
As the above said, by typing ctrl + f and searching for }; and replacing it with } would work great, but could break the code.
They are not necessary to be removed, as it is just the equivalent of:
if(true){
//...
}
/*Empty Line*/;
It won't effect the code in any way, but is best to remove them just for preference.
It may be too late for you but this could help others:
CTRL + F
write what you want to delete in your case ; and then:
CTRL + ALT + SHIFT + J
This will select all the matches for your search in that file.
Then you just have to delete DELETE