The code is "Duplicate" so it can be used multiple times in Java
Is it possible to duplicate a line or multiple lines of code to shorten the code a bit? I'm a bit new to Java, so I'm trying to figure out how to make myself efficient.
So, for a quick example, I would like to "duplicate" this line of code so that it can be used in multiple if statements. Just by referencing for example a smaller line of code. No copy paste, etc.
System.out.println("Long paragraph here");
I'm not entirely sure if this is possible without creating a new file to link. Can this be done easily? Thanks for helping newbies. I couldn't find anything in the search because I'm not sure what the term is.
+3
source to share
3 answers
You can create a method that takes the string that represents this paragraph and then call that method whenever you need it:
void printMethod(String paragraph) {
System.out.println(paragraph);
}
Or, if you always type the same paragraph:
void printParagraph() {
System.out.println("Long Paragraph");
}
+5
source to share