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 avoid repeating your code, create a method. For example:



public static void printParagraph() {
    System.out.println("Long paragraph here");
}

      

+4


source


It is good practice, if applicable, to use abstraction and inheritance to avoid code duplication. For example, a behavior (method) can be placed in a parent class and then child classes can inherit the use method.

+1


source







All Articles