I have a few confusions about writing Java code, and I need some clarifications:
import java.util.Scanner;
public class NameAbbreviation {
private static String fullName;
private static Scanner nameInput;
public NameAbbreviation(String name) {
NameAbbreviation.fullName = name;
}
public char getInitialLetterOfFirstName() {
char initialletterOfFirstName = fullName.charAt(0);
return initialletterOfFirstName;
}
public String getInitialLetterOfLastName() {
int space = fullName.lastIndexOf(" ");
String initialletterOfLastName = fullName.substring(space + 1,
space + 2);
return initialletterOfLastName;
}
public static void main(String[] args) {
nameInput = new Scanner(System.in);
String name = nameInput.nextLine();
NameAbbreviation na = new NameAbbreviation(name);
System.out.println(na.getInitialLetterOfFirstName() + " "
+ na.getInitialLetterOfLastName());
}
}
I have class variables
fullName and
nameInput. If I make
nameInput local, it shows: "Resource leak: nameInput is never closed." So I just follow the Eclipse suggestion and make it a field. What should I need to follow?
I have 2 methods -
getInitialLetterOfFirstName()
and
getInitialLetterOfLastName()
, the return types of which are "char" and "String" respectively. I could eventually make the return type as void. What are the advantages or disadvantages if I have void or specific return type? As both the way of code works, what do I need to follow or does it depend on how I am writing the code?
Both the methods
getInitialLetterOfFirstName()
and
getInitialLetterOfLastName()
don't have any parameters/arguments. I could eventually create the method with argument like:
getInitialLetterOfFirstName(String name) {
this.fullName = name; .......}
getInitialLetterOfLastName(String name) {
this.fullName = name; .......}
If I create the methods with arguments, I need to pass the value during the instantiation of the object. So I avoid it here, and prefer to have only once to pass the argument value.
Is there any rule to follow, like to make the methods with parameters or not, as here both are possible with or without argument methods?
What do I need to follow as good practice, code performance issues, etc.?