• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on Method return type

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the question from K & b book :

import java.util.*;
class Roo{

public static void main(String args[])
{
Roo r=new Roo();
Object o=r.test();
}
object test(){}
//line 9
}

Which two of the following code fragments inserted at line 9 will not compile?

1)return null;
2)object t=new object();
return t;
3)int a[]=new int[2];
return a;
4) char[][] c=new char[2][2];
return c[0][1];
5)char [][]c=new char[2][2];
retutn c[1];
6)return 7;

Ans:4 and 6

I know that since 7 is primitive you cann't return. But I didn't understand ans 4 .
What is the difference between 4 & 5;

Can anybody help me to understand?

Thanks.
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
#5 works for the same reason that #3 also works. In java, an array implicitly extends java.lang.Object. What #3 and #5 are doing is returning a reference to an object (which happens to be an array).
 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What is the difference between 4 & 5;



4 returns a char which is a primitive and 5 returns an array which is an object.
 
roopa chakra
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic