Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File separator allowed within java.io.File

Found a confusing question while learning about file separators

Suppose that the file c:\book\java exists. Which of the following lines of code creates an object that represents the file? (Choose all that apply.)

1. new File("c:\book\java"); 2. new File("c:\\book\\java"); 3. new File("c:/book/java"); 4. new File("c://book//java"); 5. None of the above

the book (assumig a dos based file system) says that

  1. & 3. are right answer
  1. is correct because Java requires a backslash to be escaped with another backslash.
  2. is also correct because Java will convert the slashes to the right one when working with paths..
  • Can 4 also be correct by this logic?
  • and when i change to mac/linux file system - what should be the answer ? (update: we are only creating a file object - whether it makes sense is not the question here - the question is which of these will finally return the path shown above)
like image 547
RangerReturn Avatar asked Dec 19 '25 09:12

RangerReturn


1 Answers

Can 4 also be correct by this logic?

Given that the question is

Suppose that the file c:\book\java exists. Which of the following lines of code creates an object that represents the file? (Choose all that apply.)

  1. new File("c:\book\java");
  2. new File("c:\book\java");
  3. new File("c:/book/java");
  4. new File("c://book//java");
  5. None of the above

2 and 3 are obviously correct. So, does the File object in 4 "create an ojbect that represents the file"?

Yes it does.

Assuming C:\book\java exists, this code

public static void main( String[] args ) throws IOException
{
    File f = new File( args[ 0 ] );
    System.err.printf( "args[0]: %s\n", args[ 0 ] );
    System.err.printf( "Path: %s\n", f.getCanonicalPath() );
}

produces this output:

args[0]: C://book//java
Path: C:\book\java

So new File( "C://book//java" ) most definitely "creates an object that represents the file" and is also a correct answer.

Any argument that it does not is literally incorrect. The question is whether or not the string "creates an object that represents the file". C://book//java demonstrably does exactly that.

like image 161
Andrew Henle Avatar answered Dec 20 '25 22:12

Andrew Henle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!