What Is The Logic Behind This Result

Why does this code result in these answers?

[EDIT] Fixed the incorrect part about pass by value and clone()

You are asking two questions so let's attach each one separately.

A) What is the value of c and c2 at specific points in the code.

To answer this you need to realize that just saying 'c = c2' doesn't tell the full story. You first create two instances of the Customer object and store the references to them in c and c2 respectively. When you assign c = c2 you are making both variable store the reference to the same (single) instance of Customer; the other will get garbage collected. Now, it is possible to change the state of the remaining object through method calls to either c OR c2 because they both refer to the same instance.

This means that

c.setNbrOf(4+1);               // AAA
c2.setNbrOf(c.getNbrOf()+1); // BBB

changes the value of the same nbrOf member variable twice, it just looks like they are separate because you have made c an alias of c2 (or vice versa depending on how you want to look at it). After line AAA c.nbrOf does equal 5; to calculate what happens in line BBB you need to break the line up into its parts. Calling c2.setNbrOf() with an argument that is actually an expression of the sum of two things, the result of a call to c.getNbrOf() and the numeric literal '1'. The call to c.getNbrOf() returns 5 and the expression adds 1 to it before passing the result, 6, to the call of c2.setNbrOf(). Since c and c2 are aliases of each other you will get a result of '6' when you call getNbrOf using either c or c2 simply because they both point to the same instance.

B) Why does the ++tal in the method andra affect it's value globally?

Well, it doesn't affect the value globally, it only looks that way because again, you have run into an expression used as an argument to a method.

andra(c, ++tal);      // CCC

The call to andra() does not pass '++tal' into the method, it evaluates the expression first, which actually increments tal by 1 in the local scope and then evaluates the value of tal to determine the value to be sent to the method call. This means that, yes, tal was 11 before the line CCC but during the evaluation of the arguments the variable's value was changed to 12 before the call is made. So why does the code print '12' when you can clearly see that

public static void andra(Customer p, int tal) {
p.setName("K2");
tal=9; // DDD
p.setNbrOf(tal);
}

line DDD should result in the value of p.nbrOf being 9? Well, yes, the value of p.nbrOf does get changed to '9' in the line following DDD, just as p.name gets changed to "K2". This leads to your question of why the code prints '12' instead of '9'. This is because of another thing you have to consider and that is scope. The method andra() actually creates a new storage location named 'tal' that is not the same location as the variable with the same name in main(), that is andra() is hiding the name 'tal' so that when it changes the value of 'tal' to 9 it is only changing the local variable and not the variable with the same name in the calling code.

I have to say that this sample code is doing several things to trip you up, which also means it's doing its job to help you understand the different ways the language handles its symbol table that can be confusing. The sample code isn't making it any better by using tal as a local variable in the test code AND as a parameter name in the methods, that is a poor practice but was used here to make the exercise more difficult.

Try this code to see what is actually happening.

// actually Test3 would be a better name, but I'll leave that to you
public class Test {
public static void main(String[] args) {
Customer c = new Customer();
c.setName("K1");

Customer c2 = c;
c.setNbrOf(4+1);
c2.setNbrOf(c.getNbrOf()+1);
int tal = c.getNbrOf()+5;
int tal2 = ++tal;
System.out.println("Namn: "+c.getName()+" ålder: "+c2.getNbrOf()+" reference to c:"+ c);
andra(c, tal2);
System.out.println("Namn: "+c.getName()+" ålder: "+c.getNbrOf()+",
Tal: "+tal);
}
public static void andra(Customer p, int tal3) {
p.setName("K2");
tal3=9;
System.out.println("BEFORE - reference to p: "+p+" tal: "+tal3+" p.nbrOf:"+p.getNbrOf());
p.setNbrOf(tal3);
System.out.println("AFTER - reference to p: "+p+" tal: "+tal3+" p.nbrOf:"+p.getNbrOf());

}
}

This should show several things, the reference to p should be a different value than the reference held in c, using unique variable and parameter names should make it clearer about which variables are being evaluated or changed, and moving the ++tal expression to outside the method call should show how the variable is not being changed from within andra().

What is logic behind runtime of programs?

Adding characters to the end is optimised internally to reuse the same string (array of characters) in memory. Adding at the beginning requires creating a new string, with the position of each character shifted.

What is the logic behind this binary adder question?

I think "overflow" is normally defined in terms of whether the result makes sense, not whether some bit happens to fall off the edge in the process.

You are adding 1 to -1, and the result is 0. Everything is in range; there is no overflow.

Overflow would have been if you added, say, 127 and 1. That should yield 128, but since we're dealing with 8-bit two's complement, you will get -128 instead. That would be overflow.

Digression: One might argue that the question is badly posed because the number FF (decimal 255) cannot be represented in 8-bit twos complement, where the range is -128 to 127, inclusive. However, it is quite common that hex numbers are used to show bit patterns, regardless of what those bit patterns actually mean, and the bit pattern "all bits set" would mean -1.

What is the logic of the recursion

Unless we hit the stop condition:

fact(num) = fact(num - 1) * num;

Therefore:

fact(3) = fact(3 - 1) * 3;

Keeping in mind that fact(1) = 1 (from the if statement early in the fact() method):

fact(3) = fact(2) * 3;
fact(2) = fact(1) * 2;
fact(1) = 1;

Replacing each element:

fact(3) = 1 * 2 * 3;

The recursion is used to repeatedly dive deeper into the process until a stop condition is encountered - in this case when num = 1.

Method result not save in memory how does that work?

deleteCharAt is a mutating method although it also returns a StringBuilder object. This can be easily proved with the following code

String text = "abcde";
StringBuilder builder1 = new StringBuilder(text);
StringBuilder builder2 = builder1.deleteCharAt(text.length() - 1);

System.out.println(builder1.toString() + " - " + builder2.toString());

Output

abcd - abcd



Related Topics



Leave a reply



Submit