|
|||||||||||||
Java
General Tips and Best Practices |
Corretto, Open JDK Java for AWS [edit]
Amazon Web Service (AWS) have their own flavor of Linux, and so they tend to offer variants of popular packages especially tuned for Amazon Linux, Linux 2, Linux 2023 (at least as of 2023).
Elsewhere
Scanner, Keyboard Input Quirks
For programs that may prompt users multiple times for keyboard input, sometime it is unclear if the scanner buffer is rereading input already provided. To avoid that, it may make sense to reset the scanner using new which will flush the buffer and make sure the next token is something new from the keyboard.
import java.util.Scanner; // console input needs this public class ScannerTest { public static void main(String[] args) { // Creates a Scanner object Scanner input = new Scanner(System.in); String s1; System.out.print("Type the string 'test' [press return]: "); while(input.hasNext("test") == false) { System.out.print("try again [press return]: "); s1 = input.nextLine(); } // this CLEARS the keyboard queue, weird input triggers without this input = new Scanner(System.in); System.out.print("Type any string for a product name [press return]: "); s1 = input.nextLine(); System.out.print("You typed: " + s1); } }
Elsewhere
Except for File that contains main(), Single Class / Source Code File
For the most pat, Java enforces a single source code file per class. However an exception to this is the source code file that contains the main() function, the start up code for any Java program. The source code file that contains the main() method may have unlimited other classes also defined in the same file, which though unwieldy can allow simple programs to use polymorphism and other tiered class heirachies without needing multiple source code files.
Lambda Expressions, Using :: (double colon), and Related Syntax Sugar
The stream operation in Java allows for lists/arrays/... to have an operation applied to each element. With parallel computing, such statements are easier for multi-core computers to parallelize ( process faster). To further shorten the syntax for operations to be done to each element in a list double colon syntax is permitted.
These do the same thing,
stream.forEach(s -> System.out.println(s));
one uses the shorter double colon syntax
stream.forEach(System.out::println);
Elsewhere: GeeksforGeeks, interface vs class
Miscellaneous