Function taking no arguments Java - java

This does not work
public String getjLabel4text(void){...
But this does
public String getjLabel4text(){...
Why so? I am not taking any arguments so shouldn't I write void there? Why is it causing an error?

More generally, method declarations have six components, in order:
Modifiers—such as public, private, etc.
The return type—the data type of the value returned by the method, or void if the method does not return a value.
The method name—the rules for field names apply to method names as well, but the convention is a little different.
The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
An exception list—to be discussed later.
The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
Oracle Documentation

Java is not like C/C++ You do not need to put void parameter on a function with no parameters, and it throws an error because it is not a valid parameter definition as in java you can not have parameters of type void.

In C and C++ we can take void as an method argument because void is a datatype in both c and c++ . But Java is different, Here void is not a datatype rather its a keyword that is used just to signify method will not return any argument. so taking void as argument is technically invalid and is of no use, this () itself is sufficient.
Ex.
public String Name() { return "Hello";}
and
public String Name(void){ return "Hello";}
In C : Name() will take unspecified no of argument for unspecified type and Name(void) will take no argument.
In C++ : Both Name() and Name(void) will take no argument.
In Java : Name() will work while Name(void) will return compilation error.

There is no need to explicitly mark method as no argument in Java.
You just omit any argument definition and there it is, a method with no arguments.
There is, though a need for return type for any method. It's where void gets in.

void is just for specifying a return value. Declaration of a return type is required for the syntax to work correctly. Since the argument list length is variable, having none is acceptable. void is a keyword, and is not allowed in the argument list.

A method can return a value or not.
public void doSomthing(String text) {
print text;
}
This don't return any value but executes and returns.
public String doSomthing(String text) {
return text;
}
This method returns the text.
You can't input a void.

Related

Cannot find matching method from Groovy to Java

Groovyc: [Static type checking] - Cannot find matching method io.swagger.client.util.EmUtil#addLobList(java.lang.Object, java.lang.Object). Please check if the declared type is correct and if the method exists.
I am calling this function in a static block in groovy, as shown below:
static {
Arrays.asList(LOBEnum.values()).forEach {lob -> EmUtil.getInstance().addLobList(lob.name(), lob.getLob())}
EmUtil.getInstance().setPrefix("CCB_Reference_Data_")
EmUtil.getInstance().init()
}
This calls a java function, as shown below:
public void addLobList(String lob, String licenseLob) {
lobList.add(lob);
lobLicenseList.add(licenseLob);
}
It looks like lob.name() and lob.getLob() each have a return type of Object. If you want to use the return values of those methods as parameters to your addLobList method, the static type checker needs to make sure those are String instance. You can cast those with (String). Alternatively, you could change the return value of those methods to String.

Overloading method with parent type and child type argument and passing null while calling. Why method with childtype argument is getting called [duplicate]

I have added three methods with parameters:
public static void doSomething(Object obj) {
System.out.println("Object called");
}
public static void doSomething(char[] obj) {
System.out.println("Array called");
}
public static void doSomething(Integer obj) {
System.out.println("Integer called");
}
When I am calling doSomething(null) , then compiler throws error as ambiguous methods. So is the issue because Integer and char[] methods or Integer and Object methods?
Java will always try to use the most specific applicable version of a method that's available (see JLS §15.12.2).
Object, char[] and Integer can all take null as a valid value. Therefore all 3 version are applicable, so Java will have to find the most specific one.
Since Object is the super-type of char[], the array version is more specific than the Object-version. So if only those two methods exist, the char[] version will be chosen.
When both the char[] and Integer versions are available, then both of them are more specific than Object but none is more specific than the other, so Java can't decide which one to call. In this case you'll have to explicitly mention which one you want to call by casting the argument to the appropriate type.
Note that in practice this problem occurs far more seldom than one might think. The reason for this is that it only happens when you're explicitly calling a method with null or with a variable of a rather un-specific type (such as Object).
On the contrary, the following invocation would be perfectly unambiguous:
char[] x = null;
doSomething(x);
Although you're still passing the value null, Java knows exactly which method to call, since it will take the type of the variable into account.
Each pair of these three methods is ambiguous by itself when called with a null argument. Because each parameter type is a reference type.
The following are the three ways to call one specific method of yours with null.
doSomething( (Object) null);
doSomething( (Integer) null);
doSomething( (char[]) null);
May I suggest to remove this ambiguity if you actually plan to call these methods with null arguments. Such a design invites errors in the future.
null is a valid value for any of the three types; so the compiler cannot decide which function to use. Use something like doSomething((Object)null) or doSomething((Integer)null) instead.
Every class in Java extends Object class.Even Integer class also extends Object. Hence both Object and Integer are considered as Object instance. So when you pass null as a parameter than compiler gets confused that which object method to call i.e. With parameter Object or parameter Integer since they both are object and their reference can be null. But the primitives in java does not extends Object.
I Have tried this and when there is exactly one pair of overloaded method and one of them has a parameter type Object then the compiler will always select the method with more specific type. But when there is more than one specific type, then the compiler throws an ambiguous method error.
Since this is a compile time event, this can only happen when one intentionally passes null to this method. If this is done intentionally then it is better to overload this method again with no parameter or create another method altogether.
class Sample{
public static void main (String[] args) {
Sample s = new Sample();
s.printVal(null);
}
public static void printVal(Object i){
System.out.println("obj called "+i);
}
public static void printVal(Integer i){
System.out.println("Int called "+i);
}
}
The output is Int called null and so ambiguity is with char[] and Integer
there is an ambiguity because of doSomething(char[] obj) and doSomething(Integer obj).
char[] and Integer both are the same superior for null that's why they are ambiguous.

How to name two variables that have the same meaning but different types

I have a method that parses a String and converts it to a boolean.
The legal values are "true" and "false".
boolean convertStringToBoolean(String text) {
if (text.equals("true") {
return true;
} else if (text.equals("false")) {
return false;
} else {
throw new IllegalArgumentException(text);
}
}
When I use this variable, I get a naming problem.
void doSomething(String isSpecificReadString) {
boolean isSpecificRead = convertStringToBoolean(isSpecificReadString);
...
}
The problem is that the parameter carries a meaning that I want to keep in its name.
The meaning doesn't change just because the type is changed.
So far, my solution has been to just suffix the type to the parameter.
But I don't like this solution.
What should I call the variables to solve this problem?
So far, my solution has been to just suffix the type to the parameter.
But I don't like this solution.
Strongly typed language as Java works in this way.
Variables cannot change their type at runtime.
You have to accept the language constraints.
Converted a data from a type into another type within a method may create this issue.
But your actual solution is rather fine.
The intention is clear and you kept a natural name for the target variable.
You indeed added the type suffix only for the input that will be converted (temporary/intermediary variable), not for the output that will be used in the next statement(s).
As inspired by Andy Turner, I can make two doSomething methods.
A method that takes a String and another that takes a boolean.
The String method can then call the boolean method.
As follows:
void doSomething(String isSpecificRead) {
doSomething(convertStringToBoolean(isSpecificReadString));
}
void doSomething(boolean isSpecificRead) {
...
}

Override toString method in Java

public class Curiosity {
public void toString()//error because of this specific method name
{
System.out.println("method is successfully implemented");
}
}
How can i use a method of the same name "toString()" if i want to ?
Do I have to give its return type as String if not what should i do to change its return type like suppose if i want to use a void return type for toString does java allow that ?
toString() method must return a String. That's the only way to override Object's toString().
public String toString()
{
return "method is successfully implemented";
}
If you wish to use the same name but not override Object's toString, you can overload the name toString by adding arguments, thus changing the signature of your method.
Example :
public void toString (String something)
{
System.out.println("method is successfully implemented " + something);
}
You are trying to overload toString() method in a wrong manner
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
The only way to use toString() in your class is by keeping the return type as String
public String toString()
{
//your code here
}
That is how it is defined in Objectclass and if you wish to override it you will have to use the exact signature
or if you still wish to use the method name as toString what you can do is change the method's signature.
A method's signature includes method's name and the parameters.
Remember that return type is not a part of a method's signature
You can look at the source code of the java.lang.Object.
The toString method have a return value in String type. You can't have another method which's name is toString but return type is not String.
Actually, it's forbidden in Java in any inheritance relationship. When you call the method, the compiler only cares the name and the parameters. So how can it distinguishes the methods of the same name but with the different return type?

return void in a void method?

I know I can do this:
void someMethod(){
return;
}
but I get a syntax error on
void someMethod(){
return void;
}
Why is the latter not allowed? It makes more sense to me.
Edit: I know what a void method is, and that I don't have to return from it at all(and probably shouldn't, in most cases) but I don't understand why I can't return void from a void method. In my opinion, there should be no keyword in the method declaration (like constructors) if the you are able to write return;.
I think both are to be shunned. I prefer this:
void someMethod() {
// do stuff; no return at bottom
}
I'd be willing to be that you'd find lots of methods in the JDK source code that look like this.
When you declare a method as void, you're saying that the method does not return a value. Attempting to return a value, therefore, is illegal. Additionally, return void; has a syntax error because void is not (indeed, cannot be) the name of an in-scope variable.
void is a type, not an expression, so trying to write return void is the same as trying to write return int: syntactically invalid.
When you call return void;, you are using a reserved keyword in the incorrect manner. Since it would not expect the keyword void in that manner, it would cause an error.
The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the Java keyword void.
If you would prefer to return something, then you can return null; by parameterizing a type Void like in this answer, but that's unconventional. Best bet is to omit return altogether or just say return;.
return x; indicates that control is leaving the method and that its result is the value of x.
return; indicates that control is leaving the method without a result.
The type void is a type with zero values, so for void methods there is no x such that return x makes sense.
All non-void methods must do one of three things:
Fail to exit ever.
Finish abnormally with an exception.
Finish normally with zero or one return values.
Since void is the only type with zero possible values (Classes with private uncalled ctors don't count because of null), there is no possible return in a non-void method such that return makes sense.

Categories