Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we have a newline after method name in Java?

Tags:

java

This is one doubt regarding best practice in Java. Is it good idea to leave a blank line after method name. Eg. say I have following code

public void print(String str) {
    System.out.println("Hello word" + str);
}

So, here is it good practice to leave a blank line before Print statement? I checked Java doc regarding that. http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html

It says, Blank should be :- Between the local variables in a method and its first statement

I am not sure if it means the same thing that I am asking or it is something else.

Anything you can tell would be great.

like image 603
hatellla Avatar asked Jun 23 '17 01:06

hatellla


People also ask

How do you call a method in Java?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;).

Where should you put blank lines in your Java programs?

Blank lines improve readability by setting off sections of code that are logically related. Two blank lines should always be used in the following circumstances: Between sections of a source file. Between class and interface definitions.

How do you do a line break in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


2 Answers

The standard doesn't apply in your case because you have no local variables. So I'd say

// YES
public void print(String str) {
    System.out.println("Hello word" + str);
}

is just fine. Much better than:

// NO
public void print(String str) {
                                      // This blank line is unnecessary
    System.out.println("Hello word" + str);
}

The standard is talking about something like this:

// YES
public void print(String str) {
    double rand = Math.random(100);
                                        // A blank here is good
    System.out.println("Hello word" + str + "; today's number is " + rand);
}

being preferred over

// NO
public void print(String str) {
    double rand = Math.random(100);
    System.out.println("Hello word" + str + "; today's number is " + rand);
}
like image 173
Kevin Anderson Avatar answered Sep 17 '22 13:09

Kevin Anderson


Short answer: No. That piece of the standard is meaning that you should leave a gap between the local variables and the first statement inside the method.

i.e:

String someText = "text";
String moreText = "more text";
// gap here
System.out.println(someText + " " + anotherText);
like image 29
axwr Avatar answered Sep 18 '22 13:09

axwr