Computer Science Canada

Java Trivia

Author:  wtd [ Mon Oct 03, 2005 11:25 am ]
Post subject:  Java Trivia

Let's see how good the resident Java gurus really are. Smile

Two true or false tests.

In Java, all object types are passed by reference.

Java does not have pointers.

Author:  rizzix [ Mon Oct 03, 2005 11:40 am ]
Post subject: 

True. True. (although java references can contain null values and are re-assignable, it really depends on ur definition of a pointer/reference.. in my books a pointer is somthing to which u can directy assign a physical address as in C-pointers.)

Author:  wtd [ Mon Oct 03, 2005 11:55 am ]
Post subject: 

False and false. Smile

Java:
public class Test
{
   public static void main(String[] args)
   {
      String str = "Foo";
      System.out.println(str);
      foo(str);
      System.out.println(str);
   }

   public void foo(String s)
   {
      s = "Hello";
   }
}


Compare to:

c++:
#include <string>
#include <iostream>

void foo(std::string& s)
{
   s = "Hello";
}

int main()
{
   std::string str("Foo");
   std::cout << str << std::endl;
   foo(str);
   std::cout << str << std::endl;

   return 0;
}


And pointers exist. Smile

See NullPointerException. Wink

Author:  rizzix [ Mon Oct 03, 2005 12:02 pm ]
Post subject: 

I got a better one for you.. (everyone is free to answer.. the first one give the right answer will get 200 bits)

Now here's the question, explain me why the follow code results true:
Java:
String s1 = "hello world";
String s2 = "hello world";

s1 == s2; // true

Author:  rizzix [ Mon Oct 03, 2005 12:03 pm ]
Post subject: 

it's funny but you are wrong both times Wink

(yes i know it appears to be soo but it isin;t) you just happened to pick a poor example (the java String object)

Explaination:

first let's look at your code
code:
public class Test
{
   public static void main(String[] args)
   {
      String str = "Foo";
      System.out.println(str);
      foo(str);
      System.out.println(str);
   }

   public void foo(String s)
   {
      s = "Hello";
   }
}


Now here's the deal..
when passing str to foo.. what actually happens inside foo is this:
Java:
String s = foo
Basically the reference s now points to foo.. so if u reassign s a new object i.e ("hello").. that does not mean u are infact re-assigning foo the object "hello".

a better example would be this (cuz strings are immutable objects):

code:
public class Test
{
   class A {
       private String str;
       public void setStr(String s) {
           str = s;
       }
       public String toString() {
           return str;
       }
   }

   public static void main(String[] args)
   {
      A obj = new A();
      a.setStr("foo");
      System.out.println(a);
      foo(a);
      System.out.println(a);
   }

   public void foo(A a)
   {
      a.setStr("Hello");
   }
}

Author:  wtd [ Mon Oct 03, 2005 12:13 pm ]
Post subject: 

Quote:
Both s1 and s2 are in fact pointers (Java goes to great pains to hide this fact), and both are pointing to the same value. Since both strings can be determined at compile-time to be identical in value, and since Java's strings are immutable, it only allocates that string once. Thus both pointers are pointing to the same location in memory.

If we were to manually construct the string through concatenation, the Java compiler becomes incapable of (or unwilling to) determine whether they contain the same value, and thus we end up with two different locations in memory allocated. Since == tests for referential equality, this will now fail.

It can easily be seen from this example that == is a highly unreliable test to use here and the code should be rewritten using the "equals" method.

Author:  rizzix [ Mon Oct 03, 2005 12:15 pm ]
Post subject: 

ditto.

Author:  wtd [ Mon Oct 03, 2005 12:20 pm ]
Post subject: 

rizzix wrote:
it's funny but you are wrong both times Wink

(yes i know it appears to be soo but it isin;t) you just happened to pick a poor example (the java String object)

Explaination:

first let's look at your code
code:
public class Test
{
   public static void main(String[] args)
   {
      String str = "Foo";
      System.out.println(str);
      foo(str);
      System.out.println(str);
   }

   public void foo(String s)
   {
      s = "Hello";
   }
}


Now here's the deal..
when passing str to foo.. what actually happens inside foo is this:
Java:
String s = foo
Basically the reference s now points to foo.. so if u reassign s a new object i.e ("hello").. that does not mean u are infact re-assigning foo the object "hello".

a better example would be this (cuz strings are immutable objects):

code:
public class Test
{
   class A {
       public String str;
   }

