• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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.
 
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic