See the values of variables change while a Java program is running? - java

Consider a java program with many variables and some of them are counters for loops I want to see the values of these variables as they change with time , WITHOUT putting print statements everywhere in my code.
Why ? I think it can help me to debug easily.
Example-
int a = 7;
for(i=0; i<3; i++)
{
a++;
}
As this program runs I want to get live reports like this:
t is 0, a is 7, i is 0
t is 3, a is 8, i is 1
t is 12, a is 9, i is 2
(t is time, time factor is NOT necessary though)

You can use a debugger. Debuggers will help you keep track of that without actually sending your vars to STDOUT. I recommend DDD because it's free and professionally used. http://www.gnu.org/software/ddd/
Note: to avoid confusion about how it works, DDD works on top of JDB, the Java debugger included in the JDK.

You should use a debugger and put a breakpoint where you want to see the values (in this case at the line with a++). The you can see the value at each iteration.
Most IDEs have debuggers (Intellij IDEA, Eclipse or NetBeans).

This is what debuggers are used for.. to step through your code and check the values of variables. If you want your code to print out statements every so often, you can use the Timer class and TimerTask to print out the value of a variable for a specified time interval.

1. Use Debugger, If you are using an IDE like Eclipse, IntelliJ, then its build in, into it.
2. If you are not using any debugger, then you can use jdb The Java Debugger.
See JPDA for the debugger architecture specifications.

Eclipse doesn't support this if I'm not mistaken but in Intellij IDEA you can setup breakpoint in a way that doesn't stop your application running when hit it but instead evaluates and logs particular expression you specified. The same functionality available for those who use ms visual studio:)

Related

Is there a way to tell if there is code not being used in java?

Whenever I program, I seem to accumulate a lot of "trash" code, code that is not in use anymore. Just to keep my code neat, and to avoid making any expensive and unnecessary computations, Is there an easy way to tell if there is code that is not being used?
One of the basic principles which will help you in this regard is to reduce visibility of everything as much as possible. If a class can be private don't make it default, protected or public. Same applies for methods and variables. It is much easier when you can say for sure if something is not being used outside a class. In cases like this even IDEs like Eclipse and IntelliJ Idea will suggest you about unused code.
Using this practice while developing and refactoring code is the best way to clean unused code confidently without the possibility of breaking the application. This will help in scenarios even when reflection is being used.
It's difficult to do in Java since it's a reflective language. (You can't simply hunt for calls to a certain class or function, for example, since reflection can be used to call a function using strings that can only be resolved at runtime.)
So in full generality, you cannot be certain.
If you have adequate unit tests for your code base then the possibility of redundant code should not be a cause for concern.
I think "unused code" means the code that is always not executed at runtime. I hope I interpreted you correctly.
The way to do a simple check on this is very easy. Just use IntelliJ IDEA to write your code. It will tell you that parts of your code that will never be executed and also the parts where the code can be simplified. For example,
if (x == 5) {
}
And then it will tell you that this if statement is redundant. Or if you have this:
return;
someMethod();
The IDE will tell you that someMethod() can never be reached. And it also provides a lot of other cool features.
But sometimes this isn't enough. What if you have
if (x == 5) {
someMethod();
}
But actually in your code, x can only be in the range of 1 to 4? The IDE won't tell you about this. You can use a tool that shows your code coverage by running lots of tests. Then you can see which part of your code is not executed.
If you don't want to use such a tool, you can put breakpoints in your methods. Then run some tests by hand. When the debugger steps through your code, you can see exactly where the code goes and exactly which piece(s) of code is not executed.
Another method to do this is to use the Find/Replace function of the IDE. Check if some of your public/private methods are not being called anywhere. For example, to check whether someMethod() is called, search for someMethod in the whole project and see if there are occurrences other than the declaration.
But the most effective way would be,
Stop writing this kind of code in the first place!
i think the best way to check that is to install a plugin of coverage like eclemma and create unit and integration tests to get 100% of coverage of the code that accomplish the use code/task you have.
The code that don't need to be tested or don't pass over it after the tests are completed and run, is code that you are not using
Try to avoid accumulating trash in the first place. Remove stuff you don't need anymore. (You could make a backup or better use a source code management system.)
You should also write unit tests for your functions. So you know if it still works after you remove something.
Aside from that, most IDEs will show you unused local variables and private methods.
I do imagine situation when you have app developed by years and some part of your functions doesn't used anymore even they still working. Example: Let's assume you make some changes on internal systems when specific event occured but it is not occurs anymore.
I would say you could use AspectJ to obtain such data / log and then analyze after some time.

How skip line in Intellij idea debug?

Suppose I have java code like this (only as Example):
public void someMethod(){
int a = 3;
int b = 2; // <-- stay debug here
a = b + 2;
System.out.prinln(a);
}
It is possible to skip execution of line a = b + 2; and go immidiatly to System.out.prinln(a);?
P.S. I use Intellij Idea 12.
It's not possible with the debugger to not execute parts of the code.
It is however possible to execute extra code and change values on variables so if you need to exclude one row from execution during debug you will have to alter your code to prepare for that kind of debugging.
public void someMethod() {
int a = 3;
int b = 2;
boolean shouldRun = true;
if (shouldRun) {
a = b + 2;
}
System.out.prinln(a);
}
You would then set a break point that changes the value of shouldRun without stopping execution. It can be done like this.
Note that
Suspend isn't checked
Log evaluated expression is used to alter a variable when the break point is hit
IntelliJ recently published a blog post about a plugin called Jump to Line that can accomplish this, even though IntelliJ itself doesn't have this functionality. It really is surprising that IntelliJ still doesn't have this functionality, when Visual Studio has had it for so many years!
https://blog.jetbrains.com/idea/2020/08/jump-to-any-line-while-debugging/
It is possible to skip lines only if you use hotswapping, or put in other words, code reloading tool - add code changes/new code at runtime. Hotswapping is the functions of replacing components without shutting down the system. Hotswapping can also refer to the ability to alter the running code of a program without needing to interrupt its execution.
There are various hotswapping tools like: JRebel (https://zeroturnaround.com/software/jrebel/) or HotSwapAgent (http://www.hotswapagent.org/)
You avoid having to rebuild the entire application to reload code changes, this is a huge time savings. Instead of running your full build process, simply use the compiler built into your IDE and the hotSwap agent/tool will reload the code into the JVM.
In this case, it would not be actually skipping, but you can just comment/change the lines and reload it. This tools are quite awesome!!!! It greatly speeds up the development/debugging process.
You can't just skip 'line execution' when debugging. You can press F8 to step over.
An option is to skip the execution of the rest of the method. You can invoke Force Return and even set a return value.
As stated here by ntotomanov , you can use HotSwap for it.
but just adding that i use remote debug to debug my Docker based apps , so if i want this kind of functionality i just comment out the code , and go to Build -> Recompile class or Rebuild Project . then Intellij issues Build & Attempting to HotSwap the code ! in case you did small thing like comment out the code it most of the times always succeeds. happy debugging.
It is not possible to skip the EXECUTION of the lines in IntelliJ and even in Eclipse.
Only thing you can do is you can do step over (F8)-which will trace line by line without
going inside any function.
One more thing is Step out(Shift+F8)- which will go to next debug point directly by executing in between lines in that single step.

Hooking an existing method in Java

I want to hook the method System.out.print in Java and have the ability to read/change the variables used in the method before the part of the method is called that actually adds the string to whatever the output stream is.
In C++ I would just detour the function, or set an int3 instruction so I could access the registers but in java I have no idea how to accomplish something similar.
You can rewrite the byte code of the methods, and in the process capture/change the local variables. It is not trivial. See some notes here.
Maybe what you really want is a java debugger? You can connect a debugger to a remote process, add a breakpoint, and capture/change the local variables pretty easily using eclipse.
What is the real problem you are trying to solve?
Have a look at this link.
He sneakily defines a static anonymous class so that System.out points to something different, and therefore print and println will route through that object.
You can reassign System.out (and System.err) to another object which does what you want to do with it. Said object usually gets the old System.out value so that output can be made in the end.
This is usually done in main() and influences the whole JVM.
We use this to have automatic wrapping at 130 columns in a very peculiar setting where longer lines are truncated.
Since JDK 1.1, the System.setOut and System.setErr methods are added to enable applications to hook the streams.
Link : http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setOut(java.io.PrintStream)
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setErr(java.io.PrintStream)
#Nowayz Some time before i too had the same problem with me.
After some research i came to know About AOP. AOP i.e. AspectJ provides a facility to intercept the java APIs by applying the pointcuts before,after, around. So have a look at it .You can refer my question on stack .it may help you.

Changing object fields on the fly while debugging in Eclipse [duplicate]

Using Eclipse, when debugging is it possible to change the value of variables during runtime of a project for testing purposes.
For example, say I have a method that returns the number 5 but for testing purposes i want to output 10 instead. This isn't the problem I'm facing its a little more complex but its just to get my idea across.
You should be able to set a break-point, go into debug mode, open the variables views and here change the content of the variables.
You can access variables through the Variables view. There you can right click on any variable and select "Change value ...".
Resources :
standford.edu - eclipse guide
help.eclipse.org - change var value
... and you can do much, much more:-) Just to give you and idea.
You may change the code during debug which is hot swapped and is effectively changed (recompiled) in given debug session.
You may run given method run (e.g. after catching breakpoint) few times without rerunning debug -> use drop to frame feature on method stack.
After you have changed the code you have to save it (cntrl-S) to make it effective.
You will see your running application respond to the code-change after the cntrl-S
I hope this works for you. it took me some time to figure this out.
Run your application in debug mode then go to variables window. select the parameter then change values according to your requirements. then save (ctrl+s). and go ahead with your changes. Hope this will help.
If variables window is missing. then goto eclipse window->show views->variables

Commenting out System.out.println

Do System.out.println(...) calls pose any effect if left in BlackBerry code or any other programming language?
When removed, the compilation time may be reduced, but is there any particular other reason to remove them?
There are a couple of things you need to know before using System.out.println() on Blackberry:
Once you print out something to the standard output any person that has your application installed on the device will be able to see them. All they need to do is to attach the device to the simulator and run in debug mode. So make sure you do not print out anything sensitive such as passwords, class names etc. in the released application.
The performance overhead that the System.out.println() itself makes is minimal, especially when the output stream is not attached to anything (i.e. Device is not connected and not in debug mode).
I myself rather use Blackberry preprocessor to be able to disable all logs before making a release. For this reason I define a logging directive LOGGING and then in my code:
//#ifdef LOGGING
System.out.println("LOGGING is enabled");
//#endif
For more on how to use preprocessors in Blackberry Eclipse plugin see this.
I prefer to use a flag to disable sysouts. Sysouts are really slow if you use them a lot, eg. in loops.
If you don't intend to use the output for anything like debugging ect. then it's best to take it out. Your program will only run as fast as the line can be output so in theory the less system.out line you have the faster the process will be.
Hope this helps.
Runtime might be also reduced, as the statements are actually executed - even if the user doesn't see the output on the screen. If you're using a lot of these (e.g. in tight loops) or you're passing to them Objects with expensive toString() methods, the useless output may be slowing you down.
Also, if you're passing String as an argument, those will take some space in bytecode and in memory. You on your souped-up machine with 173 PB of RAM may not care, but there are resource-constrained systems (such as mobile devices).
You should be able to use Ant to preprocess these lines out of your source code. (Make sure that none of them have side-effects!)
I don't know specifically about Blackberry, but if your program is writing to an unknown device (i.e. you are not sure where standard out is going), there may be a potential for your app to occasionally/sporadically/inexplicably block momentarily in the attempt to write.
Create your own method, i.e. :
public static void consoleMessage(String msg){
if(DEBUG_FLAG){
System.out.println(msg);
}
}
Then use only this throughout your code. It will save you the time for changing all the lines.
Use something like Log4J instead of system out print statements, it gives you much more flexibility
Keeping System.out statements isn't that bad a thing to do usually. Users might be able to see them so it doesnt always look good in a production environment. A better idea is to use a logging framework such as java.util.logging or log4j. These can be configured to dump output to the console, to a file, a DB, a webservice ...
Keep in mind that just becuase you can't see the output it doesn't mean that no work is being done at runtime. The JVM still has to create a String to pass to system.out (or a log statement) which can take a fair bit of memory/CPU for large/complex objects like collections.
Sysout statements access a synchronized, shared resource, which causes synchronization between threads using it. That can prevent memory consistency bugs in multithreaded programs if there is no other code which enforces synchronization. When the sysout statements are removed, any existing memory consistency bugs in the code may surface for the first time.
For an example of this effect, see: Loop doesn't see changed value without a print statement.
It's not an object and it doesn't have any memory attached to it so there shouldn't be any effect besides the time to run it and compile it. And of course readability maybe lol

Categories