| Line 3: |
Line 3: |
| | ===With apt=== | | ===With apt=== |
| | <nowiki>sudo apt-add-repository ppa:webupd8team/java | | <nowiki>sudo apt-add-repository ppa:webupd8team/java |
| − | sudo apt-get update
| + | sudo apt-get update |
| − | sudo apt-get install oracle-java8-installer</nowiki>
| + | sudo apt-get install oracle-java8-installer</nowiki> |
| | | | |
| | Also ensure your JAVA_HOME variable has been set to: | | Also ensure your JAVA_HOME variable has been set to: |
| Line 79: |
Line 79: |
| | System.out.println("My integer is: " + myInt); | | System.out.println("My integer is: " + myInt); |
| | } | | } |
| − | }</source> | + | }</source><syntaxhighlight lang="java"> |
| | + | //Java 11 |
| | + | " ".isBlank(); // --> true |
| | + | " lr ".strip(); //Java 11 |
| | + | " lr ".stripLeading().replace(" ", "@"); |
| | + | " lr ".stripTrailing().replace(" ", "@"); |
| | + | "line1\nline2\nline3".lines().forEach(System.out::println); |
| | + | |
| | + | //Java 12 |
| | + | "UPPER".transform(s -> s.substring(2)); |
| | + | |
| | + | //Java 13 |
| | + | "My name is %s. My age is %d".formatted("Rafa", 40); |
| | + | |
| | + | //Java 14 |
| | + | |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | ==Enum type== | | ==Enum type== |
| | See code example:<br /> | | See code example:<br /> |
| Line 279: |
Line 297: |
| | words.contains("Dog"); | | words.contains("Dog"); |
| | words.indexOf("Cat"); | | words.indexOf("Cat"); |
| − | </syntaxhighlight> | + | </syntaxhighlight>List.of() and List.copyOf() creates unmodifiable lists copyOf is introduced on Java 10 |
| | | | |
| | ===ArrayList=== | | ===ArrayList=== |
| Line 791: |
Line 809: |
| | ===Reading text files=== | | ===Reading text files=== |
| | See: [https://github.com/rafahsolis/javaTutorial/blob/master/ReadTextFile.java ReadTextFile.java] | | See: [https://github.com/rafahsolis/javaTutorial/blob/master/ReadTextFile.java ReadTextFile.java] |
| | + | |
| | + | ===List files in dir=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.io.IOException; |
| | + | import java.nio.file.Files; |
| | + | import java.nio.file.Paths; |
| | + | import java.util.function.Predicate; |
| | + | |
| | + | Path currentDirectory = Paths.get("."); |
| | + | Files.list(currentDirectory).forEach(System.out::println); |
| | + | |
| | + | int levels = 5; |
| | + | Files.walk(currentDirectory, levels).forEach(System.out::println); |
| | + | |
| | + | // list only .java files |
| | + | Predicate<? super Path> predicate = path -> String.valueOf(path).contains(".java"); |
| | + | Files.walk(currentDirectory, levels).filter(predicate).forEach(System.out::println); |
| | + | |
| | + | // Search files |
| | + | BiPredicate<Path, BasicFileAttributes> javaMatcher = (path, attributes) -> String.valueOf(path).contains(".java"); |
| | + | Files.find(currentDirectory, levels, javaMatcher).forEach(System.out::println); |
| | + | |
| | + | BiPredicate<Path, BasicFileAttributes> dirMatcher = (path, attributes) -> attributes.isDirectory(); |
| | + | Files.find(currentDirectory, levels, dirMatcher).forEach(System.out::println); |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | ===Reading files (Try-With-Resources)=== | | ===Reading files (Try-With-Resources)=== |
| | This requires at least Java 7<br /> | | This requires at least Java 7<br /> |
| Line 860: |
Line 905: |
| | }</source> | | }</source> |
| | | | |
| | + | ===with nio=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.io.IOException; |
| | + | import java.nio.file.Files; |
| | + | import java.nio.file.Path; |
| | + | import java.nio.file.Paths; |
| | + | import java.util.List; |
| | + | |
| | + | public class FileReadRunner { |
| | + | public static void main(String[] args) throws IOException { |
| | + | Path pathFileToRead = Paths.get("./resources/data.txt"); |
| | + | List<String> lines= Files.readAllLines(pathFileToRead); |
| | + | System.out.println(lines); |
| | + | } |
| | + | } |
| | + | |
| | + | public class FileReadLineByLineRunner { |
| | + | public static void main(String[] args) throws IOException { |
| | + | Path pathFileToRead = Paths.get("./resources/data.txt"); |
| | + | Files.lines(pathFileToRead).forEach(System.out::println); |
| | + | Files.lines(pathFileToRead).map(String::toLowerCase).forEach(System.out::println); |
| | + | Files.lines(pathFileToRead).map(String::toLowerCase).filter(str -> str.contains("a")).forEach(System.out::println); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight><br /> |
| | ===Writing files=== | | ===Writing files=== |
| | <source lang="java"> | | <source lang="java"> |
| Line 887: |
Line 957: |
| | } | | } |
| | | | |
| − | }</source> | + | }</source><syntaxhighlight lang="java"> |
| | + | import java.io.IOException; |
| | + | |
| | + | public class FileWriteRunner { |
| | + | public static void main(String[] args){ |
| | + | Path filePath = Paths.get("./resources/filetowrite.txt"); |
| | + | List<String> list = List.of("Apfel", "Junge", "Hund"); |
| | + | Files.write(filePath, list); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===readString writeString (Java 11)=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.io.IOException; |
| | + | import java.nio.file.Files; |
| | + | import java.nio.file.Path; |
| | + | import java.nio.file.Paths; |
| | + | |
| | + | public class FileReadWriteRunner { |
| | + | public static void main(String[] args) throws IOException { |
| | + | |
| | + | // Read |
| | + | Path path = Paths.get("./file.txt"); |
| | + | String fileContent = Files.readString(path); |
| | + | System.out.println(fileContent); |
| | + | |
| | + | // Write |
| | + | String newFileContent = fileContent.replace("Line", "Lines"); |
| | + | Path path = Paths.get("./newfile.txt"); |
| | + | Files.writeString(newFilePath, newFileContent); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | | | |
| | ==Anonymous class== | | ==Anonymous class== |
| Line 893: |
Line 996: |
| | ==Exceptions== | | ==Exceptions== |
| | [http://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html Class Exception] | | [http://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html Class Exception] |
| | + | |
| | + | [https://github.com/in28minutes/in28minutes-initiatives/blob/master/The-in28Minutes-TroubleshootingGuide-And-FAQ/quick-start.md Exception Troubleshooting] |
| | ===trows=== | | ===trows=== |
| | <source lang="java"> | | <source lang="java"> |
| Line 902: |
Line 1,007: |
| | | | |
| | public class HandlingExceptions { | | public class HandlingExceptions { |
| | + | public static void main(String[] args) trows FileNotFoundException { |
| | + | File file = new File("test.txt"); |
| | + | FileReader fr = new FileReader(file); |
| | + | throw new RuntimeException("Example exception throwing"); |
| | + | } |
| | + | } |
| | + | |
| | + | // To throw Exception instead of RuntimeException you need to explicit specify your class throws an exception: |
| | + | public class HandlingExceptions throws Exception { |
| | public static void main(String[] args) trows FileNotFoundException { | | public static void main(String[] args) trows FileNotFoundException { |
| | File file = new File("test.txt"); | | File file = new File("test.txt"); |
| | FileReader fr = new FileReader(file); | | FileReader fr = new FileReader(file); |
| | throw new Exception("Example exception throwing"); | | throw new Exception("Example exception throwing"); |
| | + | } |
| | + | } |
| | + | |
| | + | // Custom exception |
| | + | class CustomException extends Exception { |
| | + | } |
| | + | |
| | + | class CustomException1 extends Exception { |
| | + | public CustomException1() |
| | + | } |
| | + | |
| | + | public class CustomExceptionRunner { |
| | + | public void static main(String[], args) throws CustomException { |
| | + | throw new CustomException("Some text"); |
| | } | | } |
| | }</source> | | }</source> |
| Line 951: |
Line 1,079: |
| | } | | } |
| | }</source> | | }</source> |
| | + | |
| | + | ===Try with resources (similar to python with)=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.Scanner; |
| | + | |
| | + | public class TryWithResourcesRunner { |
| | + | public static void main(String[] args){ |
| | + | try (Scanner scanner = new Scanner(System.in)){ |
| | + | int[] numbers = {12, 3, 4, 5}; |
| | + | int number = numbers[21]; |
| | + | } |
| | + | // this will throw an exception but scanner will be closed |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===catch multiple exceptions=== |
| | + | <syntaxhighlight lang="java"> |
| | + | try { |
| | + | // code |
| | + | } catch (IOException | SQLException ex) { |
| | + | ex.printStackTrace(); |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | ===Runtime exceptions=== | | ===Runtime exceptions=== |
| | The compiler does not force you to handle them. | | The compiler does not force you to handle them. |
| Line 1,163: |
Line 1,316: |
| | </syntaxhighlight> | | </syntaxhighlight> |
| | | | |
| | + | ==Concurrency== |
| | + | |
| | + | ===syncrhronized=== |
| | + | If there are multiple synchronized methods on an instance only one of them can be run by threads at one point in time<syntaxhighlight lang="java"> |
| | + | public class Counter { |
| | + | private int i = 0; |
| | + | |
| | + | synchronized public void increment() { // synchronized keyword: only one thread can run at same time |
| | + | i++; // get; increment; set (Not atomic, not thread safe if not synchronized) |
| | + | } |
| | + | public int getI(){ |
| | + | return i; |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Locks=== |
| | + | Solve the multiple synchronized methods on same instance (apart from ReentrantLock thre are TryLock and TryForLock)<syntaxhighlight lang="java"> |
| | + | import java.util.concurrent.locks.ReentrantLock; |
| | + | |
| | + | public class BiCounterWithLock { |
| | + | private int i = 0; |
| | + | private int j = 0; |
| | + | Lock lockForI = new ReentrantLock(); |
| | + | Lock lockForJ = new ReentrantLock(); |
| | + | |
| | + | public void incrementI() { |
| | + | lockForI.lock(); |
| | + | i++; |
| | + | lockForI.unlock(); |
| | + | } |
| | + | public int getI(){ |
| | + | return i; |
| | + | } |
| | + | public void incrementJ() { |
| | + | lockForJ.lock(); |
| | + | j++; |
| | + | lockForJ.unlock(); |
| | + | } |
| | + | public int getJ(){ |
| | + | return j; |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Atomic classes=== |
| | + | Solves the same problem as locks but for simple operators (AtomicInteger, AtomicBoolean, AtomicIntegerArray, AtomicLong, AtomicBoolean....)<syntaxhighlight lang="java"> |
| | + | import java.util.concurrent.atomic.AtomicInteger; |
| | + | |
| | + | public class BiCounterWithLock { |
| | + | private AtomicInteger i = new AtomicInteger(); |
| | + | private AtomicInteger j = new AtomicInteger(); |
| | + | |
| | + | |
| | + | public void incrementI() { |
| | + | i.incrementAndGet(); |
| | + | } |
| | + | public int getI(){ |
| | + | return i.get(); |
| | + | } |
| | + | public void incrementJ() { |
| | + | j.incrementAndGet(); |
| | + | } |
| | + | public int getJ(){ |
| | + | return j.get(); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Concurrent collections=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.Hashtable; |
| | + | import java.util.Map; |
| | + | import java.util.concurrent.atomic.LongAdder; |
| | + | import java.util.concurrent.ConcurrentMap; |
| | + | import java.util.concurrent.ConcurrentHashMap; |
| | + | |
| | + | // Not thread safe!!! |
| | + | public class MapRunner{ |
| | + | Map<Character, LongAdder> occurrances = new HashTable<>(); |
| | + | |
| | + | String str = "ABCD ABCD ABCD"; |
| | + | for (char character:str.toCharArray()){ |
| | + | LongAdder longAdder = ocurrances.get(character); |
| | + | if (longAdder==null) { |
| | + | longAdder = new LongAdder(); |
| | + | } |
| | + | longAdder.increment(); |
| | + | occurrances.put(character, longAdder); |
| | + | } |
| | + | System.out.println(occurrances); |
| | + | } |
| | + | |
| | + | |
| | + | // Thread safe |
| | + | public class ConcurrentMapRunner{ |
| | + | ConcurrentMap<Character, LongAdder> occurrances = new ConcurrentHashMap<>(); |
| | + | |
| | + | String str = "ABCD ABCD ABCD"; |
| | + | for (char character:str.toCharArray()){ |
| | + | occurances.computeIfAbsent(character, ch -> new LongAdder()).increment(); |
| | + | } |
| | + | System.out.println(occurrances); |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===CopyOnWriteArrayList=== |
| | + | Expensive write, fast concurrent read, synchronized writes, free reads. <syntaxhighlight lang="java"> |
| | + | import java.utils.List; |
| | + | import java.util.concurrent.CopyOnWriteArrayList; |
| | + | |
| | + | public class CopyOnWriteArrayListRunner { |
| | + | List<String> list = new CopyOnWriteArrayList<>(); |
| | + | |
| | + | // Threads -3 |
| | + | list.add("Ant"); |
| | + | list.add("Bat"); |
| | + | list.add("Cat"); |
| | + | |
| | + | // Threads - 10000 |
| | + | for (String element:list){ |
| | + | System.out.println(element); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ==Java tips== |
| | + | |
| | + | ===Static imports=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import static java.lang.System.out; |
| | + | import static java.util.Collections.*; |
| | + | |
| | + | out.println("System.out.printl System not needed"); |
| | + | |
| | + | sort(new ArrayList<String>()); |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Blocks=== |
| | + | <syntaxhighlight lang="java"> |
| | + | pubublic class BlocksRunner { |
| | + | public static void main(String[] args){ |
| | + | { |
| | + | int i; |
| | + | System.out.println("i can be accessed here: " + i); |
| | + | } |
| | + | System.out.println("i can not be accessed here") |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===equals and hashCode methods from an object=== |
| | + | 2 objects only obj.equals if they are the same object, but equals can be overriden (generate hashcode and equals) |
| | + | |
| | + | Hash function should return the same value if 2 objects are equal |
| | + | |
| | + | ===Access modifiers=== |
| | + | public: accessible every where. |
| | + | |
| | + | protected: accessible in same package or subclasses. |
| | + | |
| | + | (default): only inside the class or package. |
| | + | |
| | + | private: only inside the class. |
| | + | |
| | + | ===non access modifier=== |
| | + | |
| | + | ====final==== |
| | + | final classes can not be extended. |
| | + | |
| | + | final methods can not be overridden. |
| | + | |
| | + | final variable can not change (Constants). |
| | + | |
| | + | final argument can not be changed. |
| | + | |
| | + | ====static==== |
| | + | static class variables are common to all class instances. |
| | + | |
| | + | static methods can be called from class, no need for instance, inside static methods instance variables or methods are not accessible. |
| | + | |
| | + | ====Constants==== |
| | + | public static final |
| | + | |
| | + | ====Enums==== |
| | + | like: java.time.Month, java.time.DayOfWeek<syntaxhighlight lang="java"> |
| | + | enum Season { |
| | + | WINTER, SPRING, SUMMER, FALL; |
| | + | |
| | + | // to store in db |
| | + | private int value; |
| | + | WINTER(1), SPRING(2), SUMMER(3), FALL(4); |
| | + | |
| | + | private Season(int value){ |
| | + | this.value = value; |
| | + | } |
| | + | } |
| | + | |
| | + | public class EnumRunner{ |
| | + | public static void main(String[] args){ |
| | + | Season season = Season.WINTER; |
| | + | Season season1 = Season.valueOf("WINTER"); |
| | + | |
| | + | System.out.print(season1); |
| | + | System.out.print(Season.SPRING.ordinal()); |
| | + | System.out.print(Season.SPRING.getValue()); |
| | + | System.out.print(Arrays.toString(Season.values())); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ====module-info.java==== |
| | + | requires: allows usage of other modules |
| | + | |
| | + | requires transitive: allows usage of other modules and modules that use this module will also have access to it |
| | + | |
| | + | exports: allows other packages to use your classes |
| | + | <br /> |
| | + | |
| | + | ==Predicate Not== |
| | + | Java 11<syntaxhighlight lang="java"> |
| | + | import java.util.List; |
| | + | import java.util.function.Predicate; |
| | + | |
| | + | public class PredicateNotRunner { |
| | + | public static boolean isEven(Integer number){ |
| | + | return number&2==0; |
| | + | } |
| | + | public static void main(String[] args){ |
| | + | List<Integer> numbers = List.of(3, 4, 5, 57, 65, 88); |
| | + | // Predicate<Integer> evenNumberPredicate = number -> number%2==0; |
| | + | // numbers.stream().filter(evenNumberPredicate).forEach(System.out::println); |
| | + | |
| | + | numbers.stream().filter(Predicate.not(PredicateNotRunner::isEven)).forEach(System.out::println); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ==Sort strings== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.ArrayList; |
| | + | import java.util.Collections; |
| | + | import java.util.List; |
| | + | import java.util.Comparator; |
| | + | |
| | + | class LengthComparator implements Comparator<String> { |
| | + | @Override |
| | + | public int compare(String str1, String str2){ |
| | + | return Integer.compare(str1.length(), str2.length()); |
| | + | } |
| | + | } |
| | + | |
| | + | public class AnonymousClassRunner{ |
| | + | public static void main(String args){ |
| | + | List<String> animals = new ArrayList<String>(List.of("Ant", "Cat", "Ball", "Elephant")); |
| | + | // Collections.sort(animals); //Alphabetical order |
| | + | Collections.sort(animals, new LengthComparator()); //Length order |
| | + | System.out.println(animals); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ==Logger== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.logging.Logger |
| | + | |
| | + | public class BubbleSort { |
| | + | public List<String> sort(List<String> names){ |
| | + | return names; |
| | + | } |
| | + | } |
| | + | |
| | + | public class MySortingUtil { |
| | + | public List<String> sort(List<String> names){ |
| | + | BubbleSort bubbleSort = new BubbleSort(); |
| | + | return bubbleSort.sort(names); |
| | + | } |
| | + | } |
| | + | |
| | + | public class MySortingUtilConsumer { |
| | + | private static Logger logger = Logger.getLogger(MySortingUtilConsumer.class.getName()); |
| | + | |
| | + | public static void main(String args){ |
| | + | MySortingUtil util = MySortingUtil(); |
| | + | List<String> sorted = util.sort(List.of("Elephant", "Bat", "Mosquito")); |
| | + | logger.info(sorted.toString()); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight><br /> |
| | ==Eclipse shortcuts== | | ==Eclipse shortcuts== |
| | Ctrl + Space → Autocomplete.<br /> | | Ctrl + Space → Autocomplete.<br /> |
| Line 1,172: |
Line 1,614: |
| | ==Notes== | | ==Notes== |
| | Hibernate → Java ORM framework for web design | | Hibernate → Java ORM framework for web design |
| | + | |
| | + | ==java cli== |
| | + | <syntaxhighlight lang="bash"> |
| | + | # Compile class |
| | + | javac someclass.java |
| | + | |
| | + | # List modules |
| | + | java --list-modules |
| | + | |
| | + | # Java shell |
| | + | jshell |
| | + | |
| | + | # Run java application |
| | + | java -jar someclass.jar |
| | + | |
| | + | # List module dependencies |
| | + | java -d java.sql |
| | + | |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ==Frameworks== |
| | + | [[Java: Spring|Spring]] |
| | + | |
| | + | ==Java and Eclipse troubleshooting== |
| | + | |
| | + | ====Default Home Folder for JDK==== |
| | + | |
| | + | *Windows: C:\Program Files\Java\jdk-{version} |
| | + | **Example for JDK 16 - C:\Program Files\Java\jdk-16 |
| | + | **Example for JDK 17 - C:\Program Files\Java\jdk-17 |
| | + | *Mac: /Library/Java/JavaVirtualMachines/jdk-{version}.jdk/Contents/Home |
| | + | **Example for JDK 16 - /Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home |
| | + | **Example for JDK 17 - /Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home |
| | + | |
| | + | ====Default Home Folder for JDK==== |
| | + | |
| | + | *Windows: C:\Program Files\Java\jdk-{version}\bin |
| | + | **Example for JDK 16 - C:\Program Files\Java\jdk-16\bin |
| | + | *Mac: /Library/Java/JavaVirtualMachines/jdk-{version}.jdk/Contents/Home/bin |
| | + | **Example for JDK 16 - /Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home/bin |
| | + | |
| | + | [[Category:Java]] |