Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Duplicating' code so it can be used multiple times in Java

Tags:

java

Is it possible to duplicate a line or multiple lines of code in order to shorten the code a bit? I'm a bit new at Java so I'm attempting to learn how to make myself efficient.

So, for a quick example, I would like to 'duplicate' this line of code to be able to be used in multiple if statements. Just by referencing say, a smaller line of code. Without having to copy paste, etc.

System.out.println("Long paragraph here");

I'm not entirely even sure if this is possible without creating a new file to be referenced. Would this be able to be done easily? Thanks for helping out a newbie. I couldn't find anything in the search because I'm not sure what the term for this would be.

like image 244
nextDouble Avatar asked Jun 13 '26 06:06

nextDouble


1 Answers

You could make a method that takes a string representing that paragraph and then call that method each time you need it:

void printMethod(String paragraph) {
    System.out.println(paragraph);
}

Or if you are always printing the same paragraph:

void printParagraph() {
    System.out.println("Long Paragraph");
}
like image 151
nem035 Avatar answered Jun 14 '26 20:06

nem035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!