| Line 1: |
Line 1: |
| − | == hello world == | + | All the code can be found at: [https://github.com/rafahsolis/javaTutorial javaTutorial] |
| | + | ==Install== |
| | + | ===With apt=== |
| | + | <nowiki>sudo apt-add-repository ppa:webupd8team/java |
| | + | sudo apt-get update |
| | + | sudo apt-get install oracle-java8-installer</nowiki> |
| | + | |
| | + | Also ensure your JAVA_HOME variable has been set to: |
| | + | /usr/lib/jvm/java-8-oracle |
| | + | |
| | + | ===From Source=== |
| | + | wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u5-b13/jdk-8u5-linux-x64.tar.gz |
| | + | sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/oracle_jdk8/jre/bin/java 2000 |
| | + | sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/oracle_jdk8/bin/javac 2000 |
| | + | update-alternatives --display java |
| | + | update-alternatives --display javac |
| | + | |
| | + | ==hello world== |
| | <source lang="java"> | | <source lang="java"> |
| | public class aplication { | | public class aplication { |
| Line 10: |
Line 27: |
| | | | |
| | }</source> | | }</source> |
| − | == variables == | + | ==Numeric variables== |
| | <source lang="java"> | | <source lang="java"> |
| | public class variables { | | public class variables { |
| Line 28: |
Line 45: |
| | | | |
| | }</source> | | }</source> |
| − | == Strings == | + | |
| | + | ==Data types== |
| | + | byte b; byte (8 bits) |
| | + | |
| | + | short s; short (16 bits) |
| | + | |
| | + | int i; Integer (32 bits) |
| | + | |
| | + | long lo; long (64 bits) |
| | + | |
| | + | float f=4.0f; (32 bits) Not precise use big decimal instead |
| | + | |
| | + | double d; (64 bits) Not precise use big decimal instead |
| | + | |
| | + | char c; (16 bits) |
| | + | |
| | + | String st; String |
| | + | |
| | + | boolean isTrue; true/false |
| | + | |
| | + | Todo: Arrays etc... |
| | + | |
| | + | ==Strings== |
| | <source lang="java"> | | <source lang="java"> |
| | public class stringstuto { | | public class stringstuto { |
| Line 40: |
Line 79: |
| | System.out.println("My integer is: " + myInt); | | System.out.println("My integer is: " + myInt); |
| | } | | } |
| − | }</source> | + | }</source><syntaxhighlight lang="java"> |
| − | == Loops == | + | //Java 11 |
| − | === While === | + | " ".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== |
| | + | See code example:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/EnumTypes.java EnumTypes.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Animal.java Animal.java]<br /> |
| | + | |
| | + | ==Operators== |
| | + | ===Asignment=== |
| | + | = Asignment |
| | + | ===Arithmetic=== |
| | + | + Additive<br /> |
| | + | - Substraction<br /> |
| | + | * Multiplication |
| | + | / Division<br /> |
| | + | % Remainder<br /> |
| | + | |
| | + | ===Increment / Decrement=== |
| | + | ++ Increment<br /> |
| | + | -- Decrement |
| | + | |
| | + | += 1 Increment by one |
| | + | |
| | + | -= 1 Decrement by one |
| | + | |
| | + | /=2 Divide by 2 |
| | + | |
| | + | <nowiki>*</nowiki>= 2 multiplied by 2<br /> |
| | + | ===Logic=== |
| | + | == Equal to (*)<br /> |
| | + | != Not Equal to<br /> |
| | + | > Greater than<br /> |
| | + | >= Greater than or equal to<br /> |
| | + | < Less than<br /> |
| | + | <= Less than or equal to<br /> |
| | + | && Conditional-AND<br /> |
| | + | || Conditional-OR<br /> |
| | + | ?: Ternary (shorthand for if-then-else statement: CONDITION? VALUE_IF_TRUE : VALUE_IF_FALSE)<syntaxhighlight lang="java"> |
| | + | int number = 2; |
| | + | boolean isEven = ( number % 2 == 0 ? true : false) |
| | + | </syntaxhighlight><br /> |
| | + | <br /> |
| | + | (*) Check .equals()<br /> |
| | + | ===Bitwise and Bit Shift Operators=== |
| | + | ~ Unary bitwise complement<br /> |
| | + | << Signed left shift<br /> |
| | + | >> Signed right shift<br /> |
| | + | >>> Unsigned right shift<br /> |
| | + | & Bitwise AND<br /> |
| | + | ^ Bitwise exclusive OR<br /> |
| | + | | Bitwise inclusive OR<br /> |
| | + | ===Type comparison operator=== |
| | + | instanceof |
| | + | |
| | + | ==Loops== |
| | + | ===While=== |
| | <source lang="java"> | | <source lang="java"> |
| | int myInt = 0; | | int myInt = 0; |
| Line 51: |
Line 160: |
| | }</source> | | }</source> |
| | | | |
| − | === For === | + | ===For=== |
| | <source lang="java"> | | <source lang="java"> |
| | for(int i=0; i<5;i++){ | | for(int i=0; i<5;i++){ |
| | System.out.printf("The value of i is %d\n", i); | | System.out.printf("The value of i is %d\n", i); |
| | }</source> | | }</source> |
| − | === Do While === | + | ===Do While=== |
| | <source lang="java"> | | <source lang="java"> |
| | public static void main(String[] args) { | | public static void main(String[] args) { |
| Line 70: |
Line 179: |
| | }</source> | | }</source> |
| | | | |
| − | == Conditional == | + | ==Conditional== |
| − | === if === | + | ===if=== |
| | <source lang="java"> | | <source lang="java"> |
| | int value = 20; | | int value = 20; |
| Line 85: |
Line 194: |
| | }</source> | | }</source> |
| | | | |
| − | === switch case === | + | ===switch case=== |
| | <source lang="java"> | | <source lang="java"> |
| | switch(VariableIntOrString){ | | switch(VariableIntOrString){ |
| Line 100: |
Line 209: |
| | }</source> | | }</source> |
| | | | |
| − | == User Input == | + | ==User Input== |
| | <source lang="java"> | | <source lang="java"> |
| | import java.util.Scanner; | | import java.util.Scanner; |
| Line 123: |
Line 232: |
| | | | |
| | *Note: Ctrl + Shift + O in eclipse adds all the imports you need. | | *Note: Ctrl + Shift + O in eclipse adds all the imports you need. |
| − | == Arrays == | + | |
| | + | ==Arrays== |
| | <source lang="java"> | | <source lang="java"> |
| | int[] values; | | int[] values; |
| Line 132: |
Line 242: |
| | | | |
| | values.length; → returns the array lenght<br /> | | values.length; → returns the array lenght<br /> |
| − | === Iterating trough an array === | + | ===Iterating trough an array=== |
| | <source lang="java"> | | <source lang="java"> |
| | String[] fruits = {"apple", "banana", "pear", "kiwi"}; | | String[] fruits = {"apple", "banana", "pear", "kiwi"}; |
| Line 139: |
Line 249: |
| | } | | } |
| | </source> | | </source> |
| − | === Multidimensional arrays === | + | |
| | + | ===Fill array=== |
| | + | <syntaxhighlight lang="java"> |
| | + | int[] marks = new int[5] |
| | + | Arrays.fill(marks, 100) |
| | + | </syntaxhighlight> |
| | + | |
| | + | ====Other==== |
| | + | <syntaxhighlight lang="java"> |
| | + | Arrays.equals(array1, array2) // Compare 2 arrays |
| | + | Arrays.sort(array1) // Sort array |
| | + | </syntaxhighlight> |
| | + | |
| | + | ====Array of arguments==== |
| | + | <syntaxhighlight lang="java"> |
| | + | void print(int... values) { |
| | + | System.out.print(Arrays.toString(values)); |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Multidimensional arrays=== |
| | <source lang="java"> | | <source lang="java"> |
| | int[][] grid = { | | int[][] grid = { |
| Line 150: |
Line 280: |
| | </source> | | </source> |
| | | | |
| − | == Eclipse shortcuts == | + | ==Collections== |
| | + | List: Can't add elements. |
| | + | |
| | + | ArrayList: Access very slow, efficient insert and delete |
| | + | |
| | + | LinkedList: Iteration very slow faster insertion and deletion |
| | + | |
| | + | Vector: Thread safe (syncronized) |
| | + | |
| | + | ===List=== |
| | + | <syntaxhighlight lang="java"> |
| | + | List<String> words = List.of("Apple", "Bat", "Cat"); |
| | + | words.size(); |
| | + | words.isEmpty(); |
| | + | words.get(0); |
| | + | words.contains("Dog"); |
| | + | words.indexOf("Cat"); |
| | + | </syntaxhighlight>List.of() and List.copyOf() creates unmodifiable lists copyOf is introduced on Java 10 |
| | + | |
| | + | ===ArrayList=== |
| | + | <syntaxhighlight lang="java"> |
| | + | List<String> words = List.of("Eagle", "Dog", "Pear"); |
| | + | List<String> wordsArrayList = new ArrayList<String>(words) |
| | + | |
| | + | ArrayList<String> items = new ArrayList<String>() |
| | + | items.add("Apple") |
| | + | items.add("Bat") |
| | + | items.add(2, "Cat") |
| | + | items.remove("Pear") |
| | + | items.remove(0) |
| | + | items.size() |
| | + | Colections.max(items) |
| | + | List<String> newList= List.of("Table", "Pencil", "Hole"); |
| | + | wordsArrayList.addAll(newList) |
| | + | wordsArrayList.set(6, "Fish") // Modify element on position 6 |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ====Different ways to loop lists==== |
| | + | <syntaxhighlight lang="java"> |
| | + | for (String word:words){ |
| | + | System.out.println(word); |
| | + | } |
| | + | for (int i=0; i<words.size(); i++){ |
| | + | System.out.println(words.get(i)); |
| | + | } |
| | + | |
| | + | |
| | + | // Use this one when modifiying list |
| | + | Iterator wordsIterator = words.iterator(); |
| | + | while (wordsIterator.hasNext()){ |
| | + | if (wordsIterator.next().endsWith("at")){ |
| | + | wordsIterator.remove(); |
| | + | } |
| | + | } |
| | + | |
| | + | |
| | + | </syntaxhighlight>Collections.sort(<array_list_var>) |
| | + | |
| | + | Requires implementation of Comparable interface. ej:<syntaxhighlight lang="java"> |
| | + | public class Student implements Comparable<Student> { |
| | + | private int id; |
| | + | private String name; |
| | + | |
| | + | public Student(int id, String name){ |
| | + | super(); |
| | + | this.id = id; |
| | + | this.name = name; |
| | + | } |
| | + | |
| | + | public int getId() { |
| | + | return id; |
| | + | } |
| | + | @override |
| | + | public int compareTo(Student that){ |
| | + | return Integer.compare(this.id, that.id); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight>with comparators<syntaxhighlight lang="java"> |
| | + | class DescendingStudentComparator implements Comparator<Student> { |
| | + | @Override |
| | + | public int compare(Student student1, Student student2){ |
| | + | return Integer.compare(student1.getId(), student2.getId()); |
| | + | } |
| | + | } |
| | + | |
| | + | Collections.sort(studentsArrayList, new DescendingStudentComparator()); |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Set Interface (unique values)=== |
| | + | <syntaxhighlight lang="java"> |
| | + | Set<String> set = Set("Apple", "Banana", "Cat"); |
| | + | Set<String> hashset = new HashSet<>(set); |
| | + | hashset.add("Dog"); |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Hashing (Fast searches)=== |
| | + | LinkedHashSet: keeps the order in which elements are inserted<syntaxhighlight lang="java"> |
| | + | Set<Integer> numbers = new LinkedHashSet<>(); |
| | + | numbers.add(4185); |
| | + | numbers.add(545); |
| | + | </syntaxhighlight><br /><syntaxhighlight lang="java"> |
| | + | import java.util.List; |
| | + | import java.util.Set; |
| | + | import java.util.TreeSet; |
| | + | import java.util.LinkedHashSet; |
| | + | import java.util.HashSet; |
| | + | |
| | + | |
| | + | public class SetRunner{ |
| | + | public static void main(String[] args){ |
| | + | List<Character> characters = List.of('A', 'Z', 'A', 'B', 'Z', 'F'); |
| | + | // print unique characters in sorted order |
| | + | Set<Character> treeSet = new TreeSet<>(characters); |
| | + | System.out.println("treeSet" + treeSet); |
| | + | |
| | + | //print unique characters in insertion order |
| | + | Set<Character> linkedHashSet = new LinkedHashSet<>(characters); |
| | + | System.out.println("linkedHashSet" + linkedHashSet); |
| | + | |
| | + | // hashset, sometimes sorted some not |
| | + | Set<Character> HashSet = new HashSet<>(characters); |
| | + | System.out.println("linkedHashSet" + linkedHashSet); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Tree (Reduces cost of search, insert and delete)=== |
| | + | <syntaxhighlight lang="java"> |
| | + | TreeSet<Integer> numbers = new TreeSet<>(Set.of(65, 54, 34, 12, 99)); |
| | + | numbers.floor(40); // lower or equal to 40 in set |
| | + | numbers.lower(34); //lower than 34 |
| | + | numbers.ceiling(34); //>= |
| | + | numbers.higher(34); //> |
| | + | numbers.subSet(20, 80); // Returns numbers between 20 and 80 in set |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Queue=== |
| | + | <syntaxhighlight lang="java"> |
| | + | Queue <String> queue = new PriorityQueue<>(); |
| | + | queue.poll() // pull things out of queue |
| | + | queue.offer("Apple") // put things on queue |
| | + | queue.addAll(List.of("Zebra", "Monkeky")) // put lists on queue |
| | + | </syntaxhighlight><syntaxhighlight lang="java"> |
| | + | import java.util.Comparator; |
| | + | import java.util.List; |
| | + | import java.util.PriorityQueue; |
| | + | import java.util.Queue; |
| | + | |
| | + | class StringLenghtComparator implements Comparator<String> { |
| | + | @Override |
| | + | public int compare(String value1, String value2){ |
| | + | return Integer.compare(value1.lenght(), value2.length()); |
| | + | } |
| | + | } |
| | + | |
| | + | |
| | + | public class QueueRunner{ |
| | + | public void main(String[]; args){ |
| | + | // Queue<String> queue = new PriorityQueue<>(new StringLenghtComparator ()); |
| | + | Queue<String> queue = new PriorityQueue<>(); |
| | + | queue.addAll(List.of("Zebra", "Monkey", "Cat")); |
| | + | System.out.println(queue.poll()); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Map=== |
| | + | Key - Value Pair |
| | + | |
| | + | HashMap --> Not syncronized |
| | + | |
| | + | HashTable -> synchronized (thread safe) |
| | + | |
| | + | LinkedHashMap -> Insertion order is mainained, slower deletion and insertion, faster iteration |
| | + | |
| | + | TreeMap -> Data stored in sorted order<syntaxhighlight lang="java"> |
| | + | Map<String, Integer> map = Map.of("A", 3, "B", 5, "Z", 10); |
| | + | map.get("Z"); |
| | + | map.size(); |
| | + | map.isEmpty(); |
| | + | map.containsKey("A"); |
| | + | map.cointainsValue(4); |
| | + | map.keySet(); |
| | + | map.values(); |
| | + | |
| | + | Map<String, Integer> hashmap = new HashMap(map); |
| | + | hashmap.put("F", 5); |
| | + | |
| | + | </syntaxhighlight><syntaxhighlight lang="java"> |
| | + | HashMap<String, Integer> hashmap = new HashMap<>(); |
| | + | hashmap.put("Z", 5); |
| | + | hashmap.put("A", 7); |
| | + | |
| | + | //keeps insertion order |
| | + | LinkedhashMap<String, Integer> linkedHashMap = new LinkkedHashMap<>(); |
| | + | linkedHashMap.put("F", 25); |
| | + | linkedHashMap.put("A", 15); |
| | + | |
| | + | // sorts on keys |
| | + | TreeMap<String, Integer> treemap = new TreeMap<>(); |
| | + | treemap.put("Z", 5); |
| | + | treemap.put("A", 7); |
| | + | |
| | + | </syntaxhighlight><syntaxhighlight lang="java"> |
| | + | import java.util.HashMap; |
| | + | import java.util.Map; |
| | + | |
| | + | |
| | + | public class MapRunner { |
| | + | public static void main(String[] args){ |
| | + | String str = "Text to count words and letters"; |
| | + | |
| | + | Map<Character, Integer> occurances = new HashMap<>(); |
| | + | char[] chars = str.toCharArray(); |
| | + | for (char character:characters){ |
| | + | Integer integer = occurances.get(character); |
| | + | if (integer == null) { |
| | + | occurances.put(character, 1); |
| | + | } else { |
| | + | occurrances.put(character, integer + 1); |
| | + | } |
| | + | System.out.println(occurrances); |
| | + | } |
| | + | |
| | + | |
| | + | Map<String, Integer> stringOccurances = new HashMap<>(); |
| | + | String[] words = str.split(" "); |
| | + | for (String word:words){ |
| | + | Integer integer = stringOccurances .get(word); |
| | + | if (integer == null) { |
| | + | stringOccurances .put(word, 1); |
| | + | } else { |
| | + | stringOccurances .put(word, integer + 1); |
| | + | } |
| | + | System.out.println(stringOccurances ); |
| | + | } |
| | + | |
| | + | } |
| | + | } |
| | + | </syntaxhighlight>TreeMap<syntaxhighlight lang="java"> |
| | + | TreeMap<String, Integer> treemap = new TreeMap(); |
| | + | treemap.put("F", 25); |
| | + | treemap.put("Z", 5); |
| | + | treemap.put("L", 250); |
| | + | treemap.put("A", 15); |
| | + | treemap.put("B", 25); |
| | + | treemap.put("G", 25); |
| | + | treemap.higherKey("B"); |
| | + | --> F |
| | + | treemap.higherKey("C"); // > |
| | + | --> F |
| | + | treemap.ceilingKey("B"); //>= |
| | + | --> B |
| | + | tremap.lowerKey("B"); |
| | + | tremap.floorKey("B"); |
| | + | treemap.lastEntry(); |
| | + | treemap.firtstEntry(); |
| | + | treemap.subMap("C", "Y"); |
| | + | treemap.subMap("B", true, "Z", true); // to include last element |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ==Streams== |
| | + | <syntaxhighlight lang="java"> |
| | + | List<Integers> numbers = List.of(3, 5, 8, 213, 45, 4, 7) |
| | + | numbers.stream().sorted().forEach(element -> System.out.println(element)); |
| | + | numbers.stream().distinct().map(e -> e * e).forEach(e -> System.out.println(e)); |
| | + | IntStream.range(1, 11).map(e -> e * e).forEach(e -> System.out.println(e)); |
| | + | List.of("Apel", "Ant", "Bat").stream().map(s -> s.tolowercase()).forEach(p -> System.out.println(p)); |
| | + | IntStream.range(1, 11).reduce(0, (n1, n2) -> n1+n2) |
| | + | List.of(23, 12, 34, 53).stream().min((n1, n2) -> Integer.compare(n1, n2)).get() |
| | + | List.of(23, 12, 34, 53).stream().max((n1, n2) -> Integer.compare(n1, n2)).get() |
| | + | List.of(23, 12, 34, 53).stream().filter(e -> e%2==1).collect(Collectors.toList()); |
| | + | List.of(23, 45, 67, 53).stream().filter(e -> e%2==0).max((n1, n2)->Integer.compare(n1, n2)).orElse(0); |
| | + | |
| | + | // with method reference |
| | + | public static class MethodReferencesRunner { |
| | + | public static boolean isEven(Integer number){ |
| | + | return number%2==0; |
| | + | } |
| | + | } |
| | + | |
| | + | Integer max = List.of(23, 45, 67, 34).stream().filter(MethodReferencesRunner::isEven).max(Integer::compare).orElse(0); |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ==Classes and Objects== |
| | + | <source lang="java"> |
| | + | class Person { |
| | + | String name; |
| | + | int age; |
| | + | |
| | + | void speak(String text) { |
| | + | System.out.println(text + name + " and i am " + age + " years old."); |
| | + | } |
| | + | int yearsToRetire () { |
| | + | int yearsLeft = 67 - age; |
| | + | return yearsLeft; |
| | + | } |
| | + | publick String toString(){ |
| | + | return name + ' (' + age + ')' |
| | + | } |
| | + | } |
| | + | |
| | + | class Student extends Person { |
| | + | String college; |
| | + | } |
| | + | |
| | + | public class Classes { |
| | + | public static void main(String[] args){ |
| | + | Person person1 = new Person(); |
| | + | |
| | + | person1.name = "Joe Doe"; |
| | + | person1.age = 37; |
| | + | |
| | + | person1.speak("My name is: "); |
| | + | System.out.println("Years to retirement= " + person1.yearsToRetire()); |
| | + | System.out.println(person1 instanceof Person); // true |
| | + | System.out.println(person1 instanceof Object); // true |
| | + | System.out.println(person1 instanceof Student); // false |
| | + | } |
| | + | } |
| | + | </source><br /> |
| | + | ==Setters and 'this'== |
| | + | <source lang="java"> |
| | + | package tutorial1; |
| | + | |
| | + | class Frog { |
| | + | private String name; |
| | + | private int age; |
| | + | |
| | + | public void setName(String name){ |
| | + | this.name = name; |
| | + | } |
| | + | |
| | + | public void setAge(int newAge){ |
| | + | age = newAge; |
| | + | } |
| | + | |
| | + | public String getName(){ |
| | + | return name; |
| | + | } |
| | + | |
| | + | public int getAge(){ |
| | + | return age; |
| | + | } |
| | + | |
| | + | } |
| | + | |
| | + | public class setters { |
| | + | |
| | + | public static void main(String[] args) { |
| | + | Frog frog1 = new Frog(); |
| | + | |
| | + | frog1.setName("Steven"); |
| | + | frog1.setAge(1); |
| | + | |
| | + | System.out.println(frog1.getName()+ " " + frog1.getAge()); |
| | + | |
| | + | } |
| | + | |
| | + | } |
| | + | </source> |
| | + | ==Constructors== |
| | + | Methods that are executed at the instantiation of a class.<br /> |
| | + | There can be more than one, diferentiated on the number of parameters that are passed at the instantiation of a class.<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/constructors.java example code] |
| | + | |
| | + | ==static== |
| | + | static is used to define class variables and methods.<br /> |
| | + | static objects are referenced by the class, not the instance.<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/staticMethod.java example code] |
| | + | |
| | + | ==final== |
| | + | final is used to declare constants. The asignment of value must be at the declaration<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/constructors.java example code] |
| | + | |
| | + | ==StringBuilder / formatting== |
| | + | StringBuilder is more efficient for strings appending than using += |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/StringBuilderBufferFormatting.java example code] |
| | + | |
| | + | ==Inheritance & abstract== |
| | + | Use key word extends at the class declaration<br /> |
| | + | private variables and methods are not inherited.<br /> |
| | + | protected would be the appropiated declaration to be able to inherit variables without being public. |
| | + | <source lang="java"> |
| | + | public abstract class Machine { |
| | + | abstract public void move(); |
| | + | } |
| | + | |
| | + | public class Car extends Machine { |
| | + | public void move() { |
| | + | System.out.println("Moving...") |
| | + | } |
| | + | }</source> |
| | + | sample code files:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/inheritance.java inheritance.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Machine.java Machine.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Car.java Car.java] |
| | + | |
| | + | ==Packages== |
| | + | Packages allow to have classes with the same name as long as they are in diferent packages. <br /> |
| | + | In orther to be able to use the classes from a package it must be imported.<br /> |
| | + | Each package classes will be on a package folder.<br /> |
| | + | The first line of the .java file for the classes of one package must be: package package_name |
| | + | Example: |
| | + | <source lang="java"> |
| | + | import tutorial1.ocean.fish |
| | + | </source> |
| | + | Example files:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/tree/master/ocean tutorial1.ocean package]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/packageexample.java packageexample.java] |
| | + | |
| | + | ==Interfaces== |
| | + | If you whant to define a method for more than one class, you should use an interface (rigt click on project > new > interface)<br /> |
| | + | Interfaces file names should start with upper case.<syntaxhighlight lang="java"> |
| | + | public interface GamingConsole { |
| | + | public void up(); |
| | + | public void down(); |
| | + | public void left(); |
| | + | public void right(); |
| | + | |
| | + | default void start() { |
| | + | System.out.println("Start"); |
| | + | } |
| | + | } |
| | + | |
| | + | public class MarioGame implements GamingConsole { |
| | + | @Override |
| | + | public void up() { |
| | + | System.out.println("Jump"); |
| | + | } |
| | + | |
| | + | @Override |
| | + | public void down() { |
| | + | System.out.println("Goes into a hole"); |
| | + | } |
| | + | |
| | + | @Override |
| | + | public void left() { |
| | + | System.out.println("Go back"); |
| | + | } |
| | + | |
| | + | @Override |
| | + | public void right() { |
| | + | System.out.println("Go forward"); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight><br /> |
| | + | Example files:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/interfaces.java interfaces.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/PersonInterface.java PersonInterface.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Machine.java Machine.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Info.java Info.java]<br /> |
| | + | |
| | + | ==public/private/protected variables== |
| | + | public → can be accesed from anywhere.<br /> |
| | + | public final static → constant.<br /> |
| | + | private → can only be accesed from the class where it was declared.<br /> |
| | + | protected → can only be by the class where it was declarated, subclasses and from it's package.<br /> |
| | + | no access specifier → only accesible from the same package.<br /> |
| | + | |
| | + | ==Polymorphism== |
| | + | You can point a variable of a parent type to a child type, it will have the methods from it's type but overriden by the subclass.<br /> |
| | + | You wont be able to call methods from the subclass that are not implemented on the variable type.<br /> |
| | + | Example files:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Polymorphism.java Polymorphism.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Plant.java Plant.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Tree.java Tree.java] |
| | + | |
| | + | ==Encapsulation and the API== |
| | + | Variables whithin a class should be private and if you need to change them use getters and setters.<br /> |
| | + | [https://docs.oracle.com/javase/8/docs/api/ Java 8 API] |
| | + | |
| | + | ==Casting Numerical Values== |
| | + | See [https://github.com/rafahsolis/javaTutorial/blob/master/Casting.java examples] |
| | + | |
| | + | ==Upcasting and Downcasting== |
| | + | Code examples:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/UpcastingDowncasting.java UpcastingDowncasting.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Camara.java Camara.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Machine.java Machine.java]<br /> |
| | + | |
| | + | ==Generic class== |
| | + | Can work with other objects specified at the class instantiation.<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Generic.java Generic.java] |
| | + | <source lang="java"> |
| | + | import java.util.ArrayList; |
| | + | import java.util.HashMap; |
| | + | |
| | + | public class Generic { |
| | + | public static void main(String[] args) { |
| | + | |
| | + | //////////// Before Java 5 ////////// |
| | + | ArrayList list1 = new ArrayList(); |
| | + | list1.add("Banana"); |
| | + | list1.add("Apple"); |
| | + | list1.add("Orange"); |
| | + | |
| | + | String fruit = (String)list1.get(1); |
| | + | System.out.println(fruit); |
| | + | |
| | + | ///////// After Java 5 ///////////// |
| | + | ArrayList<String> strings = new ArrayList<String>(); |
| | + | strings.add("cat"); |
| | + | strings.add("dog"); |
| | + | strings.add("fish"); |
| | + | |
| | + | String animal = strings.get(2); |
| | + | System.out.println(animal); |
| | + | |
| | + | ///////// There can be more than one type argument ////// |
| | + | HashMap<Integer, String> map= new HashMap<Integer, String>(); |
| | + | |
| | + | //////// Java 7 ////////////////////// |
| | + | ArrayList<Integer> someList = new ArrayList<>(); |
| | + | |
| | + | |
| | + | } |
| | + | } |
| | + | </source> |
| | + | ===Generics and Wildcards=== |
| | + | See: [https://github.com/rafahsolis/javaTutorial/blob/master/Generic.java Generic.java] |
| | + | ==Files== |
| | + | ===Reading text files=== |
| | + | 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)=== |
| | + | This requires at least Java 7<br /> |
| | + | <source lang="java"> |
| | + | import java.io.BufferedReader; |
| | + | import java.io.File; |
| | + | import java.io.FileNotFoundException; |
| | + | import java.io.FileReader; |
| | + | import java.io.IOException; |
| | + | |
| | + | public class FilesTryWithResources { |
| | + | public static void main(String[] args) { |
| | + | File file = new File("./src/tutorialJava/textFile.txt"); |
| | + | |
| | + | try (BufferedReader br = new BufferedReader(new FileReader(file))) { |
| | + | String line; |
| | + | |
| | + | while ((line = br.readLine()) != null) { |
| | + | System.out.println(line); |
| | + | } |
| | + | |
| | + | } catch (FileNotFoundException e) { |
| | + | System.out.println("File not found: " + file.toString()); |
| | + | |
| | + | } catch (IOException e) { |
| | + | System.out.println("Unable to read the file: " + file.toString()); |
| | + | } |
| | + | |
| | + | } |
| | + | }</source> |
| | + | ===Reading files with FileReader=== |
| | + | <source lang="java"> |
| | + | import java.io.BufferedReader; |
| | + | import java.io.File; |
| | + | import java.io.FileNotFoundException; |
| | + | import java.io.FileReader; |
| | + | import java.io.IOException; |
| | + | |
| | + | public class ReadingFiles { |
| | + | |
| | + | public static void main(String[] args) { |
| | + | File file = new File("./src/tutorialJava/textFile.txt"); |
| | + | BufferedReader br = null; |
| | + | |
| | + | try { |
| | + | FileReader fr = new FileReader(file); |
| | + | br = new BufferedReader(fr); |
| | + | |
| | + | String line; |
| | + | |
| | + | while ((line = br.readLine()) != null) { |
| | + | System.out.println(line); |
| | + | } |
| | + | |
| | + | } catch (FileNotFoundException e) { |
| | + | System.out.println("File not found" + file.toString()); |
| | + | } catch (IOException e) { |
| | + | System.out.println("Unable to read the file: " + file.toString()); |
| | + | } finally { |
| | + | try { |
| | + | br.close(); |
| | + | } catch (IOException e) { |
| | + | System.out.println("Can't close the file."); |
| | + | } |
| | + | |
| | + | } |
| | + | |
| | + | } |
| | + | }</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=== |
| | + | <source lang="java"> |
| | + | import java.io.BufferedWriter; |
| | + | import java.io.File; |
| | + | import java.io.FileNotFoundException; |
| | + | import java.io.FileWriter; |
| | + | import java.io.IOException; |
| | + | |
| | + | public class WritingFiles { |
| | + | |
| | + | public static void main(String[] args) { |
| | + | File file = new File("./src/tutorialJava/textFile2.txt"); |
| | + | |
| | + | try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) { |
| | + | br.write("This is line 1"); |
| | + | br.newLine(); |
| | + | br.write("This is line 2"); |
| | + | br.newLine(); |
| | + | br.write("Last line"); |
| | + | br.newLine(); |
| | + | |
| | + | } catch (IOException e) { |
| | + | System.out.println("Unable to read the file: " + file.toString()); |
| | + | } |
| | + | |
| | + | } |
| | + | |
| | + | }</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== |
| | + | see: [https://github.com/rafahsolis/javaTutorial/blob/master/AnonymousClass.java AnonymousClass.java] |
| | + | ==Exceptions== |
| | + | [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=== |
| | + | <source lang="java"> |
| | + | package tutorialJava; |
| | + | |
| | + | import java.io.File; |
| | + | import java.io.FileNotFoundException; |
| | + | import java.io.FileReader; |
| | + | |
| | + | 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 { |
| | + | File file = new File("test.txt"); |
| | + | FileReader fr = new FileReader(file); |
| | + | 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> |
| | + | |
| | + | ===try/catch=== |
| | + | <source lang="java"> |
| | + | import java.io.IOException; |
| | + | import java.text.ParseException; |
| | + | |
| | + | public class MultipleExceptions { |
| | + | public static void main(String[] args) { |
| | + | Test test = new Test(); |
| | + | |
| | + | //Option 1 |
| | + | try { |
| | + | test.run(); |
| | + | } catch (IOException e) { |
| | + | // e.printStackTrace(); |
| | + | System.out.println("File not found."); |
| | + | } catch (ParseException e) { |
| | + | // e.printStackTrace(); |
| | + | System.out.println("Parse error."); |
| | + | } |
| | + | |
| | + | //Option 2 |
| | + | try { |
| | + | test.run(); |
| | + | } catch (IOException | ParseException e) { |
| | + | // TODO Auto-generated catch block |
| | + | e.printStackTrace(); |
| | + | } |
| | + | |
| | + | //Option 3 |
| | + | try { |
| | + | test.run(); |
| | + | } catch (Exception e) { |
| | + | // TODO Auto-generated catch block |
| | + | e.printStackTrace(); |
| | + | } finally { |
| | + | // Do something |
| | + | } |
| | + | |
| | + | //Option 4 |
| | + | // add throws to main declaration... |
| | + | } |
| | + | }</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=== |
| | + | The compiler does not force you to handle them. |
| | + | <source lang="java"> |
| | + | package tutorialJava; |
| | + | |
| | + | public class RuntimeExceptions { |
| | + | |
| | + | public static void main(String[] args) { |
| | + | int value = 7; |
| | + | String[] texts = {"cero", "one", "two"}; |
| | + | |
| | + | //runtime exceptions |
| | + | //// division by 0(ArithmeticException) |
| | + | try { |
| | + | value = value/0; |
| | + | } catch (Exception e){ |
| | + | System.out.println(e.getMessage()); |
| | + | System.out.println(e.toString()); |
| | + | e.printStackTrace(); |
| | + | } |
| | + | //// ArrayIndexOutOfBoundsException |
| | + | System.out.println(texts[3]); |
| | + | // NoPointerException |
| | + | |
| | + | } |
| | + | |
| | + | }</source> |
| | + | ==Abstract Class== |
| | + | Classes that can't be instantiated, only inherited.<br /> |
| | + | See example files:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/AbstractClasses.java AbstractClasses.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/AbstractClassChild2.java AbstractClassChild2.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/AbstractClassChild1.java AbstractClassChild1.java]<br /> |
| | + | |
| | + | ==.equals() Method== |
| | + | It's used to compare if two objects of the same class are equal. In order to be able to use it you must override this method by:<br /> |
| | + | Right click on the class > source > Generate hashCode() and Equals()...<br /> |
| | + | Select the fields you whant to compare.<br /> |
| | + | See code examples:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/EqualsMethod.java EqualsMethod.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Persona.java Persona.java]<br /> |
| | + | |
| | + | ==Inner Classes== |
| | + | Clases declared inside other classes.<br /> |
| | + | Code examples:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/InnerClasses.java InnerClasses.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Robot.java Robot.java] |
| | + | |
| | + | ==Recursion== |
| | + | See code example:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Recursion.java Recursion.java]<br /> |
| | + | |
| | + | ==Serialization== |
| | + | Turning an object into binary data, deserialization is the opposite.<br /> |
| | + | Code examples:<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/WriteObjects.java WriteObjects.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/ReadObjects.java ReadObjects.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/Persona.java Persona.java]<br /> |
| | + | |
| | + | ===Multiple Objects=== |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/WriteMultipleObjects.java WriteMultipleObjects.java]<br /> |
| | + | [https://github.com/rafahsolis/javaTutorial/blob/master/ReadMultipleObjects.java ReadMultipleObjects.java]<br /> |
| | + | ===Transient Keyword=== |
| | + | To prevent the serialization of some variable in a class you can declare it as:<br /> |
| | + | <source lang="java"> |
| | + | private transient int variableName;</source> |
| | + | Static fields aren't serialized too. |
| | + | |
| | + | ==Threading== |
| | + | <syntaxhighlight lang="java"> |
| | + | class Task1 extends Thread { |
| | + | public void run() { |
| | + | System.out.print("\nTask1 Started"); |
| | + | // Do something |
| | + | Thread.yield(); // let other thread take over |
| | + | System.out.print("\nTask1 Done"); |
| | + | } |
| | + | } |
| | + | |
| | + | class Task2 implements Runnable { |
| | + | public void run() { |
| | + | System.out.print("\nTask2 Started"); |
| | + | // Do something |
| | + | System.out.print("\nTask2 Done"); |
| | + | } |
| | + | } |
| | + | |
| | + | public class ThreadBasicsRunner { |
| | + | public static void main(String[] args) throws InterruptedException { |
| | + | Task1 task1 = new Task1(); |
| | + | task1.setPriority(10); // min = 1 max = 10 |
| | + | task1.start(); |
| | + | |
| | + | Task2 task2 = new Task2(); |
| | + | Thread task2thread = new Thread(task2); |
| | + | task2thread.start(); |
| | + | |
| | + | // wait for task1 to end |
| | + | task1.join(); |
| | + | |
| | + | // task3 |
| | + | System.out.print("\nTask3 Started"); |
| | + | // Do something |
| | + | System.out.print("\nTask3 Done"); |
| | + | } |
| | + | } |
| | + | |
| | + | |
| | + | |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Executor service=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.concurrent.ExecutorService; |
| | + | import java.util.concurrent.Executors; |
| | + | |
| | + | class Task extends Thread{ |
| | + | public Task(int number){ |
| | + | this.number = number; |
| | + | } |
| | + | |
| | + | public void run() { |
| | + | System.out.print("\nTask" + number + " Started"); |
| | + | |
| | + | for (i=number*100; i<=number*100+99; i++){ |
| | + | System.out.print(i + " "); |
| | + | } |
| | + | System.out.print("\nTask" + number + " Done"); |
| | + | } |
| | + | } |
| | + | |
| | + | public class ExecutorServiceRunner { |
| | + | public static void main(String[] args){ |
| | + | // ExecutorService executorService = Executors.newSingleThreadExecutor(); |
| | + | ExecutorService executorService = Executors.newFixedThreadPool(2); |
| | + | executorService.execute(new Task(1)); |
| | + | executorService.execute(new Task(2)); |
| | + | executorService.execute(new Task(3)); |
| | + | executorService.execute(new Task(4)); |
| | + | executorService.shutdown() |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Return values from threads=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.concurrent.Callable; |
| | + | import java.util.concurrent.ExecutorService; |
| | + | import java.util.concurrent.Future; |
| | + | |
| | + | class CallableTask implements Callable<String> { |
| | + | |
| | + | public CallableTask(String name){ |
| | + | this.name = name; |
| | + | } |
| | + | |
| | + | @Override |
| | + | public String call() throws Exception { |
| | + | Thread.sleep(1000); |
| | + | return "Hello " + name; |
| | + | } |
| | + | } |
| | + | |
| | + | public class CallableRunner throws InterruptedException, ExecutionException { |
| | + | public static void main(String[] args){ |
| | + | ExecutorService executorService = Executors.newFixedThreadPoool(1); |
| | + | Future<String> welcomeFuture = executorService.submit(new CallableTask("Manolo")); |
| | + | System.out.print("\ncallable executed") |
| | + | String welcomeMessage = welcomeFuture.get(); |
| | + | System.out.print("\nMain completed") |
| | + | executorService.shutdown(); |
| | + | } |
| | + | } |
| | + | </syntaxhighlight> |
| | + | |
| | + | ===Multiple callable runner=== |
| | + | <syntaxhighlight lang="java"> |
| | + | import java.util.concurrent.Callable; |
| | + | import java.util.concurrent.ExecutorService; |
| | + | import java.util.concurrent.Future; |
| | + | |
| | + | class CallableTask implements Callable<String> { |
| | + | |
| | + | public CallableTask(String name){ |
| | + | this.name = name; |
| | + | } |
| | + | |
| | + | @Override |
| | + | public String call() throws Exception { |
| | + | Thread.sleep(1000); |
| | + | return "Hello " + name; |
| | + | } |
| | + | } |
| | + | |
| | + | public class MultipleCallableRunner throws InterruptedException, ExecutionException { |
| | + | public static void main(String[] args){ |
| | + | ExecutorService executorService = Executors.newFixedThreadPoool(3); |
| | + | |
| | + | List<CallableTask> tasks = List.of(new CallableTask("Manolo"), new CallableTask("Pedro")); |
| | + | |
| | + | List<Future<String>> results = executorService.invokeAll(tasks); |
| | + | // String result = executorService.invokeAny(tasks); // returns only 1 the fastest |
| | + | for (Future<String> result:results){ |
| | + | System.out.println(result.get()); |
| | + | } |
| | + | |
| | + | System.out.print("\nMain completed") |
| | + | executorService.shutdown(); |
| | + | } |
| | + | } |
| | + | </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== |
| | Ctrl + Space → Autocomplete.<br /> | | Ctrl + Space → Autocomplete.<br /> |
| | Ctrl + d → Delete Line<br /> | | Ctrl + d → Delete Line<br /> |
| | Ctrl + o → Automatically add imports<br /> | | Ctrl + o → Automatically add imports<br /> |
| | + | Ctrl + Shift + f → Indent<br /> |
| | + | Ctrl + m → Toogle fulscreen<br /> |
| | + | |
| | + | ==Notes== |
| | + | 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]] |