As I am going through the dumps for the preparation of OCA-Level 1 I encountered one question I don't know the answer to.
If a method is defined with three arguments, when you use this method with two arguments will the third argument be null by default?
a. YES
b. NO
The code is
class overload{
int ovlDemo (int a , int b, int c){
System.out.println("hi"+ a+""+ b);
return a+b;
}
}
class EJava5{
public static void main (String args[]){
overload ab= new overload();
ab.ovlDemo(4,6,9);
}
}
For the above code it will have values 4, 6, 9
..................EDIT...................
But for this code given below has compilation error as the int c is not passed a value at ab.ovlDemo. SO i just need is confirmation that what will be third variable?
a.) Null
b.) 0
class overload{
int ovlDemo (int a , int b, int c){
System.out.println("hi"+ a+""+ b);
return a+b;
}
}
class EJava5{
public static void main (String args[]){
overload ab= new overload();
ab.ovlDemo(4,6);
}
}
If a method is defined with three arguments, when you use this method with two arguments will the third argument be null by default?
As worded, the question is nonsensical, because you can't 'use this method with two arguments'. The compiler won't let you. The question of null-ness at runtime doesn't arise, because you can't get to run-time.
The answer is therefore 'no', but not for any of the reasons given.
Related
public class Demo1{
public static void main(String[] args){
show('A','A');
}
public static void show(char c, long a){
System.out.println("long-char");
}
public static void show(char c, int a){
System.out.println("char-int");
}
}
Output : char-int
But when I change the order of parameters in the first show() method (replacing
public static void show(char c, long a){} with public static void show(long a, char c) {}), I get a compilation error.
The compiler says that it is an ambiguous method call, because it is.
The general approach taken for overload resolution is to find the most specific applicable method, given the number and types of the actual parameters.
In the first case, the two methods have char as their first parameter; so it is only down to choosing whether the int or long overload is more specific, given that the actual parameter is a char: it is the int overload which is more specific, because int is narrower than long.
In the second case, one method has char as the first parameter; one method has char as the second parameter. So, given that the actual parameters are both chars, one of the parameters has to be converted (widened) to invoke either of the methods.
The language spec does not define that one is more specific than the other in such a case; they are both considered equally applicable, so the method call is ambiguous, and thus is a compile-time error.
Is it possible for two methods to be have the same name and same parameters and return the same type?
For example I have these two methods:
class Method
{
public int mm(int a,int b)
{
return a+b;
}
public int mm(int a,int b)
{
return ab;
}
public static void main*String j[])
{
Method m=new Method();
System.out,println(m.add(12,23);
System.out.println(m.add(12.0f,23.0f);
}
}
But this code generate error it means that return type should not same
Overloading methods must differ in one of the following :
Number of parameters.
Data type of parameters.
Sequence of Data type of parameters.
I see there are several syntactical errors in the code snippet you provided. Never mind, I guess the syntax got wrong while you wanted to put up the code in the question.
Coming to your query:
You see you have the exact method signatures for both your mm methods. Both the mm methods take int a and int b and returns an int.
Thus the compiler will not know what method to call because these two methods will be called in exactly the same conditions. In other words, there is no simple scenario when either of these methods will not be called.
However, if you change the arguments of either of the mm methods, your code will compile:
public int mm(int a, int b) {
return a + b;
}
public int mm(float a, float b) {
return 1;
}
public static void main(String j[]) {
Method m = new Method();
System.out.println(m.mm(12, 23));
System.out.println(m.mm(12.0f, 23.0f));
}
In the above case, the compiler will call the second mm method in the second call statement, System.out.println(m.mm(12.0f, 23.0f));
Thus here you see, you can have same return type.
Hope it helps you!
Not, Both methods have the same signature, You can cause the program to become aware of itself and destroy the world. Try something like this:
public int mm(int a ,int b, int op)
{
int result = 0;
switch (op) {
case 1:
result = a + b;
break;
case 2:
result = a * b;
case 3:
result = a - b;
default:
break;
}
return result;
}
public static void main(String [] args)
{
Method m = new Method();
System.out.println( m.mm(5,5,1));
}
For such questions, you should always consult the JLS. So here we go:
§8.4.9. Overloading
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
The same holds true for interfaces:
§9.4.2. Overloading
If two methods of an interface (whether both declared in the same interface, or both inherited by an interface, or one declared and one inherited) have the same name but different signatures that are not override-equivalent (§8.4.2), then the method name is said to be overloaded.
The term "override-equivalent" is explained here:
§8.4.2. Method Signature
Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.
The terms "signature" and "subsignature" are also explained in this paragraph, of which signature is the more important one:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
Summarizing this all, it means that the return type is not part of a method's signature, which also means that different return types are not enough to make methods different (with respect to overloading).
I am trying to understand how Overloading in JAVA works and trying to get grasp of various overloading rules that are applied in case of widening, autoboxing and varargs in JAVA. I am not able to understand what is happening in the following scenario:
package package1;
public class JustAClass {
public static void add(int a, long b) {
System.out.println("all primitives");
}
//public static void add(Integer a, long b) {
// System.out.println("Wraper int, primitive long");
//}
public static void add(int a, Long b) {
System.out.println("Primitive int, Wrapper long");
}
public static void add(Integer a, Long b){
System.out.println("All wrapper");
}
public static void main(String[] args) {
int a = 10;
Integer b = 10;
long c = 9;
Long d = 9l;
add(a,c);
add(a,d);
add(b,c);
add(b,d);
}
}
At this point, I get a compilation error at the third invocation of the add method saying The method is ambiguous for the type Error .
Why is this so? What are the rules for determining which invocation of method will work? What is exactly happening in the following case?
I feel that fourth overloaded add method should work. Please help me understand the concept behind this.
There are 3 stages to method overloading resolution. The first stage doesn't do auto-boxing/unboxing, which means methods that require boxing/unboxing of the passed parameters in order to match one of the overloaded versions of add will only be considered if no match was found that doesn't require boxing/unboxing. That's why 3 of your calls, which have a single exact match, work. Regarding add(b,c);, see below why it's ambiguous.
add(a,c); // exact match to add(int a, long b)
add(a,d); // exact match to add(int a, Long b)
add(b,c); // there is no exact match, so at least one of the passed parameters must
// be boxed or unboxed. However, by unboxing b to int or boxing
// c to Long, each of the three add methods can match, and the
// compiler doesn't know which one to prefer
add(b,d); // exact match to add(Integer a, Long b)
This question already has answers here:
What is the ellipsis (...) for in this method signature?
(5 answers)
Closed 7 years ago.
I was looking through some code and saw the following notation. I'm somewhat unsure what the three dots mean and what you call them.
void doAction(Object...o);
Thanks.
It means that this method can receive more than one Object as a parameter. To better understating check the following example from here:
The ellipsis (...) identifies a variable number of arguments, and is
demonstrated in the following summation method.
static int sum (int ... numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i++)
total += numbers [i];
return total;
}
Call the summation method with as many comma-delimited integer
arguments as you desire -- within the JVM's limits. Some examples: sum
(10, 20) and sum (18, 20, 305, 4).
This is very useful since it permits your method to became more abstract. Check also this nice example from SO, were the user takes advantage of the ... notation to make a method to concatenate string arrays in Java.
Another example from Variable argument method in Java 5
public static void test(int some, String... args) {
System.out.print("\n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
As mention in the comment section:
Also note that if the function passes other parameters of different
types than varargs parameter, the vararg parameter should be the last
parameter in the function declaration public void test (Typev ... v ,
Type1 a, Type2 b) or public void test(Type1 a, Typev ... v
recipientJids, Type2 b) - is illegal. ONLY public void test(Type1 a,
Type2 b, Typev ... v)
It's called VarArgs http://www.javadb.com/using-varargs-in-java. In this case, it means you can put multiple instances of Object as a parameter to doAction() as many as you wants :
doAction(new Object(), new Object(), new Object());
How to initialize the values in constructor that the values cannot be passed by object and that we could pass them from main method?
class ex
{
int a,b;
ex()
{
this.a=b;
}
public static void main(String args[])
{
//here we pass the values to that consructor ex
ex obj=new ex();
}
}
make an overloaded constructor which accepts two arguments.
public ex(int a, int b) {
this.a = a;
this.b = b;
}
public static void main(String...args){
ex obj = new ex(1,2)
}
values canntot be passed by object we should pass from main method
If i understand correctly, you want to pass arguments from the main method and nitialize them in your constructor, the only was to do is by passing them to the constuctor while object creation
You can call setter method from constructor if don't want to display initialization values while declaring new object.
Please see code below for reference :
class Testcl {
int a,b;
Testcl(){
setValues(1,2);
}
private void setValues(int a, int b){
this.a=a;
this.b=b;
}
public static void main(String [] args){
Testcl test = new Testcl();
System.out.println("a : " + test.a + " b : " + test.b);
}}
The first thing to say is that this does actually "work" ... in the sense that it compiles and executes without any errors.
int a,b; // default initialized to 'zero'
ex() {
this.a=b; // assigns 'zsro' to a.
}
But of course, it doesn't achieve anything ... because a is already zero at that point.
Now the main method could assign something to the a and/or b fields after the constructor returns. But there is no way (in pure Java1) to get some non-zero value into b before the constructor is called ... if that is what you are asking.
The practical solution is to just to add a and b arguments to the constructor.
1 - a non-pure Java solution might be to "monkey around" with the bytecodes of the constructor so that it does what you "need" to do. But that's pretty horrible, and horrible solutions have a tendency of coming back to bite you.