wood burning stoves 2.0*
The moose likes Java in General and the fly likes Method Overloading with default param values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Method Overloading with default param values" Watch "Method Overloading with default param values" New topic
Author

Method Overloading with default param values

Anjanesh Lekshminarayanan
Ranch Hand

Joined: Oct 21, 2003
Posts: 46
Hi

Why doesnt this method overloading work ?


I was trying to assign default values
(like public static String foo(byte a = 5, byte b = 10))
only to realize tha Java doesnt support default assignments.

I get


JDK 6

Thanks


Anjanesh Lekshminarayanan
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Are you sure that that's exactly the error you are getting? Because that would be strange. I compiled this small test program:

And got the following errors:

Note that the compiler does not complain that it can't find foo(byte, byte) - it does complain that it can't find variants of this function that take an int parameter. That is because the literal numeric values are of type int, not byte. They are not automatically converted to byte.

You can either (1) cast the literals to byte, or (2) use int instead of byte in the method arguments.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Anjanesh Lekshminarayanan
Ranch Hand

Joined: Oct 21, 2003
Posts: 46
Ah..Thanks.

Yes - you're right, I got

I wanted to use byte to save memory since I know the values are going to be from 1-50 or so.

So I got to typecast all literals manually ?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Originally posted by Anjanesh Lekshminarayanan:
So I got to typecast all literals manually ?

If you explicitly want these to be interpreted as byte and not as int, yes.

There's one special case for byte in the Java language. When you declare a byte and you assign a literal value to it, you don't have to cast it.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by Anjanesh Lekshminarayanan:

I wanted to use byte to save memory


Using byte-sized method parameters will not have any effect on memory usage. Using bytes as member variable may.


[Jess in Action][AskingGoodQuestions]
 
Don't get me started about those stupid light bulbs.
 
subject: Method Overloading with default param values
 
Similar Threads
Ascii to binary and binary to ascii
Java Byte to Hex String
Question on using return value and not.
is there any way pass arguments to class method without overloading ?
Compiler optimization of final variables