Given the following 2 classes Example1 and Example2 and excluding all performance characteristics, do these two classes operate the exact same way. That is, regardless of how simple or complex either methodA or methodB is or can be, would the result of running these two classes, under all possible conditions (both internal and external), always be absolutely the same?
public class Example1
{
public static void main (String [] args)
{
try
{
// this will not compile since nextBoolean() is not static
// boolean t = java.util.Random.nextBoolean();
// changed to
java.util.Random r = new java.util.Random();
boolean t = r.nextBoolean();
if (t)
{
methodA();
methodB();
}
}
catch (Throwable t)
{
t.printStackTrace(System.out);
}
}
private static void methodB ()
{
// code goes here
}
private static void methodA ()
{
// code goes here
}
}
public class Example2
{
public static void main (String [] args)
{
try
{
boolean t = java.util.Random.nextBoolean();
if (t)
{
methodA();
}
if (t)
{
methodB();
}
}
catch (Throwable t)
{
t.printStackTrace(System.out);
}
}
private static void methodB ()
{
// code goes here
}
private static void methodA ()
{
// code goes here
}
}
The results are not guaranteed to be absolutely the same, although in general they will be. Specifically, you can write a methodA
and methodB
implementation that would yield different results when run in Example1
and Example2
, even if the class names of the main program were made the same before execution.
One way to accomplish this would be to generate the stack trace and then introspect on the line number for the execution of methodB
, which is different in Example1
and Example2
.
For example, the below methodB will result in different output when run in Example1
and Example2
.
public static void methodB()
{
int count = 0;
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement element : elements)
{
count += element.getLineNumber();
}
System.out.println(count);
}
However, in general the programs will yield the same results since this type of logic based on stack traces or other such aspects is unusual.