   public static void main(String[] args)
   {
      A obj = new A();
      a.str = "foo";
      System.out.println(a.str);
      foo(a);
      System.out.println(a.str);
   }

   public void foo(A a)
   {
      a.str = "Hello";
   }
}


You're still confused. When you pass "a" into "foo", you're copying the pointer value into a completely new variable. Of course, you then assign to a field of the object "a" is pointing to, which mutates that field. Sadly Java lacks a "const" context.

This has nothing to do with references.

c++:
#include <string>
#include <iostream>

struct A
{
   std::string str;

   A() : str("Foo") { }
};

void foo(A *a)
{
   a->str = "Hello";
} 

int main()
{
   A *a = new A;
   std::cout << a->str << std::end;
   foo(a);
   std::cout << a->str << std::end;

   return 0;
}

Author:  rizzix [ Mon Oct 03, 2005 12:24 pm ]
Post subject: 

No i'm not confused... You are... You're thinking too much in C++.
Java references are not like C++ references..


maybe this will explain it a bit better:
code:
String a = "abc";
System.out.println(a);
String b = a;
b = "xyz";
System.out.println(a);


notice just cuz i assigned b, a. does not mean a has changed to "xyz"


NOTE: i also updated my previous example to better represent what i was trying to say.

Author:  wtd [ Mon Oct 03, 2005 12:27 pm ]
Post subject: 

I'm not thinking in C++. It just happens to be convenient for this, having both pointers and references.

Author:  rizzix [ Mon Oct 03, 2005 12:29 pm ]
Post subject: 

I told you java reference are not like c++ reference.. they point to objects yet they can't point to a physical address.

fact is.. c++ references are more like name aliases.

Author:  wtd [ Mon Oct 03, 2005 12:33 pm ]
Post subject: 

rizzix wrote:
code:
String a = "abc";
System.out.println(a);
String b = a;
b = "xyz";
System.out.println(a);


notice just cuz i assigned b, a. does not mean a has changed to "xyz"


Yes, you have two pointers: "a" and "b". You start out with "a" pointing to "abc".

You then have "b" point to the same location in memory that "a" points to.

You then decide that "b" should point to "xyz" instead.

Naturally, "a" is unchanged.

c++:
std::string *a = new std::string("abc");
std::cout << *a << std::endl;
std::string *b = a;
b = new std::string("xyz");
std::cout << *a << std::endl;


That's what the Java example is basically doing, though its syntax does a poor job of reflecting that behavior.

Author:  wtd [ Mon Oct 03, 2005 12:34 pm ]
Post subject: 

rizzix wrote:
I told you java reference are not like c++ reference.. they point to objects yet they can't point to a physical address.


But they do point to a physical address. You don't see that because Java doesn't want you to see its frilly underthings, but that's what's going on. Smile

Author:  rizzix [ Mon Oct 03, 2005 12:36 pm ]
Post subject: 

*sigh* i'f you'd rather call it that..

Java references are very much liker perl references... they are logical.. they can't really point to anything physical.. it's all in the VM.

i can't really do this in java:
Java:
Object a = 0x1F23FA;
or something like that...

Author:  rizzix [ Mon Oct 03, 2005 12:41 pm ]
Post subject: 

wtd wrote:
rizzix wrote:
code:
String a = "abc";
System.out.println(a);
String b = a;
b = "xyz";
System.out.println(a);


notice just cuz i assigned b, a. does not mean a has changed to "xyz"


Yes, you have two pointers: "a" and "b". You start out with "a" pointing to "abc".

You then have "b" point to the same location in memory that "a" points to.

You then decide that "b" should point to "xyz" instead.

Naturally, "a" is unchanged.



Ditto similarly in your example the reference s (the parameter) is assigned to foo. Wink Now do you see why reassigning s simply assigns s another object.... s is not an alias of foo!

Author:  wtd [ Mon Oct 03, 2005 12:59 pm ]
Post subject: 

rizzix wrote:
i can't really do this in java:
Java:
Object a = 0x1F23FA;
or something like that...


No, but that's an artificial limitiation, rather than a sign of how the language really works. It's doing that under the surface, it just isn't letting you see it.

In fact, all paremeters are passed by value. It just so happens, that in the case of objects, that value is the pointer to the object. Smile

And yes, true references are effectively "name aliases".

Perhaps you would have preferred an Ada example (ints, since strings can be a pain in Ada):

