Query about return statement!!
we know that a method should always return a value in java if it's signature does not havevoid....but in some programs, i have seen return without anything following it.....ie,
try {
if (args.length==0 || args[0].equalsIgnoreCase("-s")) {
ServerSocket listener = new ServerSocket(port);
System.out.println("Listening on port " + listener.getLocalPort());
connection = listener.accept();
//listener.close();
}
else {
connection = new Socket(args[0],port);
}
out = new PrintWriter(connection.getOutputStream());
out.println(HANDSHAKE);
out.flush();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
message = in.readLine();
if (! message.equals(HANDSHAKE) )
throw new IOException("Connected program is not ChatWindow");
System.out.println("Connected.");
}
catch (Exception e) {
System.out.println("Error opening connection.");
System.out.println(e.toString());
return;
}
What is the use of the return statement inside that catch block?
also if we put a return like this inside a constructor it works fine without giving errors.....
What is the use of these sort of returns?
I found this after a google search:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
The return Statement
The last of the branching statements is the return (in the glossary) statement. You use return to exit from the current method; the flow of control returns to the statement that follows the original method call. The return statement has two forms: (1) one that returns a value and (2) one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
return ++count;
The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.
return;
For information about writing methods for your classes, refer to the Defining Methods (in the Learning the Java Language trail) section.
Hope it helps
Dan
> we know that a method should always return a value in
> java if it's signature does not havevoid....but in
> some programs, i have seen return without anything
> following it.....ie,
Well, this method isn't returning a value, right? So it's completely correct. It returns without delivering something back.