Page 1 of 1

About Question enthuware.ocpjp.v7.2.1601 :

Posted: Sat Sep 14, 2013 6:33 am
by rostre
Hello,

when I run the code fragment from this question, it prints "../z", which was also my choice.
But the correct answer should be "..\..\z"? Maybe someone could explain that?


with regards

Re: About Question enthuware.ocpjp.v7.2.1601 :

Posted: Sat Sep 14, 2013 7:13 am
by admin
I just ran it and it prints ..\..\z as explained in the question. Are you sure you are running the code exactly as given?

HTH,
Paul.

Re: About Question enthuware.ocpjp.v7.2.1601 :

Posted: Sun Sep 22, 2013 8:18 am
by Wisevolk
Hello,
same answer as rostre and I just copy/paste the code

Re: About Question enthuware.ocpjp.v7.2.1601 :

Posted: Sat May 31, 2014 12:27 pm
by Crashtest
I think the answers Wisevolk and rostre had may be incorrect due to being run on an incorrect OS. I run the given code on a Mac and had the same answer:
../z
, but it is wrong. I know from Oracle's website that you can not compare two paths if one is from Win and another from Unix. Probably the same situation is with relativize. I changed "\\" to "//" unix format and got correct answer

Code: Select all

import java.nio.file.Path;
import java.nio.file.Paths;

public class Relativize {
	public static void main(String[] args) {
		Path p1 = Paths.get("x//y");   // changed, on Windows you need: "x\\y"
		Path p2 = Paths.get("z");
		Path p3 = p1.relativize(p2);
		System.out.println(p3);
	}
	
}
Now it prints correctly:

Code: Select all

../../z

Re: About Question enthuware.ocpjp.v7.2.1601 :

Posted: Wed Aug 13, 2014 9:44 am
by bluster
For future questioners, Crashtest nailed it. I just tested on both Mac and Windows, and with the slash direction adjustments got what he said on Mac, and what Paul said on Windows.

Re: About Question enthuware.ocpjp.v7.2.1601 :

Posted: Sat Aug 06, 2016 8:41 am
by insider
"//" unix format
Probably it's needed to add that having two forward slashes looks pointless and misleading, one slash is enough.
Windows-style code has two backslashes in a row because the first one is escape character. With forward slash there's nothing to escape.

Unfortunately the code is actually platform-dependent. If I got this right, on Unix backslash is treated as part of the file name and not as a separator. Thus in "x\\y" there's actually one segment and not two. Windows, however, is more lenient and calmly translates forward slash to backslash as a separator.

Therefore running "x/y" produces "..\..\z" result on both Windows and Unix (but never puts you in a confusing situation thus not giving a chance to learn something). Running "x\\y" produces "..\..\z" only on Windows but not on Unix where the result is "..\z".