ada:
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
   A : Integer := 42;

   procedure Foo(Bar : out Integer) is
   begin
      Bar := 27;
   end Foo;
begin
   Put(A, 0); New_Line;
   Foo(A);
   Put(A, 0); New_Line;
end Test;

Author:  rizzix [ Mon Oct 03, 2005 2:32 pm ]
Post subject: 

Quote:
In fact, all paremeters are passed by value. It just so happens, that in the case of objects, that value is the pointer to the object. Smile
you could very-well say that nevertheless objects in java are passed by reference alone.

Author:  rizzix [ Mon Oct 03, 2005 2:52 pm ]
Post subject: 

wtd wrote:
No, but that's an artificial limitiation, rather than a sign of how the language really works. It's doing that under the surface, it just isn't letting you see it.
Wrong again. It's not an artificial limitation.. the jvm is designed from the ground up likewise..

how's does that make it artificial?

just because your conception of how the language works.. is different from reality.. dosen't mean the language actually works they way you think it does. the jvm never ever refers to the physical memory directy, but only if the method is labeled "native".

Java:
class test {
    public static void main(String[] args) {
        Object o = new Object();
    }
}

0 new #2 <Class java.lang.Object>
3 dup
4 invokespecial #1 <Method java.lang.Object()>
7 astore_1
8 return
notice the bytecode generated for the assignment.. there's no direct reference to a physical memory location whatsoever. the object is directly stored into the reference o.

Java references are not pointers, neither are they aliases to objects. They are pure references.

Author:  staticvoid [ Thu Mar 20, 2008 6:47 pm ]
Post subject:  But...

rizzix @ Mon Oct 03, 2005 11:02 am wrote:
I got a better one for you.. (everyone is free to answer.. the first one give the right answer will get 200 bits)

Now here's the question, explain me why the follow code results true:
Java:
String s1 = "hello world";
String s2 = "hello world";

s1 == s2; // true


...but string is a class, not a primitive type.

You could use

Java:
String s1 = "hello world";
String s2 = "hello world";
s1.equals(s2);

Author:  r691175002 [ Fri Mar 21, 2008 1:59 am ]
Post subject:  Re: Java Trivia

wtd @ Mon Oct 03, 2005 11:25 am wrote:
Let's see how good the resident Java gurus really are. Smile
Two true or false tests.
In Java, all object types are passed by reference.
Java does not have pointers.

You can only pass values which happen to be references to the objects in question. Technically you are passing by value, in general it works out like you are passing by reference. This means that any changes made to the object will affect it, however changes made to the reference itself (Via = operator) will not affect the main program.

No, Java does not have pointers. You are going to need a stronger argument than the name of an exception (Probably a legacy from earlier versions to cater to C/C++ programmers). It doesn't matter what you think they are behind the scenes or how they work, in Java there is only one type of reference, and they decided to call it a reference. They could call it SignThingie and then it would be a SignThingie, because thats what they say it is.

Essentially:
1. False
2. True

As to staticvoid, his code is correct. In this case, the equality operator will return true as both references point to the same value, as explained in third or so post.

Author:  TokenHerbz [ Thu Mar 22, 2012 11:02 pm ]
Post subject:  RE:Java Trivia

don't rely on the == operator for string tho, because what it does under neath the surface, is checks does A == B MEMORY LOCATION kinda deal. it checks to see if they sit in the same spot so if your reading a file for value A and have a value already made for B in your program thats set and ready to go, thats in memory location X, and well X doesn't = Y(being the read file)... you should ALWAYS use the .equils which compares the actual values, not just the references to location of memory. because both A and B could be exactly the same, if you read one in via file and assign one in the program the memory allocations differentiate and == results a false.

Author:  md [ Fri Mar 23, 2012 4:32 pm ]
Post subject:  RE:Java Trivia

Holy necroposting batman!

Don't do it again.

Author:  yesir360 [ Tue Dec 24, 2013 10:36 pm ]
Post subject: 

rizzix @ Mon Oct 03, 2005 9:02 am wrote:
I got a better one for you.. (everyone is free to answer.. the first one give the right answer will get 200 bits)

Now here's the question, explain me why the follow code results true:
Java:
String s1 = "hello world";
String s2 = "hello world";

s1 == s2; // true


It's by default.
(I think)

"==" is used for numbers and such
while using strings, you should use "s1.equals(s2);"
otherwise, you will just get true as default.


: