├── .gitignore
├── .idea
├── .gitignore
├── description.html
├── encodings.xml
├── misc.xml
├── modules.xml
├── project-template.xml
├── uiDesigner.xml
└── vcs.xml
├── complete-java-course.iml
└── src
└── com
├── advanced
├── arrayfunctions
│ └── ArrayFunctionsApp.java
├── collections
│ ├── arraylist
│ │ ├── Product.java
│ │ ├── ToDoListApp.java
│ │ └── WebShopApp.java
│ ├── linkedlist
│ │ └── LinkedListApp.java
│ └── vector
│ │ └── VectorApp.java
├── debugging
│ └── RockPaperScissorsApp.java
├── enumcoding
│ ├── Pizza.java
│ ├── PizzaApp.java
│ └── PizzaSize.java
├── exceptions
│ ├── DivideTwoNumbersExceptionApp.java
│ ├── FileCreationExceptionApp.java
│ ├── JuliusCesar.txt
│ └── ZeroDivisorException.java
├── filehandling
│ ├── BufferedReaderApp.java
│ ├── BufferedWriterApp.java
│ ├── CopyMoveApp.java
│ ├── DirectoriesApp.java
│ ├── FileClassUsefulFunctionsApp.java
│ ├── FileHandlingApp.java
│ ├── FileReaderApp.java
│ ├── FileWriterApp.java
│ ├── PathClassApp.java
│ ├── PrintWriterApp.java
│ └── ScannerApp.java
├── finalpractice
│ ├── GameService.java
│ ├── HangmanApp.java
│ └── words.txt
├── generics
│ ├── Box.java
│ ├── GenericsApp.java
│ ├── OrderedPair.java
│ ├── Pair.java
│ ├── Util.java
│ └── weirdpart
│ │ ├── GenericFunctions.java
│ │ └── GenericsWeirdPartApp.java
├── innerclasses
│ ├── InnerClassesApp.java
│ ├── Pizza.java
│ └── staticnested
│ │ ├── Pizza.java
│ │ └── PizzaBuilderApp.java
├── io
│ └── CharacterApp.java
├── mathfunctions
│ └── MathFunctionsApp.java
├── objectclone
│ ├── Pizza.java
│ ├── PizzaApp.java
│ └── PizzaSize.java
├── objectequals
│ ├── Pizza.java
│ ├── PizzaApp.java
│ └── PizzaSize.java
├── objectgetclass
│ ├── Pizza.java
│ ├── PizzaApp.java
│ └── PizzaSize.java
├── objecthashcode
│ ├── Pizza.java
│ ├── PizzaApp.java
│ └── PizzaSize.java
├── objecttostring
│ ├── Pizza.java
│ ├── PizzaApp.java
│ └── PizzaSize.java
├── string
│ └── StringPerformanceApp.java
├── stringtokenizer
│ └── StringTokenizerApp.java
└── timetpyes
│ └── PizzaWebshopApp.java
├── beginner
├── arrays
│ └── ArraysApp.java
├── controlflow
│ ├── ControlFlowApp.java
│ └── WhoWantsToBeAMillionaireApp.java
├── datatypes
│ ├── object
│ │ └── references
│ │ │ └── ObjectReferencesApp.java
│ └── primitives
│ │ └── MyFirstJavaApp.java
├── endsection
│ └── IMDBApp.java
├── loops
│ └── LoopsApp.java
├── methods
│ └── FunctionApp.java
├── operators
│ └── OperatorsApp.java
├── variables
│ └── MyFirstJavaApp.java
└── yourfirstjavacode
│ └── MyFirstJavaApp.java
├── expert
├── finalpractice
│ ├── HabitablePlanetApp.java
│ ├── Planet.java
│ └── PlanetRepository.java
├── lambda
│ ├── basics
│ │ ├── FunctionalProgrammingApp.java
│ │ ├── Greeter.java
│ │ ├── GuestUserGreeter.java
│ │ ├── LoggedInUserGreeter.java
│ │ └── WelcomeMessageService.java
│ ├── biconsumer
│ │ └── LambdaBiConsumerApp.java
│ ├── bifunction
│ │ └── LambdaBiFunctionApp.java
│ ├── consumer
│ │ └── LambdaConsumerApp.java
│ ├── listpractice
│ │ ├── ListLambdaExpressionApp.java
│ │ ├── NumberOperationService.java
│ │ └── Operation.java
│ ├── predicate
│ │ ├── LambdaPredicateApp.java
│ │ └── LambdaPredicateMoreApp.java
│ ├── streamexample
│ │ └── StreamExampleApp.java
│ ├── supplier
│ │ └── LambdaSupplierApp.java
│ └── undaryoperator
│ │ └── LambdaUnaryApp.java
├── maps
│ ├── hashmap
│ │ └── HashMapApp.java
│ ├── hashtable
│ │ └── HashTableApp.java
│ ├── linkedhashmap
│ │ └── LinkedHashMapApp.java
│ └── treemap
│ │ ├── TreeMapApp.java
│ │ └── TreeMapExtraFunctionsApp.java
├── methodreference
│ ├── CollectionTransformer.java
│ ├── MethodReferenceApp.java
│ ├── Person.java
│ └── PersonComparisonProvider.java
├── queues
│ ├── ArrayDequeApp.java
│ ├── LinkedListDequeApp.java
│ ├── LinkedListQueueApp.java
│ ├── PriorityQueueApp.java
│ └── StackWithLinkedListApp.java
├── sets
│ ├── enumset
│ │ └── EnumSetApp.java
│ ├── hashset
│ │ ├── HashSetApp.java
│ │ └── HashSetOperationsApp.java
│ ├── linkedhashset
│ │ └── LinkedHashSetApp.java
│ └── treemap
│ │ └── TreeSetApp.java
└── streams
│ ├── collect
│ ├── CollectGroupingByApp.java
│ ├── CollectMinMaxByTeeingApp.java
│ ├── CollectToApp.java
│ ├── CollectUtilFunctionsApp.java
│ ├── Item.java
│ └── WeatherByMonth.java
│ ├── distinct
│ └── DistinctApp.java
│ ├── filtering
│ ├── FilterApp.java
│ └── Product.java
│ ├── findfunctions
│ └── FindFunctionsApp.java
│ ├── flatmap
│ ├── CarDealership.java
│ └── FlatMapApp.java
│ ├── foreach
│ └── ForEachApp.java
│ ├── howtocreate
│ └── StreamCreationApp.java
│ ├── introduction
│ └── StreamsIntroductionApp.java
│ ├── map
│ └── MapApp.java
│ ├── match
│ └── MatchFunctionsApp.java
│ ├── minmax
│ └── MinMaxCountApp.java
│ ├── peek
│ └── PeekApp.java
│ ├── range
│ └── RangeApp.java
│ ├── reduce
│ └── ReduceApp.java
│ ├── skiplimit
│ └── SkipLimitApp.java
│ └── sorted
│ └── SortedApp.java
├── hero
├── garbagecollection
│ ├── GarbageCollectionApp.java
│ └── UnstablePlanet.java
├── multithreading
│ ├── interrupt
│ │ ├── InterruptApp.java
│ │ ├── Pump.java
│ │ └── Tank.java
│ ├── join
│ │ ├── JoinApp.java
│ │ └── RecipeStep.java
│ ├── mutex
│ │ ├── BankAccount.java
│ │ └── MutexApp.java
│ ├── producerconsumer
│ │ ├── Message.java
│ │ ├── MessageConsumer.java
│ │ ├── MessageProducer.java
│ │ └── ProducerConsumerApp.java
│ ├── runnable
│ │ ├── RunnableApp.java
│ │ └── WebsiteModule.java
│ ├── semaphore
│ │ ├── ParkingLot.java
│ │ └── SemaphoreApp.java
│ ├── sync
│ │ ├── BankAccount.java
│ │ └── SynchronizedApp.java
│ ├── thread
│ │ ├── ThreadApp.java
│ │ └── WebsiteModule.java
│ ├── threadvariables
│ │ ├── BankApp.java
│ │ └── Transaction.java
│ └── volatilekeyword
│ │ ├── BalanceReader.java
│ │ ├── BankAccount.java
│ │ └── VolatileApp.java
└── optional
│ ├── empty
│ ├── EmptyApp.java
│ └── FindFriendServiceEmpty.java
│ ├── filter
│ ├── EmailServiceFilter.java
│ └── FilterApp.java
│ ├── get
│ └── GetApp.java
│ ├── ifpresent
│ ├── EmailService.java
│ ├── IfPresentApp.java
│ ├── User.java
│ └── UserRepository.java
│ ├── ifpresentorelse
│ ├── EmailService.java
│ └── IfPresentOrElseApp.java
│ ├── isempty
│ └── IsEmptyApp.java
│ ├── newway
│ └── NewWayApp.java
│ ├── of
│ └── OfAndOfNullableApp.java
│ ├── oldway
│ ├── Friend.java
│ ├── FriendFinderService.java
│ └── OldWayApp.java
│ ├── orelse
│ ├── EmailServiceOrElse.java
│ └── OrElseApp.java
│ ├── orelseget
│ ├── EmailServiceOrElseGet.java
│ └── OrElseGetApp.java
│ └── orelsethrow
│ ├── EmailServiceOrElseThrow.java
│ └── OrElseThrowApp.java
└── intermediate
├── abstraction
├── athlete
│ ├── Athlete.java
│ ├── AthleteApp.java
│ ├── BasketballPlayer.java
│ ├── FootballPlayer.java
│ ├── Swimmer.java
│ └── Swimming.java
└── car
│ ├── Car.java
│ ├── CarsApp.java
│ ├── DodgeChallenger.java
│ ├── ElectricMode.java
│ └── ToyotaSupra.java
├── classesandobjects
├── BasketballApp.java
├── BasketballPlayer.java
├── CarsApp.java
└── DodgeChallenger.java
├── comment
└── StringFunctionsApp.java
├── defaultvalues
├── Car.java
├── DefaultValuesApp.java
└── Engine.java
├── encapsulation
├── athlete
│ ├── Athlete.java
│ ├── AthleteApp.java
│ ├── BasketballPlayer.java
│ └── FootballPlayer.java
└── car
│ ├── Car.java
│ ├── CarsApp.java
│ ├── DodgeChallenger.java
│ └── ToyotaSupra.java
├── endsection
├── Building.java
├── City.java
├── Criminal.java
├── Detective.java
├── Gang.java
├── Item.java
├── Person.java
├── Police.java
└── TheGreatRobberyApp.java
├── finalkeyword
├── Brazil.java
└── Country.java
├── inheritance
├── athlete
│ ├── Athlete.java
│ ├── AthleteApp.java
│ ├── BasketballPlayer.java
│ └── FootballPlayer.java
└── car
│ ├── Car.java
│ ├── CarsApp.java
│ ├── DodgeChallenger.java
│ └── ToyotaSupra.java
├── polymorphism
├── athlete
│ ├── Athlete.java
│ ├── AthleteApp.java
│ ├── BasketballPlayer.java
│ ├── FootballPlayer.java
│ ├── Swimmer.java
│ └── Swimming.java
└── car
│ ├── Car.java
│ ├── CarsApp.java
│ ├── DodgeChallenger.java
│ ├── ElectricMode.java
│ └── ToyotaSupra.java
├── statickeyword
├── CountriesApp.java
└── Country.java
└── stringfunctions
└── StringFunctionsApp.java
/.gitignore:
--------------------------------------------------------------------------------
1 | out/
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /workspace.xml
--------------------------------------------------------------------------------
/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main()
method
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/complete-java-course.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/com/advanced/collections/arraylist/Product.java:
--------------------------------------------------------------------------------
1 | package com.advanced.collections.arraylist;
2 |
3 | import java.util.Objects;
4 |
5 | public class Product {
6 |
7 | private String name;
8 | private double price;
9 | private String description;
10 |
11 | public Product(String name, double price, String description) {
12 | this.name = name;
13 | this.price = price;
14 | this.description = description;
15 | }
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public void setName(String name) {
22 | this.name = name;
23 | }
24 |
25 | public double getPrice() {
26 | return price;
27 | }
28 |
29 | public void setPrice(double price) {
30 | this.price = price;
31 | }
32 |
33 | public String getDescription() {
34 | return description;
35 | }
36 |
37 | public void setDescription(String description) {
38 | this.description = description;
39 | }
40 |
41 | @Override
42 | public boolean equals(Object o) {
43 | if (this == o) return true;
44 | if (o == null || getClass() != o.getClass()) return false;
45 | Product product = (Product) o;
46 | return Double.compare(product.price, price) == 0 && Objects.equals(name, product.name) && Objects.equals(description, product.description);
47 | }
48 |
49 | @Override
50 | public int hashCode() {
51 | return Objects.hash(name, price, description);
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | return "Product{" +
57 | "name='" + name + '\'' +
58 | ", price=" + price +
59 | ", description='" + description + '\'' +
60 | '}';
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/com/advanced/collections/arraylist/ToDoListApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.collections.arraylist;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 |
6 | public class ToDoListApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | ArrayList urgentTasks = new ArrayList<>();
11 | ArrayList allTasks = new ArrayList<>();
12 |
13 |
14 | urgentTasks.add("Repairing the car");
15 | urgentTasks.add("Paying the checks");
16 |
17 | allTasks.add("Cleaning the bathroom");
18 | allTasks.add("Mowing the lawn");
19 | allTasks.add("Going to the grocery store");
20 |
21 | Collections.swap(urgentTasks, 0, 1);
22 | //urgentTasks.clear();
23 | if (!urgentTasks.isEmpty()) {
24 | System.out.println("Urgent tasks:");
25 | for (String task : urgentTasks) {
26 | System.out.println("- " + task);
27 | }
28 | }
29 |
30 | allTasks.addAll(urgentTasks);
31 | Collections.sort(allTasks, Collections.reverseOrder());
32 |
33 | System.out.println("All tasks:");
34 | for (String task : allTasks) {
35 | System.out.println("- " + task);
36 | }
37 |
38 | System.out.println("--------------------------------------");
39 | if (allTasks.contains("Cleaning the bathroom")){
40 | System.out.println("I haven't cleaned the bathroom");
41 | }
42 |
43 | System.out.println("--------------------------------------");
44 | System.out.println("The first 3 most important tasks:");
45 | for (String task : allTasks.subList(0, 3)) {
46 | System.out.println("- " + task);
47 | }
48 |
49 | Collections.shuffle(allTasks);
50 | System.out.println("--------------------------------------");
51 | System.out.println("Shuffled tasks:");
52 | for (String task : allTasks) {
53 | System.out.println("- " + task);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/com/advanced/collections/arraylist/WebShopApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.collections.arraylist;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class WebShopApp {
6 |
7 | public static void main(String[] args) {
8 | ArrayList products = new ArrayList<>();
9 |
10 | products.add(new Product("Fidget spinner", 3.99, "It's fun."));
11 | products.add(new Product("Earbud", 39.99, "Extremely clear sound. Waterproof."));
12 | products.add(new Product("Earbud", 39.99, "Extremely clear sound. Waterproof."));
13 |
14 | products.add(1, new Product("36 AAA batteries", 10.99, "High-performance alkaline batteries."));
15 |
16 | products.remove(2);
17 | //products.remove(new Product("Earbud", 39.99, "Extremely clear sound. Waterproof."));
18 |
19 | products.set(0, new Product("Rubber duck", 5.99, "You can't have bath without this."));
20 |
21 | //System.out.println(products);
22 | for (Product product : products) {
23 | System.out.println(product);
24 | }
25 |
26 | System.out.println("The third element in the list:");
27 | System.out.println(products.get(2));
28 |
29 | System.out.println(products.size() + " products can be found in the list.");
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/advanced/collections/linkedlist/LinkedListApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.collections.linkedlist;
2 |
3 | import java.util.LinkedList;
4 |
5 | public class LinkedListApp {
6 |
7 | public static void main(String[] args) {
8 |
9 | LinkedList morningRoutine = new LinkedList<>();
10 |
11 | if (!morningRoutine.isEmpty()) {
12 | System.out.println("The first element of the list: " + morningRoutine.getFirst());
13 | }
14 |
15 | if (!morningRoutine.isEmpty() && morningRoutine.peekFirst() != null) {
16 | System.out.println("The first element of the list: " + morningRoutine.peekFirst().toUpperCase());
17 | }
18 |
19 | // morningRoutine.add("Brushing my teeth");
20 | // morningRoutine.add("Taking the dog for a walk");
21 | // morningRoutine.add("Doing 32 push-ups");
22 |
23 | morningRoutine.add("Brushing my teeth");
24 | morningRoutine.addFirst("Taking the dog for a walk");
25 | morningRoutine.push("Doing 32 push-ups");
26 | morningRoutine.offer("Reading 1 chapter of a book");
27 |
28 | // System.out.println("I used pop function: " + morningRoutine.pop());
29 |
30 | System.out.println(morningRoutine);
31 |
32 | System.out.println("I completed the first element on my list: " + morningRoutine.pollFirst());
33 | System.out.println("I completed the last element on my list: " + morningRoutine.pollLast());
34 |
35 | System.out.println(morningRoutine);
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/advanced/collections/vector/VectorApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.collections.vector;
2 |
3 | import java.util.Vector;
4 |
5 | public class VectorApp {
6 |
7 | public static void main(String[] args) {
8 | Vector toDoVector = new Vector<>(2, 3);
9 | System.out.println("Initial capacity of the vector: " + toDoVector.capacity());
10 |
11 | toDoVector.add("Cleaning the garden");
12 | toDoVector.add("Painting the walls");
13 | toDoVector.add("Taking the dog for a walk");
14 |
15 | System.out.println("Capacity of the vector after adding 3 elements: " + toDoVector.capacity());
16 | System.out.println("Size of the vector after adding 3 elements: " + toDoVector.size());
17 |
18 | System.out.println("The first element of the vector is: " + toDoVector.firstElement());
19 | System.out.println("The last element of the vector is: " + toDoVector.lastElement());
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/advanced/enumcoding/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.enumcoding;
2 |
3 | public class Pizza {
4 |
5 | private String name;
6 | private PizzaSize pizzaSize;
7 | private double price;
8 |
9 | public Pizza(String name, PizzaSize pizzaSize) {
10 | this.name = name;
11 | this.pizzaSize = pizzaSize;
12 | this.price = calculatePrice();
13 | }
14 |
15 | private double calculatePrice() {
16 | switch (pizzaSize) {
17 | case SMALL:
18 | default:
19 | return 5.99;
20 | case MEDIUM:
21 | return 7.99;
22 | case LARGE:
23 | return 10.99;
24 | }
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 |
31 | public PizzaSize getPizzaSize() {
32 | return pizzaSize;
33 | }
34 |
35 | public double getPrice() {
36 | return price;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/advanced/enumcoding/PizzaApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.enumcoding;
2 |
3 | public class PizzaApp {
4 |
5 | public static void main(String[] args) {
6 | System.out.println("Available sizes:");
7 | for (PizzaSize pizzaSize : PizzaSize.values()) {
8 | System.out.println("- " + pizzaSize.getPizzaSizeText());
9 | }
10 | System.out.println();
11 |
12 | Pizza pizzaOrder = new Pizza("Margareta", PizzaSize.MEDIUM);
13 | System.out.println("I ordered the following pizza:");
14 | System.out.println("Name: " + pizzaOrder.getName());
15 | System.out.println("Size: " + pizzaOrder.getPizzaSize().getPizzaSizeText());
16 | System.out.println("Price: $" + pizzaOrder.getPrice());
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/advanced/enumcoding/PizzaSize.java:
--------------------------------------------------------------------------------
1 | package com.advanced.enumcoding;
2 |
3 | public enum PizzaSize {
4 | SMALL("Small size"), MEDIUM("Medium size"), LARGE("Large size");
5 |
6 | private String pizzaSizeText;
7 |
8 | PizzaSize(String pizzaSizeText) {
9 | this.pizzaSizeText = pizzaSizeText;
10 | }
11 |
12 | public String getPizzaSizeText() {
13 | return pizzaSizeText;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/advanced/exceptions/DivideTwoNumbersExceptionApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.exceptions;
2 |
3 | public class DivideTwoNumbersExceptionApp {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(divide(30, 2));
7 | System.out.println(divide(15, 0));
8 | System.out.println("The job is finished!");
9 | }
10 |
11 | private static int divide(int dividend, int divisor){
12 |
13 | try {
14 | if (divisor == 0) {
15 | throw new ZeroDivisorException("The divisor can't be zero! - Custom exception");
16 | }
17 | return dividend / divisor;
18 | } catch (NullPointerException exception) {
19 | System.err.println("NullPointerException is thrown");
20 | return 0;
21 | } catch (ZeroDivisorException|NumberFormatException exception) {
22 | System.err.println(exception.getMessage());
23 | exception.printStackTrace();
24 | return 0;
25 | } finally {
26 | System.out.println("Hey, I'm a very good tool to close files and database connections.");
27 | }
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/advanced/exceptions/FileCreationExceptionApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.exceptions;
2 |
3 | import java.io.FileWriter;
4 | import java.io.IOException;
5 | import java.io.PrintWriter;
6 |
7 | public class FileCreationExceptionApp {
8 |
9 | public static void main(String[] args) {
10 | createFile("outputFile.txt");
11 | }
12 |
13 | private static void createFile(String fileName) {
14 | //PrintWriter outputFile = null;
15 | try(PrintWriter outputFile = new PrintWriter(new FileWriter(fileName))) {
16 | outputFile.println("Hello");
17 | } catch (IOException exception) {
18 | System.err.println("Caught an IOException: " + exception.getMessage());
19 | }
20 | System.out.println("This line comes after we tried to create a file.");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/advanced/exceptions/JuliusCesar.txt:
--------------------------------------------------------------------------------
1 | Even you, Brutus?
2 |
--------------------------------------------------------------------------------
/src/com/advanced/exceptions/ZeroDivisorException.java:
--------------------------------------------------------------------------------
1 | package com.advanced.exceptions;
2 |
3 | public class ZeroDivisorException extends Exception {
4 |
5 | public ZeroDivisorException(Exception exception) {
6 | super(exception);
7 | }
8 |
9 | public ZeroDivisorException(String message) {
10 | super(message);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/BufferedReaderApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.FileReader;
5 | import java.io.IOException;
6 | import java.util.stream.Collectors;
7 |
8 | public class BufferedReaderApp {
9 |
10 | public static void main(String[] args) {
11 |
12 | String HAMLET_PART_FILE_PATH = "src\\com\\advanced\\filehandling\\Hamlet.txt";
13 |
14 | try (FileReader hamletReader = new FileReader(HAMLET_PART_FILE_PATH)) {
15 | BufferedReader hamletBufferReader = new BufferedReader(hamletReader, 16384);
16 | String hamletPart = hamletBufferReader.lines()
17 | .collect(Collectors.joining(System.lineSeparator()));
18 | System.out.println(hamletPart);
19 | //readAllLines(hamletBufferReader);
20 |
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 |
25 | }
26 |
27 | private static void readAllLines(BufferedReader hamletBufferReader) throws IOException {
28 | StringBuilder stringBuilder = new StringBuilder();
29 | String line;
30 | while ((line = hamletBufferReader.readLine()) != null) {
31 | stringBuilder.append(line);
32 | stringBuilder.append(System.lineSeparator());
33 | }
34 | System.out.println(stringBuilder.toString());
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/BufferedWriterApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.BufferedWriter;
4 | import java.io.FileWriter;
5 | import java.io.IOException;
6 |
7 | public class BufferedWriterApp {
8 |
9 | public static void main(String[] args) {
10 |
11 | try (BufferedWriter bufferedBookWriter = new BufferedWriter(new FileWriter("src/com/advanced/filehandling/JuliusCesar.txt", true))) {
12 | bufferedBookWriter.write("Even you, Brutus?");
13 | bufferedBookWriter.newLine();
14 | } catch (IOException exception) {
15 | exception.printStackTrace();
16 | }
17 |
18 | }
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/CopyMoveApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 |
4 | import java.io.IOException;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 | import java.nio.file.Paths;
8 | import java.nio.file.StandardCopyOption;
9 |
10 | public class CopyMoveApp {
11 |
12 | public static void main(String[] args) {
13 |
14 | Path originalPath = Paths.get("src/com/advanced/filehandling/JuliusCesar.txt");
15 | Path destinationPath = Paths.get("src/com/advanced/exceptions/JuliusCesar.txt");
16 |
17 | try {
18 | if (Files.exists(originalPath)) {
19 | Files.move(originalPath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
20 | }
21 | } catch (IOException exception) {
22 | exception.printStackTrace();
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/DirectoriesApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.File;
4 | import java.util.Arrays;
5 |
6 | public class DirectoriesApp {
7 |
8 | public static void main(String[] args) {
9 | File businessBooksDirectory = new File("Ebooks\\Business");
10 |
11 | if (businessBooksDirectory.mkdirs()) {
12 | System.out.println("The new directory is created.");
13 | } else {
14 | System.out.println("Can't create the directory.");
15 | }
16 |
17 | businessBooksDirectory.deleteOnExit();
18 |
19 | File fileHandlingDirectory = new File("src\\com\\advanced\\filehandling\\");
20 | System.out.println("Files in the filehandling directory:");
21 | System.out.println(Arrays.toString(fileHandlingDirectory.list()));
22 | System.out.println(Arrays.toString(fileHandlingDirectory.listFiles()));
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/FileHandlingApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 |
6 | public class FileHandlingApp {
7 |
8 | public static void main(String[] args) {
9 | String FILE_HANDLING_DIRECTORY = "src\\com\\advanced\\filehandling\\";
10 | File famousQuotesFile = new File(FILE_HANDLING_DIRECTORY + "famousQuotes.txt");
11 |
12 | try {
13 | if (famousQuotesFile.createNewFile()) {
14 | System.out.println("The file is created.");
15 | }
16 | } catch (IOException exception) {
17 | exception.printStackTrace();
18 | }
19 |
20 | File famousPersonQuotesFile = new File(FILE_HANDLING_DIRECTORY + "famousPersonQuotes.txt");
21 | if (famousQuotesFile.renameTo(famousPersonQuotesFile)) {
22 | System.out.println("The file is renamed.");
23 | }
24 |
25 | if (famousPersonQuotesFile.delete()) {
26 | System.out.println("The file is deleted.");
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/FileReaderApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.FileReader;
4 | import java.io.IOException;
5 |
6 | public class FileReaderApp {
7 |
8 | public static void main(String[] args) {
9 | String HAMLET_PART_FILE_PATH = "src\\com\\advanced\\filehandling\\Hamlet.txt";
10 |
11 | char[] firstHundredCharacters = new char[100];
12 | try (FileReader hamletReader = new FileReader(HAMLET_PART_FILE_PATH)) {
13 | hamletReader.read(firstHundredCharacters);
14 | System.out.println(firstHundredCharacters);
15 | hamletReader.read(firstHundredCharacters);
16 | System.out.println(firstHundredCharacters);
17 | System.out.println("Read more");
18 | } catch (IOException e) {
19 | e.printStackTrace();
20 | }
21 |
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/FileWriterApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.FileWriter;
4 | import java.io.IOException;
5 |
6 | public class FileWriterApp {
7 | public static void main(String[] args) {
8 | String JULIUS_CESAR_FILE_PATH = "src/com/advanced/filehandling/JuliusCesar.txt";
9 |
10 | try (FileWriter bookWriter = new FileWriter(JULIUS_CESAR_FILE_PATH) ){
11 | bookWriter.write("Even you, Brutus?");
12 | bookWriter.append("\nYes.");
13 | } catch (IOException exception) {
14 | exception.printStackTrace();
15 | }
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/PathClassApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.nio.file.Path;
4 | import java.nio.file.Paths;
5 |
6 | public class PathClassApp {
7 |
8 | public static void main(String[] args) {
9 | Path path = Paths.get("src/com/advanced/filehandling/JuliusCesar.txt").toAbsolutePath();
10 |
11 | System.out.println("toString: " + path.toString());
12 | System.out.println("getFileName: " + path.getFileName());
13 | System.out.println("getName(0): " + path.getName(0));
14 | System.out.println("getNameCount: " + path.getNameCount());
15 | System.out.println("subpath(0,2): " + path.subpath(0,2));
16 | System.out.println("getParent: " + path.getParent());
17 | System.out.println("getRoot: " + path.getRoot());
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/PrintWriterApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.FileWriter;
4 | import java.io.IOException;
5 | import java.io.PrintWriter;
6 |
7 | public class PrintWriterApp {
8 |
9 | public static void main(String[] args) {
10 | String JULIUS_CESAR_FILE_PATH = "src/com/advanced/filehandling/JuliusCesar.txt";
11 |
12 | try (PrintWriter bookWriter = new PrintWriter(new FileWriter(JULIUS_CESAR_FILE_PATH, true))) {
13 | bookWriter.println("Even you, Brutus?");
14 | } catch (IOException exception) {
15 | exception.printStackTrace();
16 | }
17 |
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/advanced/filehandling/ScannerApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.filehandling;
2 |
3 | import java.io.File;
4 | import java.io.FileNotFoundException;
5 | import java.util.Scanner;
6 |
7 | public class ScannerApp {
8 |
9 | public static void main(String[] args) {
10 | String HAMLET_PART_FILE_PATH = "src\\com\\advanced\\filehandling\\Hamlet.txt";
11 |
12 | try (Scanner scanner = new Scanner(new File(HAMLET_PART_FILE_PATH))){
13 | scanner.useDelimiter(",");
14 | while (scanner.hasNext()) {
15 | System.out.println(scanner.next());
16 | }
17 | } catch (FileNotFoundException e) {
18 | e.printStackTrace();
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/advanced/finalpractice/HangmanApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.finalpractice;
2 |
3 | import java.io.FileNotFoundException;
4 |
5 | public class HangmanApp {
6 |
7 | public static void main(String[] args) throws FileNotFoundException {
8 | GameService gameService = new GameService();
9 | gameService.start();
10 |
11 |
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/advanced/finalpractice/words.txt:
--------------------------------------------------------------------------------
1 | java
2 | tea
3 | book
4 | dodge
--------------------------------------------------------------------------------
/src/com/advanced/generics/Box.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics;
2 |
3 | public class Box {
4 |
5 | private T typeData;
6 |
7 | public void setTypeData(T typeData) {
8 | this.typeData = typeData;
9 | }
10 |
11 | public T getTypeData() {
12 | return typeData;
13 | }
14 |
15 | @Override
16 | public String toString() {
17 | return "Box{" +
18 | "typeData=" + typeData +
19 | '}';
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/advanced/generics/GenericsApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class GenericsApp {
6 |
7 | public static void main(String[] args) {
8 |
9 | Box myFavoriteNumber = new Box<>();
10 | myFavoriteNumber.setTypeData(-15);
11 | Util.displayToString(myFavoriteNumber);
12 |
13 | Box myFavoriteActor = new Box<>();
14 | myFavoriteActor.setTypeData("Russel Crow");
15 | Util.displayToString(myFavoriteActor);
16 |
17 | ArrayList> pileOfBoxes = new ArrayList<>();
18 | pileOfBoxes.add(myFavoriteActor);
19 | pileOfBoxes.add(myFavoriteActor);
20 | Util.displayToString(pileOfBoxes);
21 |
22 | OrderedPair kobeBryant = new OrderedPair<>(24, "Kobe Bryant");
23 | Util.displayToString(kobeBryant);
24 |
25 | ArrayList> listOfCountries = new ArrayList<>();
26 | OrderedPair malta = new OrderedPair<>("MLT", "Malta");
27 | OrderedPair germany = new OrderedPair<>("GER", "Germany");
28 |
29 | listOfCountries.add(malta);
30 | listOfCountries.add(germany);
31 | Util.displayToString(listOfCountries);
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/advanced/generics/OrderedPair.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics;
2 |
3 | public class OrderedPair implements Pair {
4 |
5 | private K key;
6 | private V value;
7 |
8 | public OrderedPair(K key, V value) {
9 | this.key = key;
10 | this.value = value;
11 | }
12 |
13 | @Override
14 | public K getKey() {
15 | return key;
16 | }
17 |
18 | @Override
19 | public V getValue() {
20 | return value;
21 | }
22 |
23 | @Override
24 | public String toString() {
25 | return "OrderedPair{" +
26 | "key=" + key +
27 | ", value=" + value +
28 | '}';
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/advanced/generics/Pair.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics;
2 |
3 | public interface Pair {
4 |
5 | public K getKey();
6 | public V getValue();
7 | }
8 |
--------------------------------------------------------------------------------
/src/com/advanced/generics/Util.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics;
2 |
3 | public class Util {
4 |
5 | public static void displayToString(T typeData) {
6 | System.out.println(typeData.toString());
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/advanced/generics/weirdpart/GenericFunctions.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics.weirdpart;
2 |
3 | import java.util.ArrayList;
4 | public class GenericFunctions {
5 |
6 | public static void displayToString(T typeData) {
7 | System.out.println(typeData.toString());
8 | }
9 |
10 | public static void addNumbers(ArrayList super Integer> list) {
11 | for (int i = 1; i <= 10; i++) {
12 | list.add(i);
13 | }
14 | }
15 |
16 | public static void printList(ArrayList> list) {
17 | for(Object element : list) {
18 | System.out.print(element + " ");
19 | }
20 | System.out.println();
21 | }
22 |
23 | public void printSimpleGenerics(ArrayList list) {
24 | for(Object element : list) {
25 | System.out.print(element + " ");
26 | }
27 | System.out.println();
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/advanced/generics/weirdpart/GenericsWeirdPartApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.generics.weirdpart;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 |
6 | public class GenericsWeirdPartApp {
7 |
8 | public static void main(String[] args) {
9 | ArrayList lotteryNumbers = new ArrayList<>(Arrays.asList(23, 45, 57, 82, 14));
10 | GenericFunctions.addNumbers(lotteryNumbers);
11 | GenericFunctions.printList(lotteryNumbers);
12 | GenericFunctions.displayToString(lotteryNumbers);
13 |
14 | GenericFunctions genericFunctions = new GenericFunctions<>();
15 | //Remove the comment to see the issue with taking lotteryNumbers as parameter
16 | //genericFunctions.printSimpleGenerics(lotteryNumbers);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/advanced/innerclasses/InnerClassesApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.innerclasses;
2 |
3 | import com.advanced.enumcoding.PizzaSize;
4 |
5 |
6 |
7 | public class InnerClassesApp {
8 |
9 | private static boolean isPizzaReady(int waitedInMinutes) {
10 | class Oven {
11 | public boolean isPizzaBakedProperly() {
12 | if (waitedInMinutes > 30) {
13 | return true;
14 | }
15 | return false;
16 | }
17 | }
18 | Oven oven = new Oven();
19 | return oven.isPizzaBakedProperly();
20 | }
21 |
22 | public static void main(String[] args) {
23 | Pizza firstPizza = new Pizza("Margherita", PizzaSize.MEDIUM);
24 | System.out.println("Name: " + firstPizza.getName());
25 | Pizza secondPizza = new Pizza("Margherita", PizzaSize.MEDIUM) {
26 | @Override
27 | public String getName() {
28 | return "Anonymous";
29 | }
30 | };
31 | System.out.println("Name: " + secondPizza.getName());
32 |
33 | if (isPizzaReady(40)){
34 | System.out.println("The pizza is ready.");
35 | } else {
36 | System.out.println("The pizza is not ready yet.");
37 | }
38 |
39 | Pizza thirdPizza = new Pizza("Pizza cake", PizzaSize.LARGE);
40 | Pizza.PizzaSlice pizzaSlice = thirdPizza.cutPizzaSlice();
41 | System.out.println(pizzaSlice.calculatePizzaSliceArea());
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/advanced/innerclasses/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.innerclasses;
2 |
3 | import com.advanced.enumcoding.PizzaSize;
4 |
5 | public class Pizza {
6 |
7 | private String name;
8 | private PizzaSize pizzaSize;
9 | private double price;
10 |
11 | public Pizza(String name, PizzaSize pizzaSize) {
12 | this.name = name;
13 | this.pizzaSize = pizzaSize;
14 | this.price = calculatePrice();
15 | }
16 |
17 | class PizzaSlice {
18 | public String calculatePizzaSliceArea() {
19 | switch (pizzaSize) {
20 | case SMALL:
21 | default:
22 | return "Small slice";
23 | case MEDIUM:
24 | return "Medium slice";
25 | case LARGE:
26 | return "Large slice";
27 | }
28 | }
29 | }
30 |
31 | public PizzaSlice cutPizzaSlice() {
32 | return new PizzaSlice();
33 | }
34 |
35 | private double calculatePrice() {
36 | switch (pizzaSize) {
37 | case SMALL:
38 | default:
39 | return 5.99;
40 | case MEDIUM:
41 | return 7.99;
42 | case LARGE:
43 | return 10.99;
44 | }
45 | }
46 |
47 | public void setName(String name) {
48 | this.name = name;
49 | }
50 |
51 | public String getName() {
52 | return name;
53 | }
54 |
55 | public PizzaSize getPizzaSize() {
56 | return pizzaSize;
57 | }
58 |
59 | public double getPrice() {
60 | return price;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/com/advanced/innerclasses/staticnested/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.innerclasses.staticnested;
2 |
3 | import com.advanced.enumcoding.PizzaSize;
4 |
5 | public class Pizza {
6 | private String name;
7 | private PizzaSize pizzaSize;
8 | private boolean isExtraTomatoSauce;
9 | private boolean isSalad;
10 |
11 | private Pizza(Builder builder) {
12 | this.name = builder.name;
13 | this.pizzaSize = builder.pizzaSize;
14 | this.isExtraTomatoSauce = builder.isExtraTomatoSauce;
15 | this.isSalad = builder.isSalad;
16 | }
17 |
18 | public String getName() {
19 | return name;
20 | }
21 |
22 | public PizzaSize getPizzaSize() {
23 | return pizzaSize;
24 | }
25 |
26 | public boolean isExtraTomatoSauce() {
27 | return isExtraTomatoSauce;
28 | }
29 |
30 | public boolean isSalad() {
31 | return isSalad;
32 | }
33 |
34 | public static class Builder {
35 | private String name;
36 | private PizzaSize pizzaSize;
37 | private boolean isExtraTomatoSauce;
38 | private boolean isSalad;
39 |
40 | Builder(String name, PizzaSize pizzaSize) {
41 | this.name = name;
42 | this.pizzaSize = pizzaSize;
43 | }
44 |
45 | public Builder withExtraTomatoSauce(boolean isExtraTomatoSauce) {
46 | this.isExtraTomatoSauce = isExtraTomatoSauce;
47 | return this;
48 | }
49 |
50 | public Builder withSalad(boolean isSalad) {
51 | this.isSalad = isSalad;
52 | return this;
53 | }
54 |
55 | public Pizza build(){
56 | return new Pizza(this);
57 | }
58 |
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/com/advanced/innerclasses/staticnested/PizzaBuilderApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.innerclasses.staticnested;
2 |
3 | import com.advanced.enumcoding.PizzaSize;
4 |
5 | public class PizzaBuilderApp {
6 |
7 | public static void main(String[] args) {
8 | Pizza pizza = new Pizza.Builder("Pizza cake", PizzaSize.LARGE)
9 | .withExtraTomatoSauce(true)
10 | .withSalad(true)
11 | .build();
12 | System.out.println("Name: " + pizza.getName());
13 | System.out.println("Size: " + pizza.getPizzaSize().getPizzaSizeText());
14 | System.out.println("Extra tomato sauce: " + pizza.isExtraTomatoSauce());
15 | System.out.println("Salad: " + pizza.isSalad());
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/com/advanced/io/CharacterApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.io;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CharacterApp {
6 |
7 | public static void main(String[] args) {
8 | Scanner userInput = new Scanner(System.in);
9 |
10 | System.out.println("Welcome to World of Warlords");
11 | System.out.println("Here you can create your character: ");
12 |
13 | System.out.print("Name: ");
14 | String name = userInput.nextLine();
15 |
16 | System.out.println("Race (human or orc): ");
17 | while (!userInput.hasNext("human") && !userInput.hasNext("orc")) {
18 | System.err.println("Invalid input, you need to type in human or orc.");
19 | userInput.nextLine();
20 | }
21 | String race = userInput.nextLine();
22 |
23 | System.out.println("Difficulty (0 - easy, 1 - medium, 2 - hard): ");
24 | while (!userInput.hasNextByte(3)) {
25 | System.err.println("Invalid input, you need to type in 0 or 1 or 2.");
26 | userInput.nextLine();
27 | }
28 | byte difficulty = userInput.nextByte();
29 |
30 | System.out.println("Nightmare mode is on (true or false): ");
31 | while (!userInput.hasNextBoolean()) {
32 | System.err.println("Invalid input, you need to type in true or false.");
33 | userInput.nextLine();
34 | }
35 | boolean isNightmareModeOn = userInput.nextBoolean();
36 |
37 |
38 | System.out.println("-------------------------------");
39 | System.out.println("You character is created: ");
40 | System.out.printf("Name: \t\t%s\n", name);
41 | System.out.printf("Race: \t\t%s\n", race);
42 | System.out.printf("Difficulty: \t%d\n", difficulty);
43 | System.out.printf("Nightmare mode is on: \t%b\n", isNightmareModeOn);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/advanced/mathfunctions/MathFunctionsApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.mathfunctions;
2 |
3 | public class MathFunctionsApp {
4 |
5 | public static void main(String[] args) {
6 |
7 | double temperatureYesterday = -5.6;
8 | double temperatureToday = -Math.random() * 10;
9 |
10 | System.out.println("Absolute temperature today: " + Math.abs(temperatureToday));
11 | System.out.println("Min: " + Math.min(temperatureToday, temperatureYesterday));
12 | System.out.println("Max: " + Math.max(temperatureToday, temperatureYesterday));
13 | System.out.println("Round: " + Math.round(temperatureToday));
14 | System.out.println("Ceiling: " + Math.ceil(temperatureToday));
15 | System.out.println("Floor: " + Math.floor(temperatureToday));
16 |
17 |
18 | System.out.println("Power: " + Math.pow(temperatureToday, 2));
19 | System.out.println("Square root: " + Math.sqrt(Math.abs(temperatureToday)));
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/advanced/objectclone/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectclone;
2 |
3 | import java.util.Objects;
4 |
5 | public class Pizza implements Cloneable{
6 |
7 | private String name;
8 | private PizzaSize pizzaSize;
9 | private double price;
10 |
11 | public Pizza(String name, PizzaSize pizzaSize) {
12 | this.name = name;
13 | this.pizzaSize = pizzaSize;
14 | this.price = calculatePrice();
15 | }
16 |
17 | private double calculatePrice() {
18 | switch (pizzaSize) {
19 | case SMALL:
20 | default:
21 | return 5.99;
22 | case MEDIUM:
23 | return 7.99;
24 | case LARGE:
25 | return 10.99;
26 | }
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public PizzaSize getPizzaSize() {
34 | return pizzaSize;
35 | }
36 |
37 | public double getPrice() {
38 | return price;
39 | }
40 |
41 | @Override
42 | protected Object clone() throws CloneNotSupportedException {
43 | return super.clone();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/com/advanced/objectclone/PizzaApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectclone;
2 |
3 | public class PizzaApp {
4 |
5 | public static void main(String[] args) throws CloneNotSupportedException {
6 | System.out.println("Available sizes:");
7 | for (PizzaSize pizzaSize : PizzaSize.values()) {
8 | System.out.println("- " + pizzaSize.getPizzaSizeText());
9 | }
10 | System.out.println();
11 |
12 | Pizza pizzaOrder = new Pizza("Margareta", PizzaSize.MEDIUM);
13 | System.out.println("I ordered the following pizza:");
14 | System.out.println("Name: " + pizzaOrder.getName());
15 | System.out.println("Size: " + pizzaOrder.getPizzaSize().getPizzaSizeText());
16 | System.out.println("Price: $" + pizzaOrder.getPrice());
17 |
18 | Pizza samePizza = (Pizza) pizzaOrder.clone();
19 | System.out.println("I ordered another pizza:");
20 | System.out.println("Name: " + samePizza.getName());
21 | System.out.println("Size: " + samePizza.getPizzaSize().getPizzaSizeText());
22 | System.out.println("Price: $" + samePizza.getPrice());
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/advanced/objectclone/PizzaSize.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectclone;
2 |
3 | public enum PizzaSize {
4 | SMALL("Small size"), MEDIUM("Medium size"), LARGE("Large size");
5 |
6 | private String pizzaSizeText;
7 |
8 | PizzaSize(String pizzaSizeText) {
9 | this.pizzaSizeText = pizzaSizeText;
10 | }
11 |
12 | public String getPizzaSizeText() {
13 | return pizzaSizeText;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/advanced/objectequals/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectequals;
2 |
3 | import java.util.Arrays;
4 | import java.util.Objects;
5 |
6 | public class Pizza implements Cloneable{
7 |
8 | private String name;
9 | private PizzaSize pizzaSize;
10 | private double price;
11 |
12 | public Pizza(String name, PizzaSize pizzaSize) {
13 | this.name = name;
14 | this.pizzaSize = pizzaSize;
15 | this.price = calculatePrice();
16 | }
17 |
18 | private double calculatePrice() {
19 | switch (pizzaSize) {
20 | case SMALL:
21 | default:
22 | return 5.99;
23 | case MEDIUM:
24 | return 7.99;
25 | case LARGE:
26 | return 10.99;
27 | }
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 |
34 | public PizzaSize getPizzaSize() {
35 | return pizzaSize;
36 | }
37 |
38 | public double getPrice() {
39 | return price;
40 | }
41 |
42 | @Override
43 | protected Object clone() throws CloneNotSupportedException {
44 | return super.clone();
45 | }
46 |
47 | @Override
48 | public boolean equals(Object o) {
49 | if (this == o) {
50 | return true;
51 | }
52 | if (!(o instanceof Pizza)) {
53 | return false;
54 | }
55 | Pizza pizza = (Pizza) o;
56 | return Objects.equals(pizza.name, name) &&
57 | price == pizza.price &&
58 | pizzaSize == pizza.pizzaSize;
59 |
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/com/advanced/objectequals/PizzaApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectequals;
2 |
3 | public class PizzaApp {
4 |
5 | public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException {
6 | System.out.println("Available sizes:");
7 | for (PizzaSize pizzaSize : PizzaSize.values()) {
8 | System.out.println("- " + pizzaSize.getPizzaSizeText());
9 | }
10 | System.out.println();
11 |
12 | Pizza pizzaOrder = new Pizza("Margareta", PizzaSize.MEDIUM);
13 | System.out.println("I ordered the following pizza:");
14 | System.out.println("Name: " + pizzaOrder.getName());
15 | System.out.println("Size: " + pizzaOrder.getPizzaSize().getPizzaSizeText());
16 | System.out.println("Price: $" + pizzaOrder.getPrice());
17 |
18 | Pizza samePizza = (Pizza) pizzaOrder.clone();
19 | System.out.println("I ordered another pizza:");
20 | System.out.println("Name: " + samePizza.getName());
21 | System.out.println("Size: " + samePizza.getPizzaSize().getPizzaSizeText());
22 | System.out.println("Price: $" + samePizza.getPrice());
23 |
24 | Pizza anotherPizza = new Pizza("Margareta", PizzaSize.LARGE);
25 | System.out.println(pizzaOrder.equals(anotherPizza));
26 |
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/com/advanced/objectequals/PizzaSize.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectequals;
2 |
3 | public enum PizzaSize {
4 | SMALL("Small size"), MEDIUM("Medium size"), LARGE("Large size");
5 |
6 | private String pizzaSizeText;
7 |
8 | PizzaSize(String pizzaSizeText) {
9 | this.pizzaSizeText = pizzaSizeText;
10 | }
11 |
12 | public String getPizzaSizeText() {
13 | return pizzaSizeText;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/advanced/objectgetclass/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectgetclass;
2 |
3 | import java.util.Objects;
4 |
5 | public class Pizza implements Cloneable{
6 |
7 | private String name;
8 | private PizzaSize pizzaSize;
9 | private double price;
10 |
11 | public Pizza(String name, PizzaSize pizzaSize) {
12 | this.name = name;
13 | this.pizzaSize = pizzaSize;
14 | this.price = calculatePrice();
15 | }
16 |
17 | private double calculatePrice() {
18 | switch (pizzaSize) {
19 | case SMALL:
20 | default:
21 | return 5.99;
22 | case MEDIUM:
23 | return 7.99;
24 | case LARGE:
25 | return 10.99;
26 | }
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public PizzaSize getPizzaSize() {
34 | return pizzaSize;
35 | }
36 |
37 | public double getPrice() {
38 | return price;
39 | }
40 |
41 | @Override
42 | protected Object clone() throws CloneNotSupportedException {
43 | return super.clone();
44 | }
45 |
46 | @Override
47 | public boolean equals(Object o) {
48 | if (this == o) {
49 | return true;
50 | }
51 | if (!(o instanceof Pizza)) {
52 | return false;
53 | }
54 | Pizza pizza = (Pizza) o;
55 | return Objects.equals(pizza.name, name) &&
56 | price == pizza.price &&
57 | pizzaSize == pizza.pizzaSize;
58 |
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/src/com/advanced/objectgetclass/PizzaApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectgetclass;
2 |
3 | import java.util.Arrays;
4 |
5 | public class PizzaApp {
6 |
7 | public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException {
8 | System.out.println("Available sizes:");
9 | for (PizzaSize pizzaSize : PizzaSize.values()) {
10 | System.out.println("- " + pizzaSize.getPizzaSizeText());
11 | }
12 | System.out.println();
13 |
14 | Pizza pizzaOrder = new Pizza("Margareta", PizzaSize.MEDIUM);
15 | System.out.println("I ordered the following pizza:");
16 | System.out.println("Name: " + pizzaOrder.getName());
17 | System.out.println("Size: " + pizzaOrder.getPizzaSize().getPizzaSizeText());
18 | System.out.println("Price: $" + pizzaOrder.getPrice());
19 |
20 | Pizza samePizza = (Pizza) pizzaOrder.clone();
21 | System.out.println("I ordered another pizza:");
22 | System.out.println("Name: " + samePizza.getName());
23 | System.out.println("Size: " + samePizza.getPizzaSize().getPizzaSizeText());
24 | System.out.println("Price: $" + samePizza.getPrice());
25 |
26 | Pizza anotherPizza = new Pizza("Margareta", PizzaSize.LARGE);
27 | System.out.println(pizzaOrder.equals(anotherPizza));
28 |
29 | System.out.println("---------------------------------");
30 | System.out.println(anotherPizza.getClass().getSimpleName());
31 | System.out.println(anotherPizza.getClass().getName());
32 | System.out.println(Arrays.toString(anotherPizza.getClass().getFields()));
33 | System.out.println(Arrays.toString(anotherPizza.getClass().getDeclaredFields()));
34 | System.out.println(Arrays.toString(anotherPizza.getClass().getMethods()));
35 | System.out.println(Arrays.toString(anotherPizza.getClass().getDeclaredMethods()));
36 | System.out.println(anotherPizza.getClass().getSuperclass());
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/advanced/objectgetclass/PizzaSize.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objectgetclass;
2 |
3 | public enum PizzaSize {
4 | SMALL("Small size"), MEDIUM("Medium size"), LARGE("Large size");
5 |
6 | private String pizzaSizeText;
7 |
8 | PizzaSize(String pizzaSizeText) {
9 | this.pizzaSizeText = pizzaSizeText;
10 | }
11 |
12 | public String getPizzaSizeText() {
13 | return pizzaSizeText;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/advanced/objecthashcode/Pizza.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objecthashcode;
2 |
3 | import java.util.Objects;
4 |
5 | public class Pizza implements Cloneable{
6 |
7 | private String name;
8 | private PizzaSize pizzaSize;
9 | private double price;
10 |
11 | public Pizza(String name, PizzaSize pizzaSize) {
12 | this.name = name;
13 | this.pizzaSize = pizzaSize;
14 | this.price = calculatePrice();
15 | }
16 |
17 | private double calculatePrice() {
18 | switch (pizzaSize) {
19 | case SMALL:
20 | default:
21 | return 5.99;
22 | case MEDIUM:
23 | return 7.99;
24 | case LARGE:
25 | return 10.99;
26 | }
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public PizzaSize getPizzaSize() {
34 | return pizzaSize;
35 | }
36 |
37 | public double getPrice() {
38 | return price;
39 | }
40 |
41 | @Override
42 | protected Object clone() throws CloneNotSupportedException {
43 | return super.clone();
44 | }
45 |
46 | @Override
47 | public boolean equals(Object o) {
48 | if (this == o) {
49 | return true;
50 | }
51 | if (!(o instanceof Pizza)) {
52 | return false;
53 | }
54 | Pizza pizza = (Pizza) o;
55 | return Objects.equals(pizza.name, name) &&
56 | price == pizza.price &&
57 | pizzaSize == pizza.pizzaSize;
58 |
59 | }
60 |
61 | @Override
62 | public int hashCode() {
63 | return Objects.hash(name, pizzaSize, price);
64 |
65 | // int result = 7;
66 | //
67 | // result = 31 * result + (name == null ? 0 : name.hashCode());
68 | // result = 31 * result + (pizzaSize == null ? 0 : pizzaSize.hashCode());
69 | // result = 31 * result + Double.valueOf(price).hashCode();
70 | //
71 | // return result;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/com/advanced/objecthashcode/PizzaSize.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objecthashcode;
2 |
3 | public enum PizzaSize {
4 | SMALL("Small size"), MEDIUM("Medium size"), LARGE("Large size");
5 |
6 | private String pizzaSizeText;
7 |
8 | PizzaSize(String pizzaSizeText) {
9 | this.pizzaSizeText = pizzaSizeText;
10 | }
11 |
12 | public String getPizzaSizeText() {
13 | return pizzaSizeText;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/advanced/objecttostring/PizzaSize.java:
--------------------------------------------------------------------------------
1 | package com.advanced.objecttostring;
2 |
3 | public enum PizzaSize {
4 | SMALL("Small size"), MEDIUM("Medium size"), LARGE("Large size");
5 |
6 | private String pizzaSizeText;
7 |
8 | PizzaSize(String pizzaSizeText) {
9 | this.pizzaSizeText = pizzaSizeText;
10 | }
11 |
12 | public String getPizzaSizeText() {
13 | return pizzaSizeText;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/advanced/string/StringPerformanceApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.string;
2 |
3 | public class StringPerformanceApp {
4 |
5 | public static void main(String[] args) {
6 | long startTime = System.nanoTime();
7 |
8 | String testString = "";
9 | for (int i = 0; i <= 100000; i++) {
10 | testString += i;
11 | }
12 |
13 | // StringBuilder something = new StringBuilder("");
14 | // for (int i = 0; i <= 100000; i++) {
15 | // something.append(i);
16 | // }
17 | //
18 | // StringBuffer anything = new StringBuffer("");
19 | // for (int i = 0; i <= 100000; i++) {
20 | // anything.append(i);
21 | // }
22 |
23 | long endTime = System.nanoTime();
24 | long totalTime = endTime - startTime;
25 | System.out.println("It took " + totalTime / 1000000 + "ms");
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/advanced/stringtokenizer/StringTokenizerApp.java:
--------------------------------------------------------------------------------
1 | package com.advanced.stringtokenizer;
2 |
3 | import java.util.StringTokenizer;
4 |
5 | public class StringTokenizerApp {
6 |
7 | public static void main(String[] args) {
8 |
9 | String starWarsQuote = "May,the,force,be,with,you!";
10 |
11 | System.out.println("We are using StringTokenizer here: ");
12 | StringTokenizer stringTokenizer = new StringTokenizer(starWarsQuote, ",");
13 | System.out.println("Number of tokens: " + stringTokenizer.countTokens());
14 | while (stringTokenizer.hasMoreTokens()) {
15 | System.out.println(stringTokenizer.nextToken());
16 | }
17 |
18 | System.out.println("We are using String's split function here: ");
19 | String[] starWarsQuoteWords = starWarsQuote.split(",", 3);
20 | System.out.println("Number of elements: " + starWarsQuoteWords.length);
21 | for (String starWarsQuoteWord : starWarsQuoteWords ) {
22 | System.out.println(starWarsQuoteWord);
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/beginner/arrays/ArraysApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.arrays;
2 |
3 | public class ArraysApp {
4 | public static void main(String[] args) {
5 | int[] lotteryNumbers = new int[5];
6 |
7 | lotteryNumbers[0] = 17;
8 | lotteryNumbers[1] = 23;
9 | lotteryNumbers[2] = 67;
10 | lotteryNumbers[3] = 37;
11 | lotteryNumbers[4] = 11;
12 |
13 |
14 | for (int lotteryNumber : lotteryNumbers){
15 | System.out.println(lotteryNumber);
16 | }
17 |
18 | int[][] weeklyLotteryNumbers = {
19 | {1, 2, 3, 4, 5},
20 | {10, 20, 30, 40, 50},
21 | {13, 24, 35, 46, 57},
22 | {10, 23, 35, 48, 58}
23 | };
24 |
25 | for (int i = 0; i < weeklyLotteryNumbers.length; i++) {
26 | for (int j = 0; j < weeklyLotteryNumbers[i].length; j++) {
27 | System.out.print(weeklyLotteryNumbers[i][j] + " ");
28 | }
29 | System.out.println();
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/beginner/controlflow/ControlFlowApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.controlflow;
2 |
3 | public class ControlFlowApp {
4 | public static void main(String[] args) {
5 | boolean isDamaged = false;
6 | String carColor = "purple";
7 | char energyEfficiencyCategory = 'Z';
8 |
9 | if (isDamaged) {
10 | System.out.println("Damaged car");
11 | } else {
12 | System.out.println("Accident free car");
13 | }
14 |
15 | if (carColor.equals("red")) {
16 | System.out.println("This car is red");
17 | } else if (carColor.equals("green")) {
18 | System.out.println("This car is green");
19 | } else if (carColor.equals("blue")) {
20 | System.out.println("This car is blue");
21 | } else {
22 | System.out.println("I have no idea what's the color of the car");
23 | }
24 |
25 | switch (energyEfficiencyCategory) {
26 | case 'A':
27 | case 'B':
28 | System.out.println("Low energy consumption");
29 | break;
30 | case 'G':
31 | System.out.println("Very high energy consumption");
32 | break;
33 | default:
34 | System.out.println("Not defined category");
35 | }
36 |
37 | {
38 | int numberOfOwners = 5;
39 | {
40 | numberOfOwners++;
41 | }
42 | System.out.println("Number of owners: " + numberOfOwners);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/beginner/controlflow/WhoWantsToBeAMillionaireApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.controlflow;
2 |
3 | public class WhoWantsToBeAMillionaireApp {
4 | public static void main(String[] args) {
5 | char answer = 'C';
6 |
7 | System.out.println("Who is named as the inventor of the light bulb?");
8 | System.out.println("You marked " + answer + ". Let's see whether you are right!");
9 |
10 | if (answer == 'C'){
11 | System.out.println("You were right. You won $1.");
12 | } else {
13 | System.out.println("Sorry, the right answer is Tomas Edison. Thanks you for coming.");
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/beginner/datatypes/object/references/ObjectReferencesApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.datatypes.object.references;
2 |
3 | public class ObjectReferencesApp {
4 | public static void main(String[] args) {
5 | Byte numberOfSeats = 5;
6 | Short horsePower = 392;
7 | Integer price = 14999;
8 | Long registrationNumber = 23452352345245234L;
9 |
10 | Float fuelConsumptionUrban = 15.5F;
11 | Double fuelConsumptionPreciseAverage = 15.235252345;
12 |
13 | Boolean isDamaged = true;
14 | Character energyEfficiencyCategory = 'G';
15 |
16 | String carType = "Dodge Challenger SRT 392";
17 | String carTypeWithNewKeyword = new String("Dodge Challenger SRT 392");
18 |
19 | System.out.println("Number of seats: " + numberOfSeats);
20 | System.out.println("Horsepower: " + horsePower + "hp");
21 | System.out.println("Price: €" + price.floatValue() );
22 | System.out.println("Registration number: " + registrationNumber);
23 | System.out.println("Urban fuel consumption: " + fuelConsumptionUrban + "l/100km");
24 | System.out.println("Precise average fuel consumption: " + fuelConsumptionPreciseAverage.intValue() + "l/100km");
25 | System.out.println("The car is damaged: " + isDamaged);
26 | System.out.println("Energy efficiency category: " + energyEfficiencyCategory);
27 | System.out.println("Car model: " + carType);
28 | System.out.println("Car model with uppercase: " + carType.toUpperCase());
29 | System.out.println("Car model with lowercase: " + carType.toLowerCase());
30 | System.out.println("Car model with new keyword: " + carTypeWithNewKeyword);
31 | System.out.println("carType variable equals to carTypeWithNewKeyword: " + carTypeWithNewKeyword.equals(carType));
32 |
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/beginner/endsection/IMDBApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.endsection;
2 |
3 | public class IMDBApp {
4 | public static void main(String[] args) {
5 | String actorName = "Tom Cruise";
6 | int yearOfBorn = 1962;
7 | int age = 2020 - yearOfBorn;
8 |
9 | String[] movieTitles = {
10 | "The Last Samurai", "Minority Report", "Top Gun",
11 | "Rain Man", "Cocktail", "The Mummy", "American Made"
12 | };
13 |
14 | float[] movieRatings = {
15 | 7.7F, 7.6F, 6.9F,
16 | 8.0F, 5.9F, 5.4F, 7.1F
17 | };
18 |
19 | System.out.println("Actor's name: " + actorName);
20 | System.out.println("Born: " + yearOfBorn + " (" + age + " years old)");
21 |
22 | System.out.println("Movies:");
23 |
24 | for (int i = 0; i < movieTitles.length; i++) {
25 | System.out.println(movieTitles[i] + " - " + getRating(movieRatings[i]));
26 | }
27 | }
28 |
29 | static String getRating(float rating){
30 | if (rating <= 5.0){
31 | return "bad";
32 | } else if (rating > 5.0 && rating <= 6.5){
33 | return "average";
34 | } else if (rating > 6.5 && rating <= 7.0){
35 | return "good";
36 | } else if (rating > 7.0 && rating <= 8.0){
37 | return "very good";
38 | }else{
39 | return "amazing";
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/beginner/loops/LoopsApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.loops;
2 |
3 | public class LoopsApp {
4 | public static void main(String[] args) {
5 | int i = 1;
6 | while (i <= 0){
7 | System.out.println(i +". BEING RIGHT SUCKS");
8 | i++;
9 | }
10 | System.out.println("Value of i: " + i);
11 | System.out.println();
12 |
13 | int j = 1;
14 | do {
15 | System.out.println(j +". BEING RIGHT SUCKS");
16 | j++;
17 | } while(j <= 0);
18 | System.out.println("Value of j: " + j);
19 | System.out.println();
20 |
21 | for (int k = 1; k<=5; k++){
22 | if(k ==3){
23 | break;
24 | }
25 | System.out.println(k +". BEING RIGHT SUCKS");
26 | }
27 | System.out.println();
28 |
29 | for (int k = 1; k<=5; k++){
30 | for (int l = 1; l<=2; l++){
31 | System.out.println("k=" + k + " l=" + l + " BEING RIGHT SUCKS");
32 | }
33 | }
34 | System.out.println();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/beginner/variables/MyFirstJavaApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.variables;
2 |
3 | public class MyFirstJavaApp {
4 |
5 | public static void main(String[] args) {
6 | int numberOfFollowers = 195;
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/beginner/yourfirstjavacode/MyFirstJavaApp.java:
--------------------------------------------------------------------------------
1 | package com.beginner.yourfirstjavacode;
2 |
3 | public class MyFirstJavaApp {
4 |
5 | public static void main(String[] args) {
6 | System.out.println("May the force be with you!");
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/basics/FunctionalProgrammingApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.basics;
2 |
3 | import java.util.Scanner;
4 |
5 | public class FunctionalProgrammingApp {
6 |
7 | public static void main(String[] args) {
8 | WelcomeMessageService welcomeMessageService = new WelcomeMessageService();
9 | Scanner userStatusScanner = new Scanner(System.in);
10 | String userStatus = userStatusScanner.nextLine();
11 |
12 | Greeter greeter;
13 | if ("guest".equals(userStatus)) {
14 | greeter = () -> System.out.println("Welcome to your application. Please create an account or log in.");
15 | } else if ("loggedIn".equals(userStatus)) {
16 | greeter = () -> System.out.println("Welcome back.");
17 | } else {
18 | greeter = () -> System.err.println("Unknown user status!");
19 | }
20 |
21 | welcomeMessageService.greet(greeter);
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/basics/Greeter.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.basics;
2 |
3 | public interface Greeter {
4 | void perform();
5 | }
6 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/basics/GuestUserGreeter.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.basics;
2 |
3 | public class GuestUserGreeter implements Greeter{
4 | @Override
5 | public void perform() {
6 | System.out.println("Welcome to our application. Please create an account or log in!");
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/basics/LoggedInUserGreeter.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.basics;
2 |
3 | public class LoggedInUserGreeter implements Greeter{
4 | @Override
5 | public void perform() {
6 | System.out.println("Welcome back.");
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/basics/WelcomeMessageService.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.basics;
2 |
3 | public class WelcomeMessageService {
4 |
5 | public void greet(Greeter greeter) {
6 | greeter.perform();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/biconsumer/LambdaBiConsumerApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.biconsumer;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.function.BiConsumer;
6 |
7 | public class LambdaBiConsumerApp {
8 |
9 | public static void main(String[] args) {
10 | BiConsumer printAttribute = (text, number) -> System.out.println(text + number);
11 | printAttribute.accept("Points: ",10);
12 | printAttribute.accept("Price: $",14000);
13 |
14 | BiConsumer, Integer> multiplyNumbers = (list, number)-> {
15 | for (int i = 0; i < list.size(); i++) {
16 | list.set(i, list.get(i) * number);
17 | }
18 | };
19 | List numbers = Arrays.asList(5,4,3,2,1);
20 | multiplyNumbers.accept(numbers, 5);
21 | System.out.println(numbers);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/bifunction/LambdaBiFunctionApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.bifunction;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.function.BiFunction;
6 |
7 | public class LambdaBiFunctionApp {
8 |
9 | public static void main(String[] args) {
10 | BiFunction getPow = (numberOne, numberTwo) -> Math.pow(numberOne, numberTwo);
11 | System.out.println(getPow.apply(5, 2));
12 |
13 | BiFunction> generateList = (size, multiply) -> {
14 | List generatedList = new ArrayList<>();
15 | for (int i = 0; i < size; i++) {
16 | generatedList.add(i * multiply);
17 | }
18 | return generatedList;
19 | };
20 | System.out.println(generateList.apply(10, 1));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/consumer/LambdaConsumerApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.consumer;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.function.Consumer;
6 |
7 | public class LambdaConsumerApp {
8 |
9 | public static void main(String[] args) {
10 | Consumer printMultiplyNumber = number -> System.out.println(number * 4);
11 | printMultiplyNumber.accept(10);
12 |
13 | Consumer> multiplyNumbers = list -> {
14 | for (int i = 0; i < list.size(); i++) {
15 | list.set(i, list.get(i) * 3);
16 | }
17 | };
18 | List numbers = Arrays.asList(5,4,3,2,1);
19 | multiplyNumbers.accept(numbers);
20 | System.out.println(numbers);
21 |
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/listpractice/ListLambdaExpressionApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.listpractice;
2 |
3 | import java.util.List;
4 |
5 | public class ListLambdaExpressionApp {
6 | public static void main(String[] args) {
7 | List inputNumbers = List.of(1, 2, 3, 4, 5);
8 |
9 | NumberOperationService numberOperationService = new NumberOperationService();
10 | Operation operation = number -> number * number;
11 | List outputNumbers = numberOperationService.executeOperation(inputNumbers,operation);
12 | System.out.println(outputNumbers);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/listpractice/NumberOperationService.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.listpractice;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class NumberOperationService {
7 |
8 | public List executeOperation(List inputNumbers, Operation operation) {
9 | List outputNumbers = new ArrayList<>();
10 | for (int number : inputNumbers) {
11 | outputNumbers.add(operation.operate(number));
12 | }
13 | return outputNumbers;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/listpractice/Operation.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.listpractice;
2 |
3 | public interface Operation {
4 | int operate(int number);
5 | }
6 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/predicate/LambdaPredicateApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.predicate;
2 |
3 | import java.util.function.Predicate;
4 |
5 | public class LambdaPredicateApp {
6 |
7 | public static void main(String[] args) {
8 | Predicate moreThan5Letters = text -> text.length() > 5;
9 | Predicate startsWithWelcome = text -> text.startsWith("Welcome");
10 |
11 | boolean isMoreThan5Letters = moreThan5Letters.test("Welcome");
12 | System.out.println("The text typed in is longer than 5 letter: " + isMoreThan5Letters);
13 |
14 | boolean isStartsWithWelcome = startsWithWelcome.test("Welcome");
15 | System.out.println("The text typed in starts with \"Welcome\": " + isStartsWithWelcome);
16 |
17 | boolean isLessThan5Letters = moreThan5Letters.negate().test("Welcome");
18 | System.out.println("The text typed in is shorter than 5 letter: " + isLessThan5Letters);
19 |
20 | boolean isCombinedAnd = moreThan5Letters.and(startsWithWelcome).test("Welcome");
21 | System.out.println("The text typed in is longer than 5 letter and starts with \"Welcome\": " + isCombinedAnd);
22 |
23 | boolean isCombinedOr = moreThan5Letters.or(startsWithWelcome).test("Welcom");
24 | System.out.println("The text typed in is longer than 5 letter or starts with \"Welcome\": " + isCombinedOr);
25 |
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/predicate/LambdaPredicateMoreApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.predicate;
2 |
3 | import java.util.List;
4 | import java.util.function.Predicate;
5 | import java.util.stream.Collectors;
6 |
7 | public class LambdaPredicateMoreApp {
8 |
9 | public static void main(String[] args) {
10 | examineNumber(15, number -> number > 7);
11 |
12 | List numbers = List.of(1,2,3,4,5,6,7);
13 | List oddNumbers = numbers.stream()
14 | .filter(number -> number % 2 == 0)
15 | .collect(Collectors.toList());
16 | System.out.println(oddNumbers);
17 | }
18 |
19 | private static void examineNumber(int number, Predicate examination) {
20 | if (examination.test(number)) {
21 | System.out.println("The result of the examination of " + number + " is true.");
22 | }
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/streamexample/StreamExampleApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.streamexample;
2 |
3 | import java.util.List;
4 | import java.util.stream.Collectors;
5 |
6 | public class StreamExampleApp {
7 |
8 | public static void main(String[] args) {
9 | List inputNumbers = List.of(1,2,3,4,5);
10 |
11 | List outputNumbers = inputNumbers
12 | .stream()
13 | .map(number -> number * number)
14 | .filter(number -> number > 3)
15 | .collect(Collectors.toList());
16 |
17 | System.out.println(outputNumbers);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/supplier/LambdaSupplierApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.supplier;
2 |
3 | import java.util.Random;
4 | import java.util.function.Supplier;
5 |
6 | public class LambdaSupplierApp {
7 |
8 | public static void main(String[] args) {
9 | Supplier randomNumber1000 = () -> {
10 | Random randomNumberGenerator = new Random();
11 | return randomNumberGenerator.nextInt(1000) + 1;
12 | };
13 |
14 | System.out.println(randomNumber1000.get());
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/expert/lambda/undaryoperator/LambdaUnaryApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.lambda.undaryoperator;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import java.util.function.UnaryOperator;
7 |
8 | public class LambdaUnaryApp {
9 |
10 | public static void main(String[] args) {
11 | List numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
12 | System.out.println(operateOnList(numbers, number -> number * 3));
13 |
14 | List letters = Arrays.asList("a", "b", "c", "d", "e");
15 | System.out.println(operateOnList(letters, letter -> letter + letter));
16 |
17 | }
18 |
19 | private static List operateOnList(List list, UnaryOperator operator) {
20 | List result = new ArrayList<>();
21 | for (T listElement : list) {
22 | result.add(operator.apply(listElement));
23 | }
24 | return result;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/expert/maps/hashtable/HashTableApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.maps.hashtable;
2 |
3 | import java.util.Hashtable;
4 |
5 | public class HashTableApp {
6 |
7 | public static void main(String[] args) {
8 |
9 | Hashtable productPricesHashTable = new Hashtable<>();
10 |
11 | productPricesHashTable.put("Apple", 0.15);
12 | //productPricesHashTable.put("Cereals", null);
13 | //productPricesHashTable.put(null, 0.0);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/expert/maps/linkedhashmap/LinkedHashMapApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.maps.linkedhashmap;
2 |
3 | import java.util.HashMap;
4 | import java.util.LinkedHashMap;
5 | import java.util.Map;
6 |
7 | public class LinkedHashMapApp {
8 |
9 | public static void main(String[] args) {
10 |
11 | Map productPricesHashMap = new HashMap<>();
12 | productPricesHashMap.put("Chocolate bar", 1.5);
13 | productPricesHashMap.put("Pasta", 1.1);
14 | productPricesHashMap.put("Cereals", 1.7);
15 | productPricesHashMap.put("Apple", 0.15);
16 |
17 | System.out.println("HashMap:");
18 | for (String product : productPricesHashMap.keySet()) {
19 | System.out.println(product + " $" + productPricesHashMap.get(product));
20 | }
21 |
22 | Map productPricesLinkedHashMap = new LinkedHashMap<>();
23 | productPricesLinkedHashMap.put("Chocolate bar", 1.5);
24 | productPricesLinkedHashMap.put("Pasta", 1.1);
25 | productPricesLinkedHashMap.put("Cereals", 1.7);
26 | productPricesLinkedHashMap.put("Apple", 0.15);
27 |
28 | System.out.println("LinkedHashMap:");
29 | for (String product : productPricesLinkedHashMap.keySet()) {
30 | System.out.println(product + " $" + productPricesLinkedHashMap.get(product));
31 | }
32 |
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/expert/maps/treemap/TreeMapApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.maps.treemap;
2 |
3 | import java.util.HashMap;
4 | import java.util.LinkedHashMap;
5 | import java.util.Map;
6 | import java.util.TreeMap;
7 |
8 | public class TreeMapApp {
9 |
10 | public static void main(String[] args) {
11 |
12 | Map productPricesHashMap = new HashMap<>();
13 | productPricesHashMap.put("Chocolate bar", 1.5);
14 | productPricesHashMap.put("Pasta", 1.1);
15 | productPricesHashMap.put("Cereals", 1.7);
16 | productPricesHashMap.put("Apple", 0.15);
17 |
18 | System.out.println("HashMap:");
19 | for (String product : productPricesHashMap.keySet()) {
20 | System.out.println(product + " $" + productPricesHashMap.get(product));
21 | }
22 |
23 | Map productPricesLinkedHashMap = new LinkedHashMap<>();
24 | productPricesLinkedHashMap.put("Chocolate bar", 1.5);
25 | productPricesLinkedHashMap.put("Pasta", 1.1);
26 | productPricesLinkedHashMap.put("Cereals", 1.7);
27 | productPricesLinkedHashMap.put("Apple", 0.15);
28 |
29 | System.out.println();
30 | System.out.println("LinkedHashMap:");
31 | for (String product : productPricesLinkedHashMap.keySet()) {
32 | System.out.println(product + " $" + productPricesLinkedHashMap.get(product));
33 | }
34 |
35 | Map productPricesTreeMap = new TreeMap<>();
36 | productPricesTreeMap.put("Chocolate bar", 1.5);
37 | productPricesTreeMap.put("Pasta", 1.1);
38 | productPricesTreeMap.put("Cereals", 1.7);
39 | productPricesTreeMap.put("Apple", 0.15);
40 |
41 | System.out.println();
42 | System.out.println("TreeMap:");
43 | for (String product : productPricesTreeMap.keySet()) {
44 | System.out.println(product + " $" + productPricesTreeMap.get(product));
45 | }
46 |
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/src/com/expert/methodreference/CollectionTransformer.java:
--------------------------------------------------------------------------------
1 | package com.expert.methodreference;
2 |
3 | import java.util.Collection;
4 | import java.util.function.Supplier;
5 |
6 | public class CollectionTransformer {
7 |
8 | public static , SOURCE extends Collection>
9 | DEST transform(SOURCE sourceCollection, Supplier creator) {
10 | DEST destinationCollection = creator.get();
11 | destinationCollection.addAll(sourceCollection);
12 | return destinationCollection;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/expert/methodreference/MethodReferenceApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.methodreference;
2 |
3 | import java.util.HashSet;
4 | import java.util.List;
5 | import java.util.Set;
6 | import java.util.TreeSet;
7 |
8 | public class MethodReferenceApp {
9 |
10 | public static void main(String[] args) {
11 | List people = List.of(
12 | new Person("Steve", 40),
13 | new Person("Brit", 22),
14 | new Person("Adam", 27),
15 | new Person("Anna", 32),
16 | new Person("Kumar", 91),
17 | new Person("Anna", 4),
18 | new Person("Anna", 12));
19 |
20 | people.stream()
21 | .sorted(PersonComparisonProvider::compareByNameAndAge)
22 | .forEach(System.out::println);
23 |
24 | List numbers = List.of(12, 23, 45, 45, 67, 12, 34, 87, 102);
25 | Set numbersSet = CollectionTransformer.transform(numbers, HashSet::new);
26 | System.out.println(numbersSet);
27 |
28 | Set personSet = CollectionTransformer.transform(people, TreeSet::new);
29 | System.out.println(personSet);
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/expert/methodreference/Person.java:
--------------------------------------------------------------------------------
1 | package com.expert.methodreference;
2 |
3 | public class Person implements Comparable{
4 |
5 | private String name;
6 | private int age;
7 |
8 | public Person(String name, int age) {
9 | this.name = name;
10 | this.age = age;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 |
17 | public Integer getAge() {
18 | return age;
19 | }
20 |
21 | @Override
22 | public String toString() {
23 | return "Person{" +
24 | "name='" + name + '\'' +
25 | ", age=" + age +
26 | '}';
27 | }
28 |
29 | @Override
30 | public int compareTo(Object o) {
31 | Person person = (Person) o;
32 | return this.getAge().compareTo(person.getAge());
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/expert/methodreference/PersonComparisonProvider.java:
--------------------------------------------------------------------------------
1 | package com.expert.methodreference;
2 |
3 | import java.util.Comparator;
4 |
5 | public class PersonComparisonProvider {
6 |
7 | public static int compareByNameAndAge(Person person1, Person person2) {
8 | return Comparator.comparing(Person::getName)
9 | .thenComparing(Person::getAge)
10 | .compare(person1, person2);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/expert/queues/ArrayDequeApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.queues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Deque;
5 |
6 | public class ArrayDequeApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Deque editHistory = new ArrayDeque<>();
11 |
12 | // System.out.println("Taking action: null");
13 | // editHistory.push(null);
14 | System.out.println("Taking action: making the text bold");
15 | editHistory.push("making the text bold");
16 | System.out.println("Taking action: adding some text");
17 | editHistory.push("adding some text");
18 | System.out.println("Taking action: adding a new paragraph");
19 | editHistory.push("adding a new paragraph");
20 |
21 | System.out.println();
22 | System.out.println("The last action in our edit history: " + editHistory.peek());
23 |
24 | System.out.println("Undoing the last action: " + editHistory.pop());
25 | System.out.println("Undoing the last action: " + editHistory.pop());
26 |
27 | System.out.println();
28 | System.out.println("Taking action: making the text italic");
29 | editHistory.push("making the text italic");
30 | System.out.println("Edit history: " + editHistory);
31 |
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/expert/queues/LinkedListDequeApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.queues;
2 |
3 | import java.util.Deque;
4 | import java.util.LinkedList;
5 |
6 | public class LinkedListDequeApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Deque bankQueueNumbers = new LinkedList<>();
11 |
12 | bankQueueNumbers.addLast(30);
13 | bankQueueNumbers.offerLast(31);
14 | bankQueueNumbers.addFirst(32);
15 | bankQueueNumbers.offerFirst(33);
16 | bankQueueNumbers.offer(34);
17 | System.out.println(bankQueueNumbers);
18 |
19 | System.out.println("The first customer in the queue has the number: " + bankQueueNumbers.getFirst());
20 |
21 | System.out.println("Customer with number " + bankQueueNumbers.removeFirst() + " is called.");
22 | System.out.println(bankQueueNumbers);
23 |
24 | System.out.println("Customer with number " + bankQueueNumbers.pollLast() + " is called.");
25 | System.out.println(bankQueueNumbers);
26 |
27 | bankQueueNumbers.remove(33);
28 | System.out.println("Customer with number 33 is removed from the queue.");
29 | System.out.println(bankQueueNumbers);
30 |
31 |
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/expert/queues/LinkedListQueueApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.queues;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 |
6 | public class LinkedListQueueApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Queue bankQueueNumbers = new LinkedList<>();
11 |
12 | bankQueueNumbers.add(30);
13 | bankQueueNumbers.offer(31);
14 | bankQueueNumbers.offer(32);
15 | bankQueueNumbers.offer(33);
16 | bankQueueNumbers.offer(34);
17 | System.out.println(bankQueueNumbers);
18 |
19 | System.out.println("The first customer in the queue has the number: " + bankQueueNumbers.element());
20 |
21 | System.out.println("Customer with number " + bankQueueNumbers.remove() + " is called.");
22 | System.out.println(bankQueueNumbers);
23 |
24 | System.out.println("Customer with number " + bankQueueNumbers.poll() + " is called.");
25 | System.out.println(bankQueueNumbers);
26 |
27 | bankQueueNumbers.remove(33);
28 | System.out.println("Customer with number 33 is removed from the queue.");
29 | System.out.println(bankQueueNumbers);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/expert/queues/PriorityQueueApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.queues;
2 |
3 | import java.util.LinkedList;
4 | import java.util.PriorityQueue;
5 | import java.util.Queue;
6 |
7 | public class PriorityQueueApp {
8 |
9 | public static void main(String[] args) {
10 |
11 | Queue bankQueueNumbers = new PriorityQueue<>();
12 |
13 | bankQueueNumbers.add(34);
14 | bankQueueNumbers.offer(32);
15 | bankQueueNumbers.offer(31);
16 | bankQueueNumbers.offer(33);
17 | bankQueueNumbers.offer(30);
18 | System.out.println(bankQueueNumbers);
19 |
20 | System.out.println("The first customer in the queue has the number: " + bankQueueNumbers.element());
21 |
22 | System.out.println("Customer with number " + bankQueueNumbers.remove() + " is called.");
23 | System.out.println(bankQueueNumbers);
24 |
25 | System.out.println("Customer with number " + bankQueueNumbers.poll() + " is called.");
26 | System.out.println(bankQueueNumbers);
27 |
28 | bankQueueNumbers.remove(33);
29 | System.out.println("Customer with number 33 is removed from the queue.");
30 | System.out.println(bankQueueNumbers);
31 |
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/expert/queues/StackWithLinkedListApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.queues;
2 |
3 | import java.util.Deque;
4 | import java.util.LinkedList;
5 |
6 | public class StackWithLinkedListApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Deque editHistory = new LinkedList<>();
11 |
12 | System.out.println("Taking action: making the text bold");
13 | editHistory.push("making the text bold");
14 | System.out.println("Taking action: adding some text");
15 | editHistory.push("adding some text");
16 | System.out.println("Taking action: adding a new paragraph");
17 | editHistory.push("adding a new paragraph");
18 |
19 | System.out.println();
20 | System.out.println("The last action in our edit history: " + editHistory.peek());
21 |
22 | System.out.println("Undoing the last action: " + editHistory.pop());
23 | System.out.println("Undoing the last action: " + editHistory.pop());
24 |
25 | System.out.println();
26 | System.out.println("Taking action: making the text italic");
27 | editHistory.push("making the text italic");
28 | System.out.println("Edit history: " + editHistory);
29 |
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/expert/sets/enumset/EnumSetApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.sets.enumset;
2 |
3 | import java.util.EnumSet;
4 |
5 | public class EnumSetApp {
6 |
7 | enum PizzaSize {
8 | SMALL, MEDIUM, LARGE, EXTRA_LARGE, FAMILY;
9 | }
10 |
11 | public static void main(String[] args) {
12 |
13 | EnumSet pizzaSizes = EnumSet.allOf(PizzaSize.class);
14 | System.out.println("Available pizza sizes: " + pizzaSizes);
15 |
16 | EnumSet basicPizzaSizes = EnumSet.of(PizzaSize.SMALL, PizzaSize.MEDIUM, PizzaSize.LARGE);
17 | System.out.println("Basic pizza sizes: " + basicPizzaSizes);
18 |
19 | EnumSet middlePizzaSizes = EnumSet.range(PizzaSize.MEDIUM, PizzaSize.EXTRA_LARGE);
20 | System.out.println("Middle pizza sizes: " + middlePizzaSizes);
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/expert/sets/hashset/HashSetApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.sets.hashset;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class HashSetApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Set carBrands = new HashSet<>();
11 | carBrands.add("Toyota");
12 | carBrands.add("Nissan");
13 | carBrands.add("Ford");
14 | carBrands.add("Kia");
15 | carBrands.add("Toyota");
16 |
17 | carBrands.clear();
18 | carBrands.remove("Ford");
19 | System.out.println(carBrands);
20 | System.out.println("Kia is in the set: " + carBrands.contains("Kia"));
21 | System.out.println("The size of the set: " + carBrands.size());
22 |
23 | System.out.println();
24 | System.out.println("We have the following car brands:");
25 | for(String carBrand : carBrands) {
26 | System.out.println("-" + carBrand.toUpperCase());
27 | }
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/expert/sets/hashset/HashSetOperationsApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.sets.hashset;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class HashSetOperationsApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Set carBrands = new HashSet<>();
11 | carBrands.add("Toyota");
12 | carBrands.add("Nissan");
13 | carBrands.add("Ford");
14 | carBrands.add("Kia");
15 | System.out.println("Our original set of car brands: " + carBrands);
16 |
17 | Set newCarBrands = new HashSet<>();
18 | newCarBrands.add("Lexus");
19 | newCarBrands.add("Volvo");
20 | newCarBrands.add("Seat");
21 | newCarBrands.add("Fiat");
22 |
23 | carBrands.addAll(newCarBrands);
24 | System.out.println("After the new cars arrived: " + carBrands);
25 |
26 | Set leastReliableCarBrands = new HashSet<>();
27 | leastReliableCarBrands.add("Ford");
28 | leastReliableCarBrands.add("Fiat");
29 | leastReliableCarBrands.add("Seat");
30 | leastReliableCarBrands.add("Renault");
31 |
32 | System.out.println("All the least reliable car brands available in our dealership: "
33 | + carBrands.containsAll(leastReliableCarBrands));
34 | //carBrands.retainAll(leastReliableCarBrands);
35 | //System.out.println("The least reliable brands that can be found in our dealership: "
36 | // + carBrands);
37 |
38 | carBrands.removeAll(leastReliableCarBrands);
39 | System.out.println("After the least reliable cars are sold: " + carBrands);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/expert/sets/linkedhashset/LinkedHashSetApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.sets.linkedhashset;
2 |
3 | import java.util.LinkedHashSet;
4 | import java.util.Set;
5 |
6 | public class LinkedHashSetApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | Set carBrands = new LinkedHashSet<>(10, 0.6f);
11 | carBrands.add("Toyota");
12 | carBrands.add("Nissan");
13 | carBrands.add("Ford");
14 | carBrands.add("Kia");
15 | System.out.println("Our original set of car brands: " + carBrands);
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/expert/sets/treemap/TreeSetApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.sets.treemap;
2 |
3 | import java.util.TreeSet;
4 |
5 | public class TreeSetApp {
6 |
7 | public static void main(String[] args) {
8 |
9 | TreeSet carBrands = new TreeSet<>();
10 | carBrands.add("Toyota");
11 | carBrands.add("Nissan");
12 | carBrands.add("Ford");
13 | carBrands.add("Kia");
14 | carBrands.add("Lexus");
15 | carBrands.add("Volvo");
16 | carBrands.add("Seat");
17 | carBrands.add("Fiat");
18 | System.out.println("Our original set of car brands: " + carBrands);
19 |
20 | System.out.println();
21 | System.out.println("Lower function returns the following: " + carBrands.lower("Lexus"));
22 | System.out.println("Floor function returns the following: " + carBrands.floor("Lexus"));
23 | System.out.println("Higher function returns the following: " + carBrands.higher("Lexus"));
24 | System.out.println("Ceiling function returns the following: " + carBrands.ceiling("Lexus"));
25 |
26 | System.out.println();
27 | System.out.println("Tail set: " + carBrands.tailSet("Lexus"));
28 | System.out.println("Head set: " + carBrands.headSet("Lexus"));
29 | System.out.println("Sub set: " + carBrands.subSet("Lexus", "Toyota"));
30 |
31 | System.out.println();
32 | System.out.println("The first element: " + carBrands.first());
33 | System.out.println("The last element: " + carBrands.last());
34 | System.out.println("The pollFirst element: " + carBrands.pollFirst());
35 | System.out.println("The pollLast element: " + carBrands.pollLast());
36 | System.out.println("The set after pollFirst and pollLast: " + carBrands);
37 |
38 | System.out.println();
39 | System.out.println("The set in descending order: " + carBrands.descendingSet());
40 |
41 |
42 |
43 |
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/com/expert/streams/collect/CollectToApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.collect;
2 |
3 | import java.util.*;
4 | import java.util.function.Function;
5 | import java.util.stream.Collectors;
6 |
7 | public class CollectToApp {
8 |
9 | public static void main(String[] args) {
10 | List fruits = List.of("apple", "pineapple",
11 | "watermelon", "banana", "kiwi", "apple", "kiwi");
12 |
13 | Set availableFruits = fruits.stream()
14 | .filter(fruit -> fruit.startsWith("w"))
15 | .collect(Collectors.toSet());
16 | System.out.println("Available fruits:");
17 | System.out.println(availableFruits);
18 |
19 | Collection fruitBoxes = fruits.stream()
20 | .collect(Collectors.toCollection(LinkedList::new));
21 | System.out.println("Fruit boxes: ");
22 | System.out.println(fruitBoxes);
23 |
24 | Map fruitNamesWithUppercase = fruits.stream()
25 | .distinct()
26 | .collect(Collectors.toMap(Function.identity(), String::toUpperCase));
27 | System.out.println("Fruit names with uppercase:");
28 | System.out.println(fruitNamesWithUppercase);
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/expert/streams/collect/CollectUtilFunctionsApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.collect;
2 |
3 | import java.util.List;
4 | import java.util.stream.Collectors;
5 |
6 | public class CollectUtilFunctionsApp {
7 | public static void main(String[] args) {
8 | List playerNames = List.of("Azita", "Lamar", "Maui");
9 | List playerDamage = List.of(12, 20, 15, 120, 30, 16, 40, 20, 100);
10 | List playerDamageDouble = List.of(12.0, 20.0, 15.0, 120.0, 30.0, 16.0, 40.0, 20.0, 100.0);
11 |
12 | System.out.println("Player names: " + String.join(", ", playerNames));
13 | System.out.println("Player damages: " + playerDamage.stream()
14 | .map(Object::toString)
15 | .collect(Collectors.joining(", "))
16 | );
17 |
18 | Long numberOfHits = playerDamage.stream()
19 | .collect(Collectors.counting());
20 | System.out.println("Number of hits: " + numberOfHits);
21 |
22 | Integer overallDamage = playerDamageDouble.stream()
23 | .collect(Collectors.summingInt(Double::intValue));
24 | System.out.println("Overall damage: " + overallDamage);
25 |
26 | Double overallDamageDouble = playerDamage.stream()
27 | .collect(Collectors.summingDouble(Integer::doubleValue));
28 | System.out.println("Overall damage(double): " + overallDamageDouble);
29 |
30 | Double averageDamage = playerDamage.stream()
31 | .collect(Collectors.averagingInt(Integer::intValue));
32 | System.out.println("Average damage: " + averageDamage);
33 |
34 | System.out.println("Damage statistics: " + playerDamage.stream()
35 | .collect(Collectors.summarizingInt(Integer::intValue))
36 | );
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/expert/streams/collect/Item.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.collect;
2 |
3 | import java.util.Objects;
4 |
5 | public class Item {
6 |
7 | private String name;
8 | private int quantity;
9 | private double price;
10 |
11 | public Item(String name, int quantity, double price) {
12 | this.name = name;
13 | this.quantity = quantity;
14 | this.price = price;
15 | }
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public int getQuantity() {
22 | return quantity;
23 | }
24 |
25 | public double getPrice() {
26 | return price;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 |
33 | public void setQuantity(int quantity) {
34 | this.quantity = quantity;
35 | }
36 |
37 | public void setPrice(double price) {
38 | this.price = price;
39 | }
40 |
41 | @Override
42 | public boolean equals(Object o) {
43 | if (this == o) return true;
44 | if (o == null || getClass() != o.getClass()) return false;
45 | Item item = (Item) o;
46 | return quantity == item.quantity && Double.compare(item.price, price) == 0 && Objects.equals(name, item.name);
47 | }
48 |
49 | @Override
50 | public int hashCode() {
51 | return Objects.hash(name, quantity, price);
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | return "Item{" +
57 | "name='" + name + '\'' +
58 | ", quantity=" + quantity +
59 | ", price=" + price +
60 | '}';
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/com/expert/streams/collect/WeatherByMonth.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.collect;
2 |
3 | import java.util.Objects;
4 |
5 | public class WeatherByMonth {
6 |
7 | private String month;
8 | private int dayTimeTemperature;
9 | private int nightTimeTemperature;
10 |
11 | public WeatherByMonth(String month, int dayTimeTemperature, int nightTimeTemperature) {
12 | this.month = month;
13 | this.dayTimeTemperature = dayTimeTemperature;
14 | this.nightTimeTemperature = nightTimeTemperature;
15 | }
16 |
17 | public String getMonth() {
18 | return month;
19 | }
20 |
21 | public int getDayTimeTemperature() {
22 | return dayTimeTemperature;
23 | }
24 |
25 | public int getNightTimeTemperature() {
26 | return nightTimeTemperature;
27 | }
28 |
29 | @Override
30 | public boolean equals(Object o) {
31 | if (this == o) return true;
32 | if (o == null || getClass() != o.getClass()) return false;
33 | WeatherByMonth that = (WeatherByMonth) o;
34 | return dayTimeTemperature == that.dayTimeTemperature && nightTimeTemperature == that.nightTimeTemperature && Objects.equals(month, that.month);
35 | }
36 |
37 | @Override
38 | public int hashCode() {
39 | return Objects.hash(month, dayTimeTemperature, nightTimeTemperature);
40 | }
41 |
42 | @Override
43 | public String toString() {
44 | return "WeatherByMonth{" +
45 | "month='" + month + '\'' +
46 | ", dayTimeTemperature=" + dayTimeTemperature +
47 | ", nightTimeTemperature=" + nightTimeTemperature +
48 | '}';
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/com/expert/streams/distinct/DistinctApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.distinct;
2 |
3 | import com.expert.streams.filtering.Product;
4 |
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 |
8 | public class DistinctApp {
9 |
10 | public static void main(String[] args) {
11 | List fruits = List.of("apple", "pineapple",
12 | "watermelon", "banana", "kiwi", "apple", "kiwi");
13 | List availableFruits = fruits.stream()
14 | .distinct()
15 | .sorted()
16 | .collect(Collectors.toList());
17 |
18 | System.out.println("Available fruits:");
19 | System.out.println(availableFruits);
20 |
21 | List cereals = List.of(
22 | new Product("Lucky Puffs", "Logs", 8.59, 4.6),
23 | new Product("Cinnamon Loops", "ABC", 7.59, 4.5),
24 | new Product("Cinnamon Loops", "ABC", 7.59, 4.5)
25 | );
26 |
27 | List availableCereals = cereals.stream()
28 | .distinct()
29 | .collect(Collectors.toList());
30 | System.out.println("Available cereals:");
31 | System.out.println(availableCereals);
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/expert/streams/filtering/FilterApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.filtering;
2 |
3 | import java.util.List;
4 |
5 | public class FilterApp {
6 |
7 | public static void main(String[] args) {
8 | List cereals = List.of(
9 | new Product("Captain Crunch", "ABC", 9.99, 4.7),
10 | new Product("Fruity Oatmeal", "Old Oat", 6.99, 4.2),
11 | new Product("Cinnamon Loops", "ABC", 7.59, 4.5),
12 | new Product("Lucky Puffs", "Logs", 8.59, 4.6),
13 | new Product("Barn Flakes", "Old Oat", 5.09, 4.0),
14 | new Product("Golden Cookies", "ABC", 9.99, 4.8)
15 | );
16 |
17 | cereals.stream()
18 | .filter(cereal -> cereal.getPrice() < 8 && cereal.getBrand().equals("ABC"))
19 | .forEach(System.out::println);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/expert/streams/filtering/Product.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.filtering;
2 |
3 | import java.util.Objects;
4 |
5 | public class Product {
6 |
7 | private final String name;
8 | private final String brand;
9 | private final double price;
10 | private final double rating;
11 |
12 | public Product(String name, String brand, double price, double rating) {
13 | this.name = name;
14 | this.brand = brand;
15 | this.price = price;
16 | this.rating = rating;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 | public String getBrand() {
24 | return brand;
25 | }
26 |
27 | public double getPrice() {
28 | return price;
29 | }
30 |
31 | public double getRating() {
32 | return rating;
33 | }
34 |
35 | @Override
36 | public String toString() {
37 | return "Product{" +
38 | "name='" + name + '\'' +
39 | ", brand='" + brand + '\'' +
40 | ", price=" + price +
41 | ", rating=" + rating +
42 | '}';
43 | }
44 |
45 | @Override
46 | public boolean equals(Object o) {
47 | if (this == o) return true;
48 | if (o == null || getClass() != o.getClass()) return false;
49 | Product product = (Product) o;
50 | return Double.compare(product.price, price) == 0 && Double.compare(product.rating, rating) == 0 && Objects.equals(name, product.name) && Objects.equals(brand, product.brand);
51 | }
52 |
53 | @Override
54 | public int hashCode() {
55 | return Objects.hash(name, brand, price, rating);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/com/expert/streams/findfunctions/FindFunctionsApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.findfunctions;
2 |
3 | import com.expert.streams.collect.Item;
4 |
5 | import java.util.List;
6 | import java.util.Optional;
7 |
8 | public class FindFunctionsApp {
9 |
10 | public static void main(String[] args) {
11 | List- fruitBoxes = List.of(
12 | new Item("strawberry", 10, 7.99),
13 | new Item("blueberry", 20, 26.99),
14 | new Item("pear", 10, 28.99),
15 | new Item("apple", 10, 3.99),
16 | new Item("kiwi", 10, 11.99),
17 | new Item("pear", 20, 9.99),
18 | new Item("strawberry", 20, 19.99),
19 | new Item("apple", 10, 15.99),
20 | new Item("apple", 10, 4.99)
21 | );
22 |
23 | Optional
- firstFruitBox = fruitBoxes.stream()
24 | .findFirst();
25 | System.out.println("The first fruit box: " + firstFruitBox.get());
26 |
27 | Optional
- anyFruitBox = fruitBoxes.stream()
28 | .findAny();
29 | System.out.println("A fruit box: " + anyFruitBox.get());
30 |
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/expert/streams/flatmap/CarDealership.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.flatmap;
2 |
3 | import java.util.List;
4 | import java.util.Objects;
5 |
6 | public class CarDealership {
7 |
8 | String name;
9 | List carBrands;
10 |
11 | public CarDealership(String name, List carBrands) {
12 | this.name = name;
13 | this.carBrands = carBrands;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | public List getCarBrands() {
21 | return carBrands;
22 | }
23 |
24 | @Override
25 | public boolean equals(Object o) {
26 | if (this == o) return true;
27 | if (o == null || getClass() != o.getClass()) return false;
28 | CarDealership that = (CarDealership) o;
29 | return Objects.equals(name, that.name) && Objects.equals(carBrands, that.carBrands);
30 | }
31 |
32 | @Override
33 | public int hashCode() {
34 | return Objects.hash(name, carBrands);
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "CarDealership{" +
40 | "name='" + name + '\'' +
41 | ", carBrands=" + carBrands +
42 | '}';
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/expert/streams/flatmap/FlatMapApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.flatmap;
2 |
3 | import java.util.Collection;
4 | import java.util.List;
5 | import java.util.Set;
6 | import java.util.stream.Collectors;
7 | import java.util.stream.Stream;
8 |
9 | public class FlatMapApp {
10 |
11 | public static void main(String[] args) {
12 | Integer[][] lotteryNumbers = new Integer[][]{
13 | {5, 23, 54, 60, 22},
14 | {15, 2, 34, 77, 81},
15 | {5, 7, 89, 63, 52},
16 | };
17 | Set lotteryNumbersSet = Stream.of(lotteryNumbers)
18 | .flatMap(Stream::of)
19 | .collect(Collectors.toSet());
20 | System.out.println("The lottery numbers in the last 3 weeks: " + lotteryNumbersSet);
21 |
22 |
23 | List
> fruits = List.of(
24 | List.of("apple", "banana", "lemon"),
25 | List.of("plum", "mango", "kiwi"));
26 | List fruitsList = fruits.stream()
27 | .flatMap(Collection::stream)
28 | .collect(Collectors.toList());
29 | System.out.println("Available fruits: " + fruitsList);
30 |
31 | List carDealerships = List.of(
32 | new CarDealership("Brand New Dealership", List.of("Dodge", "Ford", "Ferrari")),
33 | new CarDealership("Total Car Ltd.", List.of("Kia", "Toyota", "Ford")),
34 | new CarDealership("Crashed Dealership", List.of("Ford", "Lexus", "Ferrari")));
35 | List availableCarBrands = carDealerships.stream()
36 | .map(CarDealership::getCarBrands)
37 | .flatMap(Collection::stream)
38 | .distinct()
39 | .collect(Collectors.toList());
40 | System.out.println("Available car brands: " + availableCarBrands);
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/expert/streams/foreach/ForEachApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.foreach;
2 |
3 | import com.expert.streams.filtering.Product;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | public class ForEachApp {
11 |
12 | public static void main(String[] args) {
13 | List cereals = List.of(
14 | new Product("Captain Crunch", "ABC", 9.99, 4.7),
15 | new Product("Fruity Oatmeal", "Old Oat", 6.99, 4.2),
16 | new Product("Cinnamon Loops", "ABC", 7.59, 4.5),
17 | new Product("Lucky Puffs", "Logs", 8.59, 4.6),
18 | new Product("Barn Flakes", "Old Oat", 5.09, 4.0),
19 | new Product("Golden Cookies", "ABC", 9.99, 4.8)
20 | );
21 |
22 | List cheapCereals = new ArrayList<>();
23 | cereals.stream()
24 | .filter(cereal -> cereal.getPrice() < 8)
25 | .forEach(cheapCereals::add);
26 | System.out.println(cheapCereals);
27 |
28 | Map smartWatches = new HashMap<>();
29 | smartWatches.put(1, new Product("Fitness Tracker", "Oxygen", 199.9, 4.7));
30 | smartWatches.put(2, new Product("Berry Watch", "HVR", 159.99, 4.6));
31 | smartWatches.put(3, new Product("A1 Model", "MorePro", 139.99, 4.3));
32 | smartWatches.put(4, new Product("A2 Model", "MorePro", 149.99, 4.4));
33 |
34 | smartWatches.entrySet().stream()
35 | .filter(productEntry -> productEntry.getValue() != null &&
36 | productEntry.getValue().getBrand().equals("MorePro"))
37 | .forEach( productEntry -> {
38 | Product productValue = productEntry.getValue();
39 | System.out.println( productValue.getName() + " - " +
40 | productValue.getBrand() + " - $" + productValue.getPrice());
41 | });
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/expert/streams/howtocreate/StreamCreationApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.howtocreate;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 | import java.util.stream.IntStream;
7 | import java.util.stream.Stream;
8 |
9 | public class StreamCreationApp {
10 |
11 | public static void main(String[] args) {
12 | List musicStyles = List.of("Rock", "Trance", "Pop", "Blues", "Classical music");
13 | musicStyles.stream()
14 | .sorted()
15 | .forEach(musicStyle -> System.out.println(musicStyle + " Extra text"));
16 |
17 | System.out.println(Stream.of("Rock", "Trance", "Pop", "Blues", "Classical music")
18 | .collect(Collectors.toList()));
19 |
20 | System.out.println("The number of elements in the array: " +
21 | Arrays.stream(new double[] {3.4, 5.7, 1.3, 54.3}).count());
22 |
23 | IntStream.range(0, musicStyles.size())
24 | .forEach(number -> System.out.println( (number + 1) + ". " + musicStyles.get(number)));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/expert/streams/introduction/StreamsIntroductionApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.introduction;
2 |
3 | import java.util.Comparator;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | public class StreamsIntroductionApp {
8 |
9 | public static void main(String[] args) {
10 | List temperatures = List.of(16, 16, 16, 17, 19, 19, 16);
11 |
12 | System.out.println(temperatures.stream()
13 | .filter(temperature -> temperature > 16)
14 | .filter(temperature -> temperature < 19)
15 | .count());
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/com/expert/streams/map/MapApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.map;
2 |
3 | import com.expert.streams.filtering.Product;
4 |
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 |
8 | public class MapApp {
9 | public static void main(String[] args) {
10 | List names = List.of("aladdin", "clara", "Cesar", "polly");
11 | List namesCapitalized = names.stream()
12 | .map(name -> name.substring(0,1).toUpperCase() + name.substring(1))
13 | .collect(Collectors.toList());
14 | System.out.println("Capitalized names:");
15 | System.out.println(namesCapitalized);
16 |
17 | List cereals = List.of(
18 | new Product("Captain Crunch", "ABC", 9.99, 4.7),
19 | new Product("Fruity Oatmeal", "Old Oat", 6.99, 4.2),
20 | new Product("Cinnamon Loops", "ABC", 7.59, 4.5),
21 | new Product("Lucky Puffs", "Logs", 8.59, 4.6),
22 | new Product("Barn Flakes", "Old Oat", 5.09, 4.0),
23 | new Product("Golden Cookies", "ABC", 9.99, 4.8)
24 | );
25 | List cerealNames = cereals.stream()
26 | .map(Product::getName)
27 | .collect(Collectors.toList());
28 | System.out.println("Cereal names: ");
29 | System.out.println(cerealNames);
30 |
31 | List increasedPriceCereals = cereals.stream()
32 | .map(product -> new Product(
33 | product.getName(),
34 | product.getBrand(),
35 | product.getPrice() * 1.2,
36 | product.getRating()
37 | ))
38 | .collect(Collectors.toList());
39 | System.out.println("Increased cereal prices:");
40 | System.out.println(increasedPriceCereals);
41 |
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/expert/streams/match/MatchFunctionsApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.match;
2 |
3 | import com.expert.streams.collect.Item;
4 |
5 | import java.util.List;
6 |
7 | public class MatchFunctionsApp {
8 |
9 | public static void main(String[] args) {
10 | List- fruitBoxes = List.of(
11 | new Item("strawberry", 10, 7.99),
12 | new Item("blueberry", 20, 26.99),
13 | new Item("pear", 10, 28.99),
14 | new Item("apple", 10, 3.99),
15 | new Item("kiwi", 10, 11.99),
16 | new Item("pear", 10, 9.99),
17 | new Item("strawberry", 20, 19.99),
18 | new Item("apple", 10, 15.99),
19 | new Item("apple", 10, 4.99)
20 | );
21 |
22 | boolean isMoreExpensiveThan = fruitBoxes.stream()
23 | .allMatch(item -> item.getPrice() > 1);
24 | System.out.println("All fruit boxes are more expensive than $10: " + isMoreExpensiveThan);
25 |
26 | boolean isKiwiAvailable = fruitBoxes.stream()
27 | .anyMatch(item -> "kiwi".equals(item.getName()));
28 | System.out.println("Kiwi is available in the shop: " + isKiwiAvailable);
29 |
30 | boolean isNoneMoreExpensiveThan = fruitBoxes.stream()
31 | .noneMatch(item -> item.getPrice() > 10);
32 | System.out.println("None of the fruit boxes is more expensive than $100: " + isNoneMoreExpensiveThan);
33 |
34 |
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/expert/streams/minmax/MinMaxCountApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.minmax;
2 |
3 | import com.expert.streams.collect.Item;
4 |
5 | import java.util.Comparator;
6 | import java.util.List;
7 |
8 | public class MinMaxCountApp {
9 |
10 | public static void main(String[] args) {
11 | List
- fruitBoxes = List.of(
12 | new Item("strawberry", 10, 7.99),
13 | new Item("blueberry", 20, 26.99),
14 | new Item("pear", 10, 28.99),
15 | new Item("apple", 10, 3.99),
16 | new Item("kiwi", 10, 11.99),
17 | new Item("pear", 20, 9.99),
18 | new Item("strawberry", 20, 19.99),
19 | new Item("apple", 10, 15.99),
20 | new Item("apple", 10, 4.99)
21 | );
22 |
23 | long numberOfBoxes = fruitBoxes.stream()
24 | .filter(fruitBox -> fruitBox.getQuantity() > 10)
25 | .count();
26 | System.out.println("The number of fruit boxes: " + numberOfBoxes);
27 |
28 | Item maxPriceFruit = fruitBoxes.stream()
29 | .max(Comparator.comparing(Item::getPrice))
30 | .get();
31 | System.out.println("The most expensive fruit box: " + maxPriceFruit);
32 |
33 | Item minPriceFruit = fruitBoxes.stream()
34 | .min(Comparator.comparing(Item::getPrice))
35 | .get();
36 | System.out.println("The cheapest fruit box: " + minPriceFruit);
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/expert/streams/peek/PeekApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.peek;
2 |
3 | import com.expert.streams.collect.Item;
4 |
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 |
8 | public class PeekApp {
9 |
10 | public static void main(String[] args) {
11 | List
- fruitBoxes = List.of(
12 | new Item("strawberry", 10, 7.99),
13 | new Item("blueberry", 20, 26.99),
14 | new Item("pear", 10, 28.99),
15 | new Item("apple", 10, 3.99),
16 | new Item("kiwi", 10, 11.99),
17 | new Item("pear", 20, 9.99),
18 | new Item("strawberry", 20, 19.99),
19 | new Item("apple", 10, 15.99),
20 | new Item("apple", 10, 4.99)
21 | );
22 |
23 | List
- filteredFruitBoxes = fruitBoxes.stream()
24 | .filter(fruitBox -> fruitBox.getQuantity() > 10)
25 | .peek(fruitBox -> System.out.println("Quantity filtered: " + fruitBox))
26 | .filter(fruitBox -> fruitBox.getPrice() < 10)
27 | .peek(fruitBox -> System.out.println("Price filtered: " + fruitBox))
28 | .peek(fruitBox -> fruitBox.setPrice(fruitBox.getPrice() + 5))
29 | .collect(Collectors.toList());
30 |
31 | System.out.println("Filtered list:");
32 | System.out.println(filteredFruitBoxes);
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/expert/streams/range/RangeApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.range;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | public class RangeApp {
6 |
7 | public static void main(String[] args) {
8 |
9 | System.out.println("Temperature scale:");
10 | IntStream.rangeClosed(10, 30)
11 | .filter(number -> number % 10 == 0)
12 | .forEach(System.out::println);
13 |
14 | System.out.println("Possibility of rain:");
15 | IntStream.range(1, 10).asDoubleStream()
16 | .map(number -> number / 10 )
17 | .forEach(System.out::println);
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/expert/streams/reduce/ReduceApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.reduce;
2 |
3 | import com.expert.streams.collect.Item;
4 |
5 | import java.util.List;
6 |
7 | public class ReduceApp {
8 |
9 | public static void main(String[] args) {
10 |
11 | List
- shoppingCart = List.of(
12 | new Item("strawberry", 10, 10),
13 | new Item("blueberry", 20, 30),
14 | new Item("pear", 10, 30)
15 | );
16 |
17 | double subTotal = shoppingCart.stream()
18 | .mapToDouble(Item::getPrice)
19 | .sum();
20 | double discount = -10;
21 | double totalPrice = shoppingCart.stream()
22 | .map(Item::getPrice)
23 | .reduce(discount, Double::sum);
24 |
25 | System.out.println("Subtotal: \t\t$" + subTotal);
26 | System.out.println("Discount: \t\t$" + discount);
27 | System.out.println("Total price: \t$" + totalPrice);
28 |
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/expert/streams/skiplimit/SkipLimitApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.skiplimit;
2 |
3 | import com.expert.streams.collect.Item;
4 |
5 | import java.util.Comparator;
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 |
9 | public class SkipLimitApp {
10 | public static void main(String[] args) {
11 | List
- fruitBoxes = List.of(
12 | new Item("strawberry", 10, 7.99),
13 | new Item("blueberry", 20, 26.99),
14 | new Item("pear", 10, 28.99),
15 | new Item("apple", 10, 3.99),
16 | new Item("kiwi", 10, 11.99),
17 | new Item("pear", 10, 9.99),
18 | new Item("strawberry", 20, 19.99),
19 | new Item("apple", 10, 15.99),
20 | new Item("apple", 10, 4.99)
21 | );
22 |
23 | List
- top3LeastExpensiveFruitBoxes = fruitBoxes.stream()
24 | .sorted(Comparator.comparing(Item::getPrice))
25 | .limit(3)
26 | .collect(Collectors.toList());
27 | System.out.println("The top 3 least expensive fruit boxes: " + top3LeastExpensiveFruitBoxes);
28 |
29 | List
- top3MostExpensiveFruitBoxes = fruitBoxes.stream()
30 | .sorted(Comparator.comparing(Item::getPrice).reversed())
31 | .skip(1)
32 | .limit(3)
33 | .collect(Collectors.toList());
34 | System.out.println("The top 3 most expensive fruit boxes: " + top3MostExpensiveFruitBoxes);
35 |
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/expert/streams/sorted/SortedApp.java:
--------------------------------------------------------------------------------
1 | package com.expert.streams.sorted;
2 |
3 | import com.expert.streams.filtering.Product;
4 |
5 | import java.util.Comparator;
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 |
9 |
10 | public class SortedApp {
11 | public static void main(String[] args) {
12 | List lotteryNumbers = List.of(34, 54, 2, 64, 11);
13 | System.out.println(lotteryNumbers.stream()
14 | .sorted(Comparator.reverseOrder())
15 | .collect(Collectors.toList()));
16 |
17 |
18 | List cereals = List.of(
19 | new Product("Captain Crunch", "ABC", 9.99, 4.7),
20 | new Product("Fruity Oatmeal", "Old Oat", 6.99, 4.2),
21 | new Product("Cinnamon Loops", "ABC", 7.59, 4.5),
22 | new Product("Lucky Puffs", "Logs", 8.59, 4.6),
23 | new Product("Barn Flakes", "Old Oat", 5.09, 4.0),
24 | new Product("Golden Cookies", "ABC", 9.99, 4.8)
25 | );
26 | cereals.stream()
27 | .sorted(Comparator.comparing(Product::getPrice)
28 | .thenComparing(Product::getName).reversed())
29 | .forEach(System.out::println);
30 |
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/hero/garbagecollection/GarbageCollectionApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.garbagecollection;
2 |
3 | public class GarbageCollectionApp {
4 |
5 | public static void main(String[] args) {
6 |
7 | UnstablePlanet artemis = new UnstablePlanet("Artemis", 5648, "gas");
8 | UnstablePlanet dunon = new UnstablePlanet("Dunon", 66472, "solid");
9 | System.out.println("The number of unstable planets: " + UnstablePlanet.getNumberOfUnstablePlanets());
10 |
11 | newUnstablePlanets();
12 | System.out.println("The number of unstable planets: " + UnstablePlanet.getNumberOfUnstablePlanets());
13 | artemis = null;
14 | dunon = null;
15 |
16 | System.gc();
17 | System.runFinalization();
18 | System.out.println("The number of unstable planets: " + UnstablePlanet.getNumberOfUnstablePlanets());
19 | }
20 |
21 | private static void newUnstablePlanets() {
22 | UnstablePlanet lethris = new UnstablePlanet("Lethris", 1486, "solid");
23 | UnstablePlanet okmaron = new UnstablePlanet("Okmaron", 3574, "gas");
24 | }
25 |
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/hero/garbagecollection/UnstablePlanet.java:
--------------------------------------------------------------------------------
1 | package com.hero.garbagecollection;
2 |
3 | public class UnstablePlanet {
4 |
5 | private String name;
6 | private int size;
7 | private String type;
8 | private static int numberOfUnstablePlanets = 0;
9 |
10 | public UnstablePlanet(String name, int size, String type) {
11 | this.name = name;
12 | this.size = size;
13 | this.type = type;
14 | numberOfUnstablePlanets++;
15 | }
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public void setName(String name) {
22 | this.name = name;
23 | }
24 |
25 | public int getSize() {
26 | return size;
27 | }
28 |
29 | public void setSize(int size) {
30 | this.size = size;
31 | }
32 |
33 | public String getType() {
34 | return type;
35 | }
36 |
37 | public void setType(String type) {
38 | this.type = type;
39 | }
40 |
41 | public static int getNumberOfUnstablePlanets() {
42 | return numberOfUnstablePlanets;
43 | }
44 |
45 | public static void setNumberOfUnstablePlanets(int numberOfUnstablePlanets) {
46 | UnstablePlanet.numberOfUnstablePlanets = numberOfUnstablePlanets;
47 | }
48 |
49 | @Override
50 | public String toString() {
51 | return "UnstablePlanet{" +
52 | "name='" + name + '\'' +
53 | ", size=" + size +
54 | ", type='" + type + '\'' +
55 | '}';
56 | }
57 |
58 | protected void finalize(){
59 | System.out.println("An unstable planet object is destroyed.");
60 | --numberOfUnstablePlanets;
61 | System.out.println("Number of remaining unstable planets: " + numberOfUnstablePlanets);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/interrupt/InterruptApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.interrupt;
2 |
3 | public class InterruptApp {
4 |
5 | public static void main(String[] args) throws InterruptedException {
6 |
7 | Tank tank = new Tank(100);
8 | Pump pumpOne = new Pump(tank, 15);
9 | Pump pumpTwo = new Pump(tank, 13);
10 |
11 | pumpOne.start();
12 | pumpTwo.start();
13 |
14 | Thread.sleep(5000);
15 |
16 | tank.consumeWater(60);
17 | Thread.sleep(5000);
18 |
19 | pumpOne.interrupt();
20 | pumpTwo.interrupt();
21 |
22 |
23 | pumpOne.join();
24 | pumpTwo.join();
25 | System.out.println("Pumps have been stopped.");
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/interrupt/Pump.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.interrupt;
2 |
3 | public class Pump extends Thread {
4 |
5 | private Tank tank;
6 | private int pumpingRate;
7 |
8 | public Pump(Tank tank, int pumpingRate) {
9 | this.tank = tank;
10 | this.pumpingRate = pumpingRate;
11 | }
12 |
13 | @Override
14 | public void run() {
15 | while (!isInterrupted()) {
16 | try {
17 | tank.pumpWater(pumpingRate);
18 | Thread.sleep(1000);
19 | } catch (InterruptedException e) {
20 | System.out.println(getName() + " thread interrupted. Stopping pumping.");
21 | interrupt();
22 | }
23 | }
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/interrupt/Tank.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.interrupt;
2 |
3 | public class Tank {
4 |
5 | private int capacity;
6 | private int currentLevel = 0;
7 |
8 | public Tank(int capacity) {
9 | this.capacity = capacity;
10 | }
11 |
12 | public synchronized void pumpWater(int pumpingRate) throws InterruptedException {
13 | if (currentLevel + pumpingRate > capacity) {
14 | System.out.println("Tank is full. Waiting for consumption...");
15 | wait();
16 | }
17 |
18 | currentLevel += pumpingRate;
19 | System.out.println("Pumping " + pumpingRate + " liters of water. Current level: " + currentLevel);
20 | }
21 |
22 | public synchronized void consumeWater(int amount) {
23 | if ( amount <= currentLevel) {
24 | currentLevel -= amount;
25 | System.out.println("Consuming " + amount + "liter(s) of water. Current level: " + currentLevel);
26 | notify();
27 | }
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/join/JoinApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.join;
2 |
3 | public class JoinApp {
4 |
5 | public static void main(String[] args) {
6 | RecipeStep onion = new RecipeStep("Dice 2 onions!", 2000);
7 | RecipeStep tomato = new RecipeStep("Dice 2 tomatoes!", 2000);
8 | RecipeStep pan = new RecipeStep("Get a pan and start frying the diced onion!", 2000);
9 | RecipeStep water = new RecipeStep("Boil 1L of water!", 10000);
10 | RecipeStep pasta = new RecipeStep("Put the pasta into the boiling water!", 500);
11 |
12 | Thread onionThread = new Thread(onion);
13 | Thread tomatoThread = new Thread(tomato);
14 | Thread panThread = new Thread(pan);
15 | Thread waterThread = new Thread(water);
16 | Thread pastaThread = new Thread(pasta);
17 |
18 | try {
19 | onionThread.start();
20 | onionThread.join();
21 | tomatoThread.start();
22 | tomatoThread.join();
23 | panThread.start();
24 | waterThread.start();
25 | waterThread.join();
26 | pastaThread.start();
27 | } catch (InterruptedException e) {
28 | e.printStackTrace();
29 | }
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/join/RecipeStep.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.join;
2 |
3 | public class RecipeStep implements Runnable {
4 |
5 | private final String description;
6 | private final int duration;
7 |
8 | public RecipeStep(String description, int duration) {
9 | this.description = description;
10 | this.duration = duration;
11 | }
12 |
13 | @Override
14 | public void run() {
15 |
16 | try {
17 | System.out.println(description);
18 | Thread.sleep(duration);
19 | } catch (InterruptedException e) {
20 | e.printStackTrace();
21 | }
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/mutex/BankAccount.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.mutex;
2 |
3 | import java.util.concurrent.locks.Lock;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 | public class BankAccount {
7 | private double balance;
8 | private final Lock lock = new ReentrantLock(true);
9 |
10 | public BankAccount(double balance) {
11 | this.balance = balance;
12 | }
13 |
14 | public void withdraw(double amount) {
15 | lock.lock();
16 | try {
17 | if (balance >= amount) {
18 | balance -= amount;
19 | System.out.println(Thread.currentThread().getName() + " - Withdrawn: $" + amount + ", New Balance: $" + balance);
20 | // try {
21 | // Thread.sleep(1000);
22 | // } catch (InterruptedException e) {
23 | // e.printStackTrace();
24 | // }
25 | } else {
26 | System.out.println("Insufficient funds. Balance: $" + balance);
27 | }
28 | } finally {
29 | lock.unlock();
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/mutex/MutexApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.mutex;
2 |
3 | public class MutexApp {
4 |
5 | public static void main(String[] args) {
6 | BankAccount bankAccount = new BankAccount(1000);
7 | Runnable withdrawal = () -> {
8 | for (int i = 0; i < 5; i++) {
9 | if (i == 1 && Thread.currentThread().getName().contains("0")) {
10 | Thread.yield();
11 | System.out.println(Thread.currentThread().getName() + " yielded.");
12 | }
13 | bankAccount.withdraw(200);
14 | }
15 | };
16 |
17 | Thread mom = new Thread(withdrawal);
18 | Thread dad = new Thread(withdrawal);
19 |
20 | mom.start();
21 | dad.start();
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/producerconsumer/Message.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.producerconsumer;
2 |
3 | public class Message {
4 |
5 | private String message;
6 |
7 | public Message(String message) {
8 | this.message = message;
9 | }
10 |
11 | public String getMessage() {
12 | return message;
13 | }
14 |
15 | public void setMessage(String message) {
16 | this.message = message;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/producerconsumer/MessageConsumer.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.producerconsumer;
2 |
3 | import java.util.concurrent.BlockingQueue;
4 |
5 | public class MessageConsumer implements Runnable {
6 |
7 | private BlockingQueue queue;
8 |
9 | public MessageConsumer(BlockingQueue queue) {
10 | this.queue = queue;
11 | }
12 |
13 | @Override
14 | public void run() {
15 | try {
16 | Message message;
17 | while (!"exit".equals((message = queue.take()).getMessage())) {
18 | Thread.sleep(100);
19 | System.out.println("Message is consumed: " + message.getMessage());
20 | }
21 | } catch (InterruptedException e) {
22 | throw new RuntimeException(e);
23 | }
24 |
25 |
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/producerconsumer/MessageProducer.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.producerconsumer;
2 |
3 | import java.util.concurrent.BlockingQueue;
4 |
5 | public class MessageProducer implements Runnable {
6 |
7 | private BlockingQueue queue;
8 |
9 | public MessageProducer(BlockingQueue queue) {
10 | this.queue = queue;
11 | }
12 |
13 | @Override
14 | public void run() {
15 | for (int i = 0; i < 100; i++) {
16 | Message message = new Message("" + i);
17 | try {
18 | queue.put(message);
19 | System.out.println("Message added to queue: " + message.getMessage());
20 | } catch (InterruptedException e) {
21 | throw new RuntimeException(e);
22 | }
23 | }
24 | try {
25 | queue.put(new Message("exit"));
26 | } catch (InterruptedException e) {
27 | throw new RuntimeException(e);
28 | }
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/producerconsumer/ProducerConsumerApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.producerconsumer;
2 |
3 | import java.util.concurrent.ArrayBlockingQueue;
4 | import java.util.concurrent.BlockingQueue;
5 |
6 | public class ProducerConsumerApp {
7 |
8 | public static void main(String[] args) {
9 | BlockingQueue queue = new ArrayBlockingQueue<>(5);
10 | MessageProducer producer = new MessageProducer(queue);
11 | MessageConsumer consumer = new MessageConsumer(queue);
12 |
13 | new Thread(producer).start();
14 | new Thread(consumer).start();
15 |
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/runnable/RunnableApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.runnable;
2 |
3 | public class RunnableApp {
4 |
5 | public static void main(String[] args) {
6 | WebsiteModule offers = new WebsiteModule("offers");
7 | WebsiteModule sales = new WebsiteModule("sales");
8 | WebsiteModule recentSearches = new WebsiteModule("recentSearches");
9 |
10 | Thread offersThread = new Thread(offers);
11 | offersThread.start();
12 |
13 | Thread salesThread = new Thread(sales);
14 | salesThread.start();
15 |
16 | Thread recentSearchesThread = new Thread(recentSearches);
17 | recentSearchesThread.start();
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/runnable/WebsiteModule.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.runnable;
2 |
3 | public class WebsiteModule implements Runnable {
4 |
5 | private String moduleName;
6 |
7 | public WebsiteModule(String moduleName) {
8 | this.moduleName = moduleName;
9 | }
10 |
11 | @Override
12 | public void run() {
13 | for (int i = 5; i > 0; i--) {
14 | System.out.println( moduleName + " module will be loaded in " + i + "sec.");
15 | try {
16 | Thread.sleep(1000);
17 | } catch (InterruptedException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/semaphore/ParkingLot.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.semaphore;
2 |
3 | import java.util.concurrent.Semaphore;
4 |
5 | public class ParkingLot {
6 |
7 | private final Semaphore spots;
8 |
9 | public ParkingLot(int numberOfSpots) {
10 | spots = new Semaphore(numberOfSpots);
11 | }
12 |
13 | public void park() {
14 | try {
15 | spots.acquire();
16 | System.out.println("Car parked. Available spots: " + spots.availablePermits());
17 | Thread.sleep(1000);
18 | } catch (InterruptedException e) {
19 | e.printStackTrace();
20 | } finally {
21 | System.out.println("Car left. Available spots: " + spots.availablePermits());
22 | spots.release();
23 | }
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/semaphore/SemaphoreApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.semaphore;
2 |
3 | public class SemaphoreApp {
4 |
5 | public static void main(String[] args) {
6 | ParkingLot parkingLot = new ParkingLot(5);
7 |
8 | Runnable parkCar = () -> {
9 | for (int i = 0; i < 2; i++) {
10 | parkingLot.park();
11 | }
12 | };
13 |
14 | for (int i = 0; i < 10; i++) {
15 | new Thread(parkCar).start();
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/sync/BankAccount.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.sync;
2 |
3 | public class BankAccount {
4 |
5 | private int balance;
6 |
7 | public BankAccount(int balance) {
8 | this.balance = balance;
9 | }
10 |
11 | public void deposit(int amount) {
12 | balance += amount;
13 | System.out.println("Deposit of $" + amount + " successful. New balance: $" + balance);
14 | }
15 |
16 | public synchronized void withdraw(int amount) {
17 | if (amount > balance) {
18 | System.out.println("Insufficient funds.");
19 | } else {
20 | try {
21 | System.out.println("3DS verification in progress.");
22 | Thread.sleep(2000);
23 | } catch (InterruptedException e) {
24 | e.printStackTrace();
25 | }
26 | balance -= amount;
27 | System.out.println("Withdrawal of $" + amount + " successful. New balance: $" + balance);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/sync/SynchronizedApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.sync;
2 |
3 | public class SynchronizedApp {
4 |
5 | public static void main(String[] args) {
6 | BankAccount account = new BankAccount(1000);
7 |
8 | Thread withdrawalMom = new Thread(() -> account.withdraw(800));
9 | Thread withdrawalDad = new Thread(() -> account.withdraw(400));
10 |
11 | withdrawalMom.start();
12 | withdrawalDad.start();
13 |
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/thread/ThreadApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.thread;
2 |
3 | public class ThreadApp {
4 |
5 | public static void main(String[] args) {
6 |
7 | WebsiteModule offers = new WebsiteModule("offers");
8 | WebsiteModule sales = new WebsiteModule("sales");
9 | WebsiteModule recentSearches = new WebsiteModule("recentSearches");
10 |
11 | offers.start();
12 | sales.start();
13 | recentSearches.start();
14 | throw new RuntimeException();
15 |
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/thread/WebsiteModule.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.thread;
2 |
3 | public class WebsiteModule extends Thread {
4 |
5 | private String moduleName;
6 |
7 | public WebsiteModule(String moduleName) {
8 | this.moduleName = moduleName;
9 | }
10 |
11 | @Override
12 | public void run() {
13 | for (int i = 5; i > 0; i--) {
14 | System.out.println( moduleName + " module will be loaded in " + i + "sec.");
15 | try {
16 | Thread.sleep(1000);
17 | } catch (InterruptedException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 |
22 | }
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/threadvariables/BankApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.threadvariables;
2 |
3 | public class BankApp {
4 |
5 | public static void main(String[] args) {
6 | Transaction transaction = new Transaction();
7 | new Thread(transaction).start();
8 | new Thread(transaction).start();
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/threadvariables/Transaction.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.threadvariables;
2 |
3 | import java.util.Random;
4 |
5 | public class Transaction implements Runnable {
6 | private double balance;
7 |
8 | @Override
9 | public void run() {
10 | balance = new Random().nextDouble() * 100;
11 | double transactionAmount = new Random().nextDouble() * 100;
12 | System.out.println("Balance: " + balance + " Transaction amount: " + transactionAmount);
13 |
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/volatilekeyword/BalanceReader.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.volatilekeyword;
2 |
3 | public class BalanceReader extends Thread {
4 |
5 | private BankAccount bankAccount;
6 |
7 | public BalanceReader(BankAccount bankAccount) {
8 | this.bankAccount = bankAccount;
9 | }
10 |
11 | @Override
12 | public void run() {
13 | double balance = bankAccount.getBalance();
14 | while (balance < 10000) {
15 | if(balance != bankAccount.getBalance()) {
16 | System.out.println("Balance is changed. The new balance is: $" + bankAccount.getBalance());
17 | balance = bankAccount.getBalance();
18 | }
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/volatilekeyword/BankAccount.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.volatilekeyword;
2 |
3 | public class BankAccount {
4 |
5 | private volatile double balance;
6 |
7 | public BankAccount(double balance) {
8 | this.balance = balance;
9 | }
10 |
11 | public double getBalance() {
12 | return balance;
13 | }
14 |
15 | public void deposit(double amount) {
16 | try {
17 | Thread.sleep(1000);
18 | } catch (InterruptedException e) {
19 | e.printStackTrace();
20 | }
21 | balance += amount;
22 | System.out.println("$" + amount + " added to the balance.");
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/hero/multithreading/volatilekeyword/VolatileApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.multithreading.volatilekeyword;
2 |
3 | public class VolatileApp {
4 |
5 | public static void main(String[] args) throws InterruptedException {
6 | BankAccount bankAccount = new BankAccount(1000);
7 | BalanceReader balanceReader = new BalanceReader(bankAccount);
8 | balanceReader.start();
9 |
10 | BalanceReader anotherBalanceReader = new BalanceReader(bankAccount);
11 | anotherBalanceReader.start();
12 |
13 | bankAccount.deposit(1000);
14 | bankAccount.deposit(2000);
15 | bankAccount.deposit(3000);
16 | bankAccount.deposit(2500);
17 | bankAccount.deposit(1500);
18 |
19 | System.out.println("Final balance: $" + bankAccount.getBalance());
20 | }
21 | }
--------------------------------------------------------------------------------
/src/com/hero/optional/empty/EmptyApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.empty;
2 |
3 | import java.util.Optional;
4 | import java.util.Scanner;
5 |
6 | public class EmptyApp {
7 |
8 | public static void main(String[] args) {
9 |
10 | // Optional nullStringOptional = null;
11 | // nullStringOptional.ifPresentOrElse(System.out::println, () -> System.out.println("Empty"));
12 |
13 | Optional emptyOptionalString = Optional.empty();
14 | emptyOptionalString.ifPresentOrElse(System.out::println, () -> System.out.println("Empty"));
15 |
16 | FindFriendServiceEmpty findFriendServiceEmpty = new FindFriendServiceEmpty();
17 | Scanner userInput = new Scanner(System.in);
18 |
19 | findFriendServiceEmpty.findFriend(userInput.nextLine())
20 | .ifPresentOrElse(System.out::println, () -> System.out.println("Not found."));
21 |
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/hero/optional/empty/FindFriendServiceEmpty.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.empty;
2 |
3 | import com.hero.optional.oldway.Friend;
4 |
5 | import java.util.List;
6 | import java.util.Optional;
7 |
8 | public class FindFriendServiceEmpty {
9 |
10 | public Optional findFriend(String friendName) {
11 | List friends = List.of(
12 | new Friend(123123L, "Adrian", 31, 1245),
13 | new Friend(123124L, "Lala", 29, 345),
14 | new Friend(123125L, "Diego", 43, 432),
15 | new Friend(123126L, "Sasha", 22, 564));
16 | Optional friendFound = Optional.empty();
17 | for (Friend friend : friends) {
18 | if (friendName.equals(friend.getName())) {
19 | friendFound = Optional.ofNullable(friend);
20 | }
21 | }
22 | return friendFound;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/hero/optional/filter/EmailServiceFilter.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.filter;
2 |
3 | import com.hero.optional.ifpresent.User;
4 |
5 | public class EmailServiceFilter {
6 | public static void sendPromotion(User user) {
7 | user.getEmail()
8 | .filter(email -> email.length() > 3 && email.contains("@") && email.contains("."))
9 | .ifPresentOrElse(
10 | email -> System.out.println("Promotion email is sent to: " + email),
11 | () -> System.out.println("Promotion SMS is sent to:" + user.getPhoneNumber())
12 | );
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/hero/optional/filter/FilterApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.filter;
2 |
3 | import com.hero.optional.ifpresent.User;
4 | import com.hero.optional.ifpresent.UserRepository;
5 |
6 | import java.util.ArrayList;
7 |
8 | public class FilterApp {
9 |
10 | public static void main(String[] args) {
11 | ArrayList users = UserRepository.getUsers();
12 | users.forEach(EmailServiceFilter::sendPromotion);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/hero/optional/get/GetApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.get;
2 |
3 | import java.util.Optional;
4 | import java.util.Scanner;
5 |
6 | public class GetApp {
7 |
8 | public static void main(String[] args) {
9 | Optional username = Optional.ofNullable(getUsername());
10 | if (username.isPresent()) {
11 | System.out.println("The username entered: " + username.get());
12 | System.out.println("Welcome, " + username.get() + "!");
13 | }
14 |
15 | }
16 |
17 | private static String getUsername() {
18 | Scanner userInput = new Scanner(System.in);
19 | String input = userInput.nextLine();
20 | return input.length() > 0 ? input : null;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/hero/optional/ifpresent/EmailService.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.ifpresent;
2 |
3 | public class EmailService {
4 |
5 | public static void sendPromotion(User user) {
6 | user.getEmail().ifPresent(
7 | email -> System.out.println("Promotion email is sent to: " + email)
8 | );
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/com/hero/optional/ifpresent/IfPresentApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.ifpresent;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class IfPresentApp {
6 |
7 | public static void main(String[] args) {
8 | ArrayList users = UserRepository.getUsers();
9 | users.forEach(EmailService::sendPromotion);
10 |
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/hero/optional/ifpresent/User.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.ifpresent;
2 |
3 | import java.util.Optional;
4 |
5 | public class User {
6 |
7 | private String name;
8 | private String email;
9 | private String phoneNumber;
10 |
11 | public User(String name, String email, String phoneNumber) {
12 | this.name = name;
13 | this.email = email;
14 | this.phoneNumber = phoneNumber;
15 | }
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public void setName(String name) {
22 | this.name = name;
23 | }
24 |
25 | public Optional getEmail() {
26 | return Optional.ofNullable(email);
27 | }
28 |
29 | public void setEmail(String email) {
30 | this.email = email;
31 | }
32 |
33 | public String getPhoneNumber() {
34 | return phoneNumber;
35 | }
36 |
37 | public void setPhoneNumber(String phoneNumber) {
38 | this.phoneNumber = phoneNumber;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/com/hero/optional/ifpresentorelse/EmailService.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.ifpresentorelse;
2 |
3 | import com.hero.optional.ifpresent.User;
4 |
5 | public class EmailService {
6 |
7 | public static void sendPromotion(User user) {
8 | user.getEmail().ifPresentOrElse(
9 | email -> System.out.println("Promotion email is sent to: " + email),
10 | () -> System.out.println("Promotion SMS is sent to:" + user.getPhoneNumber())
11 | );
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/hero/optional/ifpresentorelse/IfPresentOrElseApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.ifpresentorelse;
2 |
3 | import com.hero.optional.ifpresent.User;
4 | import com.hero.optional.ifpresent.UserRepository;
5 |
6 | import java.util.ArrayList;
7 |
8 | public class IfPresentOrElseApp {
9 |
10 | public static void main(String[] args) {
11 | ArrayList users = UserRepository.getUsers();
12 | users.forEach(EmailService::sendPromotion);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/hero/optional/isempty/IsEmptyApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.isempty;
2 |
3 | import com.hero.optional.empty.FindFriendServiceEmpty;
4 | import com.hero.optional.oldway.Friend;
5 |
6 | import java.util.Optional;
7 | import java.util.Scanner;
8 |
9 | public class IsEmptyApp {
10 |
11 | public static void main(String[] args) {
12 |
13 | FindFriendServiceEmpty findFriendServiceEmpty = new FindFriendServiceEmpty();
14 | Scanner userInput = new Scanner(System.in);
15 |
16 | Optional friend = findFriendServiceEmpty.findFriend(userInput.nextLine());
17 | if (friend.isEmpty()) {
18 | System.out.println("Not found.");
19 | } else {
20 | System.out.println(friend.get());
21 | }
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/hero/optional/newway/NewWayApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.newway;
2 |
3 | import com.hero.optional.oldway.Friend;
4 | import com.hero.optional.oldway.FriendFinderService;
5 |
6 | import java.util.Optional;
7 | import java.util.Scanner;
8 |
9 | public class NewWayApp {
10 |
11 | public static void main(String[] args) {
12 |
13 | FriendFinderService friendFinderService = new FriendFinderService();
14 | Scanner userInput = new Scanner(System.in);
15 |
16 | System.out.println("Find friend:");
17 | Optional friend = Optional.ofNullable(friendFinderService.findFriend(userInput.nextLine()));
18 | friend.ifPresentOrElse(System.out::println, () -> System.out.println("Not found."));
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/hero/optional/of/OfAndOfNullableApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.of;
2 |
3 | import java.util.Optional;
4 | import java.util.Scanner;
5 |
6 | public class OfAndOfNullableApp {
7 |
8 | public static void main(String[] args) {
9 | System.out.println("Enter your username of identification:");
10 | Optional username = Optional.of(getUsername());
11 | if (!"".equals(username.get())) {
12 | System.out.println("Welcome, " + username.get() + "!");
13 | } else {
14 | System.out.println("Username is not entered.");
15 | }
16 |
17 | }
18 |
19 | private static String getUsername() {
20 | Scanner userInput = new Scanner(System.in);
21 | String input = userInput.nextLine();
22 | return input.length() > 0 ? input : "";
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/hero/optional/oldway/Friend.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.oldway;
2 |
3 | import java.util.Objects;
4 |
5 | public class Friend {
6 |
7 | private long id;
8 | private String name;
9 | private int age;
10 | private int numberOfFriends;
11 |
12 | public Friend(long id, String name, int age, int numberOfFriends) {
13 | this.id = id;
14 | this.name = name;
15 | this.age = age;
16 | this.numberOfFriends = numberOfFriends;
17 | }
18 |
19 | public long getId() {
20 | return id;
21 | }
22 |
23 | public void setId(long id) {
24 | this.id = id;
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 |
31 | public void setName(String name) {
32 | this.name = name;
33 | }
34 |
35 | public int getAge() {
36 | return age;
37 | }
38 |
39 | public void setAge(int age) {
40 | this.age = age;
41 | }
42 |
43 | public int getNumberOfFriends() {
44 | return numberOfFriends;
45 | }
46 |
47 | public void setNumberOfFriends(int numberOfFriends) {
48 | this.numberOfFriends = numberOfFriends;
49 | }
50 |
51 | @Override
52 | public String toString() {
53 | return "Friend{" +
54 | "id=" + id +
55 | ", name='" + name + '\'' +
56 | ", age=" + age +
57 | ", numberOfFriends=" + numberOfFriends +
58 | '}';
59 | }
60 |
61 | @Override
62 | public boolean equals(Object o) {
63 | if (this == o) return true;
64 | if (o == null || getClass() != o.getClass()) return false;
65 | Friend friend = (Friend) o;
66 | return id == friend.id && age == friend.age && numberOfFriends == friend.numberOfFriends && name.equals(friend.name);
67 | }
68 |
69 | @Override
70 | public int hashCode() {
71 | return Objects.hash(id, name, age, numberOfFriends);
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/com/hero/optional/oldway/FriendFinderService.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.oldway;
2 |
3 | import java.util.List;
4 |
5 | public class FriendFinderService {
6 |
7 | public Friend findFriend(String friendName) {
8 | List friends = List.of(
9 | new Friend(123123L, "Adrian", 31, 1245),
10 | new Friend(123124L, "Lala", 29, 345),
11 | new Friend(123125L, "Diego", 43, 432),
12 | new Friend(123126L, "Sasha", 22, 564));
13 | Friend friendFound = null;
14 | for (Friend friend : friends) {
15 | if (friendName.equals(friend.getName())) {
16 | friendFound = friend;
17 | }
18 | }
19 | return friendFound;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/hero/optional/oldway/OldWayApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.oldway;
2 |
3 | import java.util.Scanner;
4 |
5 | public class OldWayApp {
6 |
7 | public static void main(String[] args) {
8 | FriendFinderService friendFinderService = new FriendFinderService();
9 | Scanner userInput = new Scanner(System.in);
10 |
11 | System.out.println("Find friend:");
12 | Friend friend = friendFinderService.findFriend(userInput.nextLine());
13 | if (friend != null) {
14 | System.out.println(friend.toString());
15 | } else {
16 | System.out.println("Not found");
17 | }
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/hero/optional/orelse/EmailServiceOrElse.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.orelse;
2 |
3 | import com.hero.optional.ifpresent.User;
4 |
5 | public class EmailServiceOrElse {
6 |
7 | public static void sendPromotion(User user) {
8 | String email = user.getEmail().orElse(guessingEmailAddress(user));
9 | System.out.println("Promotion email is sent to: " + email);
10 | }
11 |
12 | private static String guessingEmailAddress(User user) {
13 | System.out.println("Guessing the email address for: " + user.getName());
14 | return user.getName().toLowerCase() + "@example.com";
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/hero/optional/orelse/OrElseApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.orelse;
2 |
3 | import com.hero.optional.ifpresent.User;
4 | import com.hero.optional.ifpresent.UserRepository;
5 |
6 | import java.util.ArrayList;
7 |
8 | public class OrElseApp {
9 |
10 | public static void main(String[] args) {
11 | ArrayList users = UserRepository.getUsers();
12 | users.forEach(EmailServiceOrElse::sendPromotion);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/hero/optional/orelseget/EmailServiceOrElseGet.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.orelseget;
2 |
3 | import com.hero.optional.ifpresent.User;
4 |
5 | public class EmailServiceOrElseGet {
6 |
7 | public static void sendPromotion(User user) {
8 | String email = user.getEmail().orElseGet(() -> user.getName().toLowerCase() + "@example.com");
9 | System.out.println("Promotion email is sent to: " + email);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/com/hero/optional/orelseget/OrElseGetApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.orelseget;
2 |
3 | import com.hero.optional.ifpresent.User;
4 | import com.hero.optional.ifpresent.UserRepository;
5 |
6 | import java.util.ArrayList;
7 |
8 | public class OrElseGetApp {
9 |
10 | public static void main(String[] args) {
11 | ArrayList users = UserRepository.getUsers();
12 | users.forEach(EmailServiceOrElseGet::sendPromotion);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/hero/optional/orelsethrow/EmailServiceOrElseThrow.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.orelsethrow;
2 |
3 | import com.hero.optional.ifpresent.User;
4 |
5 | import java.util.NoSuchElementException;
6 |
7 | public class EmailServiceOrElseThrow {
8 |
9 | public static void sendPromotion(User user) {
10 | try {
11 | String email = user.getEmail().orElseThrow(NoSuchElementException::new);
12 | System.out.println("Promotion email is sent to: " + email);
13 | } catch (NoSuchElementException exception) {
14 | System.out.println("Something is wrong with the email address.");
15 | }
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/hero/optional/orelsethrow/OrElseThrowApp.java:
--------------------------------------------------------------------------------
1 | package com.hero.optional.orelsethrow;
2 |
3 | import com.hero.optional.ifpresent.User;
4 | import com.hero.optional.ifpresent.UserRepository;
5 |
6 | import java.util.ArrayList;
7 |
8 | public class OrElseThrowApp {
9 |
10 | public static void main(String[] args) {
11 | ArrayList users = UserRepository.getUsers();
12 | users.forEach(EmailServiceOrElseThrow::sendPromotion);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/athlete/Athlete.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.athlete;
2 |
3 | public abstract class Athlete {
4 |
5 | private String name;
6 | private String nickname;
7 | private int yearOfBorn;
8 | private String team;
9 | private int numberOfCompetitions;
10 |
11 | public Athlete(String name, String nickname, int yearOfBorn, String team, int numberOfCompetitions) {
12 | this.name = name;
13 | this.nickname = nickname;
14 | this.yearOfBorn = yearOfBorn;
15 | this.team = team;
16 | this.numberOfCompetitions = numberOfCompetitions;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 | public void getBio() {
24 | System.out.println(name + " (" + nickname + ")");
25 | System.out.println("Born in " + yearOfBorn);
26 | System.out.println("Last team is " + team + " and took part in " + numberOfCompetitions + " competitions");
27 | }
28 |
29 | public void compete() {
30 | System.out.println(name + " took part in a competition.");
31 | numberOfCompetitions++;
32 | }
33 |
34 | public String getTeam() {
35 | return team;
36 | }
37 |
38 | public void setTeam(String team) {
39 | this.team = team;
40 | }
41 |
42 | public abstract String getBodyType();
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/athlete/BasketballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.athlete;
2 |
3 | import java.util.Random;
4 |
5 | public class BasketballPlayer extends Athlete {
6 |
7 | private double freeThrowPercentage;
8 | private double pointsPerGame;
9 |
10 | public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
11 | super(name, nickname, yearOfBorn, team, gamesPlayed);
12 | this.freeThrowPercentage = freeThrowPercentage;
13 | this.pointsPerGame = pointsPerGame;
14 | }
15 |
16 | public void freeThrow(){
17 | Random randomNumberGenerator = new Random();
18 | if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
19 | System.out.println(super.getName() + " failed to score free throw.");
20 | } else {
21 | System.out.println(super.getName() + " scored free throw.");
22 | }
23 | }
24 |
25 | @Override
26 | public void getBio() {
27 | super.getBio();
28 | System.out.println("Free throw percentage: " + freeThrowPercentage);
29 | System.out.println("Points per game: " + pointsPerGame);
30 | }
31 |
32 | @Override
33 | public void compete() {
34 | super.compete();
35 | freeThrow();
36 | }
37 |
38 | @Override
39 | public String getBodyType() {
40 | return "Tall and lean muscle.";
41 | }
42 |
43 | public void setFreeThrowPercentage(double freeThrowPercentage) {
44 | this.freeThrowPercentage = freeThrowPercentage;
45 | }
46 |
47 | public void setPointsPerGame(double pointsPerGame) {
48 | this.pointsPerGame = pointsPerGame;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/athlete/FootballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.athlete;
2 |
3 | public class FootballPlayer extends Athlete {
4 |
5 | private int completions;
6 | private int passingYards;
7 |
8 | public FootballPlayer(String name, String nickname, int yearOfBorn, String team, int gamesPlayed, int completions, int passingYards) {
9 | super(name, nickname, yearOfBorn, team, gamesPlayed);
10 | this.completions = completions;
11 | this.passingYards = passingYards;
12 | }
13 |
14 | @Override
15 | public void getBio() {
16 | super.getBio();
17 | System.out.println("Completions: " + completions);
18 | System.out.println("Passing yards: " + passingYards);
19 | }
20 |
21 | @Override
22 | public String getBodyType() {
23 | return "Big muscles and great endurance.";
24 | }
25 |
26 | public void increaseCompletions(int completions) {
27 | this.completions += completions;
28 | }
29 |
30 | public void increasePassingYards(int passingYards) {
31 | this.passingYards += passingYards;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/athlete/Swimmer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.athlete;
2 |
3 | public class Swimmer extends Athlete implements Swimming{
4 |
5 | private int finaPoints;
6 |
7 | public Swimmer(String name, String nickname, int yearOfBorn, String team, int numberOfCompetitions, int finaPoints) {
8 | super(name, nickname, yearOfBorn, team, numberOfCompetitions);
9 | this.finaPoints = finaPoints;
10 | }
11 |
12 | @Override
13 | public String getBodyType() {
14 | return "Lean muscle, long torso and flexible ankles.";
15 | }
16 |
17 | @Override
18 | public void getBio() {
19 | super.getBio();
20 | System.out.println("FINA points: " + finaPoints);
21 | }
22 |
23 | @Override
24 | public void freestyle() {
25 | System.out.println("Swimming freestyle very fast.");
26 | }
27 |
28 | @Override
29 | public void compete() {
30 | super.compete();
31 | freestyle();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/athlete/Swimming.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.athlete;
2 |
3 | public interface Swimming {
4 | void freestyle();
5 | }
6 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/car/CarsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.car;
2 |
3 | public class CarsApp {
4 |
5 | public static void main(String[] args) {
6 | DodgeChallenger redDodgeChallenger = new DodgeChallenger("red", (byte)3, (short)450, (short)717, (short)7700, 40000, 15000, true);
7 | System.out.println(redDodgeChallenger.getCarName() + "'s price is $" + redDodgeChallenger.getPrice());
8 | redDodgeChallenger.setPrice(-35000);
9 | System.out.println(redDodgeChallenger.getCarName() + "'s new price is $" + redDodgeChallenger.getPrice());
10 | System.out.println("The car is in city mode.");
11 | redDodgeChallenger.startTheElectricEngine();
12 | System.out.println("The car has " + redDodgeChallenger.getMileage() + "miles");
13 | redDodgeChallenger.drive(0);
14 | System.out.println("After driving the car, it has " + redDodgeChallenger.getMileage() + "miles");
15 |
16 | System.out.println("----------------------------------------------");
17 | ToyotaSupra blackToyotaSupra = new ToyotaSupra("black", (byte)1, (short)225, (short)717, (short)3500, 40000, 15000, false);
18 | System.out.println(blackToyotaSupra.getCarName() + "'s price is $" + blackToyotaSupra.getPrice());
19 | blackToyotaSupra.setPrice(32000);
20 | System.out.println(blackToyotaSupra.getCarName() + "'s new price is $" + blackToyotaSupra.getPrice());
21 | blackToyotaSupra.startTheEngine();
22 | System.out.println("The car has " + blackToyotaSupra.getMileage() + "miles");
23 | blackToyotaSupra.drive(200);
24 | System.out.println("After driving the car, it has " + blackToyotaSupra.getMileage() + "miles");
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/car/DodgeChallenger.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.car;
2 |
3 | public class DodgeChallenger extends Car implements ElectricMode{
4 |
5 |
6 | public DodgeChallenger(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity,
7 | int price, int mileage, boolean isDamaged){
8 | super("Dodge Challenger", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
9 | }
10 |
11 | @Override
12 | public void startTheEngine() {
13 | System.out.println("A Dodge Challenger engine is started.");
14 | }
15 |
16 | @Override
17 | public void startTheElectricEngine() {
18 | System.out.println("Dodge Challenger starts its electric engine.");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/car/ElectricMode.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.car;
2 |
3 | public interface ElectricMode {
4 | void startTheElectricEngine();
5 | }
6 |
--------------------------------------------------------------------------------
/src/com/intermediate/abstraction/car/ToyotaSupra.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.abstraction.car;
2 |
3 | public class ToyotaSupra extends Car {
4 | public ToyotaSupra(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity, int price, int mileage, boolean isDamaged) {
5 | super("Toyota Supra", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
6 | }
7 |
8 | @Override
9 | public void startTheEngine() {
10 | System.out.println("A Toyota Supra Engine is started.");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/intermediate/classesandobjects/BasketballApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.classesandobjects;
2 |
3 | public class BasketballApp {
4 |
5 | public static void main(String[] args) {
6 | BasketballPlayer kobe = new BasketballPlayer("Kobe Bryant", "Black Mamba", 1978, "Lakers", 83.7, 25.0, 1346);
7 | BasketballPlayer jordan = new BasketballPlayer("Michael Jordan", "MJ", 1963, "Chicago Bulls", 83.5, 30.1, 1072);
8 | BasketballPlayer magic = new BasketballPlayer("Earvin Johnson", "Magic", 1959, "Lakers", 84.8, 19.5, 906);
9 |
10 | BasketballPlayer[] basketballPlayers = new BasketballPlayer[3];
11 | basketballPlayers[0] = kobe;
12 | basketballPlayers[1] = jordan;
13 | basketballPlayers[2] = magic;
14 |
15 | for (BasketballPlayer basketballPlayer : basketballPlayers) {
16 | basketballPlayer.freeThrow();
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/intermediate/classesandobjects/BasketballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.classesandobjects;
2 |
3 | import java.util.Random;
4 |
5 | public class BasketballPlayer {
6 |
7 | private String name;
8 | private String nickname;
9 | private int yearOfBorn;
10 | private String team;
11 |
12 | private double freeThrowPercentage;
13 | private double pointsPerGame;
14 | private int gamesPlayed;
15 |
16 | public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
17 | this.name = name;
18 | this.nickname = nickname;
19 | this.yearOfBorn = yearOfBorn;
20 | this.team = team;
21 | this.freeThrowPercentage = freeThrowPercentage;
22 | this.pointsPerGame = pointsPerGame;
23 | this.gamesPlayed = gamesPlayed;
24 | }
25 |
26 | public void freeThrow(){
27 | Random randomNumberGenerator = new Random();
28 | if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
29 | System.out.println(name + " failed to score free throw.");
30 | } else {
31 | System.out.println(name + " scored free throw.");
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/intermediate/classesandobjects/CarsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.classesandobjects;
2 |
3 | public class CarsApp {
4 |
5 | public static void main(String[] args) {
6 | DodgeChallenger redDodgeChallenger = new DodgeChallenger("red", (byte)3, (short)450, (short)717, (short)7700, 40000, 15000, true);
7 | redDodgeChallenger.getDescription();
8 | redDodgeChallenger.startTheEngine();
9 |
10 | System.out.println("----------------------------------------------");
11 | DodgeChallenger orangeDodgeChallenger = new DodgeChallenger("orange", (byte)1, (short)392, (short)492, (short)6700, 30000, 10000, false);
12 | orangeDodgeChallenger.getDescription();
13 | orangeDodgeChallenger.startTheEngine();
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/intermediate/comment/StringFunctionsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.comment;
2 |
3 | import java.util.Scanner;
4 |
5 | public class StringFunctionsApp {
6 |
7 | public static void main(String[] args) {
8 | Scanner keyboardInput = new Scanner(System.in);
9 | String inputText = keyboardInput.nextLine();
10 |
11 | if ("Paris".equals(inputText)) {
12 | System.out.println("The capital of France is typed in.");
13 | } else {
14 | System.out.println("The text typed in is: " + inputText);
15 | }
16 |
17 | if (inputText.equalsIgnoreCase("Paris")) {
18 | System.out.println("Paris was typed in.");
19 | } else {
20 | System.out.println("The text typed in is: " + inputText);
21 | }
22 |
23 | if (inputText.contains("Par")) {
24 | System.out.println("The input text contains Par.");
25 | }
26 |
27 | if (inputText.isEmpty()) {
28 | System.out.println("The input text is empty.");
29 | }
30 |
31 | System.out.println("The input text's length is: " + inputText.length());
32 | System.out.println("The input text with uppercase: " + inputText.toUpperCase());
33 | System.out.println("The input text with lowercase: " + inputText.toLowerCase());
34 |
35 | if (inputText.startsWith("P") || inputText.endsWith("P")) {
36 | System.out.println("The input text starts or ends with a P letter.");
37 | }
38 |
39 | System.out.println("The replaced text: " + inputText.replace("N", "D"));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/intermediate/defaultvalues/Car.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.defaultvalues;
2 |
3 | public class Car {
4 | private byte numberOfSeats;
5 | private short horsepower;
6 | private int price;
7 | private long registrationNumber;
8 |
9 | private float fuelConsumption;
10 | private double preciseFuelConsumption;
11 |
12 | private boolean isDamaged;
13 | private char energyEfficiencyCategory;
14 | private String color;
15 |
16 | private Boolean hasElectricEngine;
17 | private Engine engine;
18 |
19 | public void getDetails() {
20 | System.out.println("Number of seats: " + numberOfSeats);
21 | System.out.println("Horsepower: " + horsepower);
22 | System.out.println("Price: " + price);
23 | System.out.println("Registration number: " + registrationNumber);
24 | System.out.println("Fuel consumption: " + fuelConsumption);
25 | System.out.println("Precise fuel consumption: " + preciseFuelConsumption);
26 | System.out.println("This car is damaged: " + isDamaged);
27 | System.out.println("Energy efficiency category: " + energyEfficiencyCategory);
28 | System.out.println("Car's color: " + color);
29 | System.out.println("This car has electric engine: " + hasElectricEngine);
30 | System.out.println("The engine this car has is: " + engine);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/intermediate/defaultvalues/DefaultValuesApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.defaultvalues;
2 |
3 | public class DefaultValuesApp {
4 |
5 | public static void main(String[] args) {
6 | Car car = new Car();
7 | car.getDetails();
8 | String modelName = "Dodge Challenger";
9 | System.out.println(modelName);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/com/intermediate/defaultvalues/Engine.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.defaultvalues;
2 |
3 | public class Engine {
4 | }
5 |
--------------------------------------------------------------------------------
/src/com/intermediate/encapsulation/athlete/Athlete.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.encapsulation.athlete;
2 |
3 | public class Athlete {
4 |
5 | private String name;
6 | private String nickname;
7 | private int yearOfBorn;
8 | private String team;
9 | private int gamesPlayed;
10 |
11 | public Athlete(String name, String nickname, int yearOfBorn, String team, int gamesPlayed) {
12 | this.name = name;
13 | this.nickname = nickname;
14 | this.yearOfBorn = yearOfBorn;
15 | this.team = team;
16 | this.gamesPlayed = gamesPlayed;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 | public void getBio() {
24 | System.out.println(name + " (" + nickname + ")");
25 | System.out.println("Born in " + yearOfBorn);
26 | System.out.println("Last team is " + team + " and played " + gamesPlayed + " games");
27 | }
28 |
29 | public void playGame() {
30 | System.out.println(name + " started a game.");
31 | gamesPlayed++;
32 | }
33 |
34 | public String getTeam() {
35 | return team;
36 | }
37 |
38 | public void setTeam(String team) {
39 | this.team = team;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/intermediate/encapsulation/athlete/BasketballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.encapsulation.athlete;
2 |
3 | import java.util.Random;
4 |
5 | public class BasketballPlayer extends Athlete {
6 |
7 | private double freeThrowPercentage;
8 | private double pointsPerGame;
9 |
10 | public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
11 | super(name, nickname, yearOfBorn, team, gamesPlayed);
12 | this.freeThrowPercentage = freeThrowPercentage;
13 | this.pointsPerGame = pointsPerGame;
14 | }
15 |
16 | public void freeThrow(){
17 | Random randomNumberGenerator = new Random();
18 | if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
19 | System.out.println(super.getName() + " failed to score free throw.");
20 | } else {
21 | System.out.println(super.getName() + " scored free throw.");
22 | }
23 | }
24 |
25 | @Override
26 | public void getBio() {
27 | super.getBio();
28 | System.out.println("Free throw percentage: " + freeThrowPercentage);
29 | System.out.println("Points per game: " + pointsPerGame);
30 | }
31 |
32 | @Override
33 | public void playGame() {
34 | super.playGame();
35 | freeThrow();
36 | }
37 |
38 | public void setFreeThrowPercentage(double freeThrowPercentage) {
39 | this.freeThrowPercentage = freeThrowPercentage;
40 | }
41 |
42 | public void setPointsPerGame(double pointsPerGame) {
43 | this.pointsPerGame = pointsPerGame;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/intermediate/encapsulation/athlete/FootballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.encapsulation.athlete;
2 |
3 | public class FootballPlayer extends Athlete {
4 |
5 | private int completions;
6 | private int passingYards;
7 |
8 | public FootballPlayer(String name, String nickname, int yearOfBorn, String team, int gamesPlayed, int completions, int passingYards) {
9 | super(name, nickname, yearOfBorn, team, gamesPlayed);
10 | this.completions = completions;
11 | this.passingYards = passingYards;
12 | }
13 |
14 | @Override
15 | public void getBio() {
16 | super.getBio();
17 | System.out.println("Completions: " + completions);
18 | System.out.println("Passing yards: " + passingYards);
19 | }
20 |
21 | public void increaseCompletions(int completions) {
22 | this.completions += completions;
23 | }
24 |
25 | public void increasePassingYards(int passingYards) {
26 | this.passingYards += passingYards;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/intermediate/encapsulation/car/CarsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.encapsulation.car;
2 |
3 | public class CarsApp {
4 |
5 | public static void main(String[] args) {
6 | DodgeChallenger redDodgeChallenger = new DodgeChallenger("red", (byte)3, (short)450, (short)717, (short)7700, 40000, 15000, true);
7 | System.out.println(redDodgeChallenger.getCarName() + "'s price is $" + redDodgeChallenger.getPrice());
8 | redDodgeChallenger.setPrice(-35000);
9 | System.out.println(redDodgeChallenger.getCarName() + "'s new price is $" + redDodgeChallenger.getPrice());
10 | redDodgeChallenger.startTheEngine();
11 | System.out.println("The car has " + redDodgeChallenger.getMileage() + "miles");
12 | redDodgeChallenger.drive(0);
13 | System.out.println("After driving the car, it has " + redDodgeChallenger.getMileage() + "miles");
14 |
15 | System.out.println("----------------------------------------------");
16 | ToyotaSupra blackToyotaSupra = new ToyotaSupra("black", (byte)1, (short)225, (short)717, (short)3500, 40000, 15000, false);
17 | System.out.println(blackToyotaSupra.getCarName() + "'s price is $" + blackToyotaSupra.getPrice());
18 | blackToyotaSupra.setPrice(32000);
19 | System.out.println(blackToyotaSupra.getCarName() + "'s new price is $" + blackToyotaSupra.getPrice());
20 | blackToyotaSupra.startTheEngine();
21 | System.out.println("The car has " + blackToyotaSupra.getMileage() + "miles");
22 | blackToyotaSupra.drive(200);
23 | System.out.println("After driving the car, it has " + blackToyotaSupra.getMileage() + "miles");
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/intermediate/encapsulation/car/DodgeChallenger.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.encapsulation.car;
2 |
3 | public class DodgeChallenger extends Car {
4 |
5 |
6 | public DodgeChallenger(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity,
7 | int price, int mileage, boolean isDamaged){
8 | super("Dodge Challenger", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
9 | }
10 |
11 | @Override
12 | public void startTheEngine() {
13 | System.out.println("A Dodge Challenger engine is started.");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/intermediate/encapsulation/car/ToyotaSupra.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.encapsulation.car;
2 |
3 | public class ToyotaSupra extends Car {
4 | public ToyotaSupra(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity, int price, int mileage, boolean isDamaged) {
5 | super("Toyota Supra", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
6 | }
7 |
8 | @Override
9 | public void startTheEngine() {
10 | System.out.println("A Toyota Supra Engine is started.");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/Building.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public class Building {
4 |
5 | private String name;
6 | private Item[] items;
7 |
8 | public Building(String name, Item[] items) {
9 | this.name = name;
10 | this.items = items;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 |
17 | public Item[] getItems() {
18 | return items;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/City.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public class City {
4 |
5 | private Building[] buildings = new Building[4];
6 |
7 | public City() {
8 | Item[] bankItems = new Item[2];
9 | bankItems[0] = new Item("Letter opener", 1.5);
10 | bankItems[1] = new Item("Stamp", 2.5);
11 | buildings[0] = new Building("Bank", bankItems);
12 |
13 | Item[] mansionItems = new Item[2];
14 | mansionItems[0] = new Item("Pair of fancy shoes", 25.0);
15 | mansionItems[1] = new Item("Broken glass", 0.1);
16 | buildings[1] = new Building("Mansion", mansionItems);
17 |
18 | Item[] postOfficeItems = new Item[2];
19 | postOfficeItems[0] = new Item("Letter to Jenny", 1.5);
20 | postOfficeItems[1] = new Item("Pencil", 2.0);
21 | buildings[2] = new Building("Post Office", postOfficeItems);
22 |
23 | Item[] supermarketItems = new Item[2];
24 | supermarketItems[0] = new Item("A loaf of bread", 2.5);
25 | supermarketItems[1] = new Item("A bag of tea", 6.5);
26 | buildings[3] = new Building("Supermarket", supermarketItems);
27 |
28 | }
29 |
30 | public Building[] getBuildings() {
31 | return buildings;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/Criminal.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public class Criminal extends Person {
4 |
5 | public static final int SUCCESS_PERCENTAGE = 20;
6 |
7 | public Criminal(String name, String nickname, int yearOfBorn, String expertIn, Item[] items) {
8 | super(name, nickname, yearOfBorn, expertIn, items);
9 | }
10 |
11 | @Override
12 | public void printBioData() {
13 | System.out.println("Criminal person:");
14 | super.printBioData();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/Detective.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public class Detective extends Person {
4 |
5 | public static final int SUCCESS_PERCENTAGE = 20;
6 |
7 | public Detective(String name, String nickname, int yearOfBorn, String expertIn, Item[] items) {
8 | super(name, nickname, yearOfBorn, expertIn, items);
9 | }
10 |
11 | @Override
12 | public void printBioData() {
13 | System.out.println("Detective:");
14 | super.printBioData();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/Item.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public class Item {
4 | private String name;
5 | private double value;
6 |
7 | public Item(String name, double value) {
8 | this.name = name;
9 | this.value = value;
10 | }
11 |
12 | public String getName() {
13 | return name;
14 | }
15 |
16 | public double getValue() {
17 | return value;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/Person.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public abstract class Person {
4 | private String name;
5 | private String nickname;
6 | private int yearOfBorn;
7 | private String expertIn;
8 | private Item[] items;
9 |
10 | public Person(String name, String nickname, int yearOfBorn, String expertIn, Item[] items) {
11 | this.name = name;
12 | this.nickname = nickname;
13 | this.yearOfBorn = yearOfBorn;
14 | this.expertIn = expertIn;
15 | this.items = items;
16 | }
17 |
18 | public void printBioData() {
19 | System.out.println("Name: " + name + " (" + nickname + ")");
20 | System.out.println("Year of born: " + yearOfBorn);
21 | System.out.println("Expert in: " + expertIn);
22 | System.out.println("The person has the following items:");
23 | for (Item item : items) {
24 | System.out.println("-" + item.getName());
25 | }
26 | }
27 |
28 | public String getName() {
29 | return name;
30 | }
31 |
32 | public String getNickname() {
33 | return nickname;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/Police.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | import java.util.Random;
4 |
5 | public class Police {
6 |
7 | private Detective adamPalmer;
8 |
9 | Police() {
10 | Item[] adamItems = new Item[2];
11 | adamItems[0] = new Item("Revolver", 500.0);
12 | adamItems[1] = new Item("Magnifying glass", 10.0);
13 | adamPalmer = new Detective("Adam Palmer", "Coyote", 1960, "chess", adamItems);
14 | }
15 |
16 | public boolean catchCriminals(Gang gang) {
17 | if (areCriminalsCaught()) {
18 | System.out.println(adamPalmer.getName() + " managed to catch the gang");
19 | if (gang.getSumRobbedValue() > 0) {
20 | System.out.println("The stolen items are recovered.");
21 | System.out.println("Their overall value is estimated to $" + gang.getSumRobbedValue());
22 | } else {
23 | System.out.println("The gang couldn't steal anything.");
24 | }
25 | return true;
26 | } else {
27 | System.out.println(adamPalmer.getName() + " couldn't catch the criminals.");
28 | System.out.println("They managed to steal items valued $" + gang.getSumRobbedValue());
29 | return false;
30 | }
31 | }
32 |
33 | private boolean areCriminalsCaught() {
34 | Random randomNumberGenerator = new Random();
35 | if (randomNumberGenerator.nextInt(101) >= Detective.SUCCESS_PERCENTAGE) {
36 | return false;
37 | }
38 | return true;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/com/intermediate/endsection/TheGreatRobberyApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.endsection;
2 |
3 | public class TheGreatRobberyApp {
4 |
5 | public static void main(String[] args) {
6 | City city = new City();
7 | Gang theGang = new Gang();
8 | Police police = new Police();
9 | theGang.printGangInfo();
10 | System.out.println();
11 | do {
12 | theGang.letsRob(city.getBuildings());
13 | } while (!police.catchCriminals(theGang));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/intermediate/finalkeyword/Brazil.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.finalkeyword;
2 |
3 | public class Brazil extends Country {
4 | public Brazil(String name, int population, String capital) {
5 | super(name, population, capital);
6 | }
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/intermediate/finalkeyword/Country.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.finalkeyword;
2 |
3 | public class Country {
4 |
5 | private final String NAME;
6 | private int population;
7 | private String capital;
8 |
9 | public Country(String name, int population, String capital) {
10 | NAME = name;
11 | this.population = population;
12 | this.capital = capital;
13 | }
14 |
15 | public final void populationChange(int change){
16 | population += change;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/athlete/Athlete.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.athlete;
2 |
3 | public class Athlete {
4 |
5 | private String name;
6 | private String nickname;
7 | private int yearOfBorn;
8 | private String team;
9 | private int gamesPlayed;
10 |
11 | public Athlete(String name, String nickname, int yearOfBorn, String team, int gamesPlayed) {
12 | this.name = name;
13 | this.nickname = nickname;
14 | this.yearOfBorn = yearOfBorn;
15 | this.team = team;
16 | this.gamesPlayed = gamesPlayed;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 | public void getBio() {
24 | System.out.println(name + " (" + nickname + ")");
25 | System.out.println("Born in " + yearOfBorn);
26 | System.out.println("Last team is " + team + " and played " + gamesPlayed + " games");
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/athlete/AthleteApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.athlete;
2 |
3 | public class AthleteApp {
4 |
5 | public static void main(String[] args) {
6 | BasketballPlayer kobe = new BasketballPlayer("Kobe Bryant", "Black Mamba", 1978, "Lakers", 83.7, 25.0, 1346);
7 | BasketballPlayer jordan = new BasketballPlayer("Michael Jordan", "MJ", 1963, "Chicago Bulls", 83.5, 30.1, 1072);
8 | BasketballPlayer magic = new BasketballPlayer("Earvin Johnson", "Magic", 1959, "Lakers", 84.8, 19.5, 906);
9 |
10 | BasketballPlayer[] basketballPlayers = new BasketballPlayer[3];
11 | basketballPlayers[0] = kobe;
12 | basketballPlayers[1] = jordan;
13 | basketballPlayers[2] = magic;
14 |
15 | for (BasketballPlayer basketballPlayer : basketballPlayers) {
16 | System.out.println("-------------------------------------");
17 | basketballPlayer.getBio();
18 | }
19 |
20 | FootballPlayer tom = new FootballPlayer("Tom Brady", "Tom Terrific", 1977, "Tampa Bay", 285, 9988, 6377);
21 | FootballPlayer ed = new FootballPlayer("Ed Brady", "Ed Terrific", 1979, "New England Patriots", 265, 8988, 4377);
22 |
23 | FootballPlayer[] footballPlayers = new FootballPlayer[2];
24 | footballPlayers[0] = tom;
25 | footballPlayers[1] = ed;
26 |
27 | for (FootballPlayer footballPlayer : footballPlayers) {
28 | System.out.println("-------------------------------------");
29 | footballPlayer.getBio();
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/athlete/BasketballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.athlete;
2 |
3 | import java.util.Random;
4 |
5 | public class BasketballPlayer extends Athlete{
6 |
7 | private double freeThrowPercentage;
8 | private double pointsPerGame;
9 |
10 | public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
11 | super(name, nickname, yearOfBorn, team, gamesPlayed);
12 | this.freeThrowPercentage = freeThrowPercentage;
13 | this.pointsPerGame = pointsPerGame;
14 | }
15 |
16 | public void freeThrow(){
17 | Random randomNumberGenerator = new Random();
18 | if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
19 | System.out.println(super.getName() + " failed to score free throw.");
20 | } else {
21 | System.out.println(super.getName() + " scored free throw.");
22 | }
23 | }
24 |
25 | @Override
26 | public void getBio() {
27 | super.getBio();
28 | System.out.println("Free throw percentage: " + freeThrowPercentage);
29 | System.out.println("Points per game: " + pointsPerGame);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/athlete/FootballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.athlete;
2 |
3 | public class FootballPlayer extends Athlete{
4 |
5 | private int completions;
6 | private int passingYards;
7 |
8 | public FootballPlayer(String name, String nickname, int yearOfBorn, String team, int gamesPlayed, int completions, int passingYards) {
9 | super(name, nickname, yearOfBorn, team, gamesPlayed);
10 | this.completions = completions;
11 | this.passingYards = passingYards;
12 | }
13 |
14 | @Override
15 | public void getBio() {
16 | super.getBio();
17 | System.out.println("Completions: " + completions);
18 | System.out.println("Passing yards: " + passingYards);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/car/CarsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.car;
2 |
3 | public class CarsApp {
4 |
5 | public static void main(String[] args) {
6 | DodgeChallenger redDodgeChallenger = new DodgeChallenger("red", (byte)3, (short)450, (short)717, (short)7700, 40000, 15000, true);
7 | redDodgeChallenger.getDescription();
8 | redDodgeChallenger.startTheEngine();
9 |
10 | System.out.println("----------------------------------------------");
11 | ToyotaSupra blackToyotaSupra = new ToyotaSupra("black", (byte)1, (short)225, (short)717, (short)3500, 40000, 15000, false);
12 | blackToyotaSupra.getDescription();
13 | blackToyotaSupra.startTheEngine();
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/car/DodgeChallenger.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.car;
2 |
3 | public class DodgeChallenger extends Car{
4 |
5 |
6 | public DodgeChallenger(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity,
7 | int price, int mileage, boolean isDamaged){
8 | super("Dodge Challenger", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
9 | }
10 |
11 | @Override
12 | public void startTheEngine() {
13 | System.out.println("A Dodge Challenger engine is started.");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/intermediate/inheritance/car/ToyotaSupra.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.inheritance.car;
2 |
3 | public class ToyotaSupra extends Car{
4 | public ToyotaSupra(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity, int price, int mileage, boolean isDamaged) {
5 | super("Toyota Supra", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
6 | }
7 |
8 | @Override
9 | public void startTheEngine() {
10 | System.out.println("A Toyota Supra Engine is started.");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/athlete/Athlete.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.athlete;
2 |
3 | public abstract class Athlete {
4 |
5 | private String name;
6 | private String nickname;
7 | private int yearOfBorn;
8 | private String team;
9 | private int numberOfCompetitions;
10 |
11 | public Athlete(String name, String nickname, int yearOfBorn, String team, int numberOfCompetitions) {
12 | this.name = name;
13 | this.nickname = nickname;
14 | this.yearOfBorn = yearOfBorn;
15 | this.team = team;
16 | this.numberOfCompetitions = numberOfCompetitions;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 | public void getBio() {
24 | System.out.println(name + " (" + nickname + ")");
25 | System.out.println("Born in " + yearOfBorn);
26 | System.out.println("Last team is " + team + " and took part in " + numberOfCompetitions + " competitions");
27 | }
28 |
29 | public void compete() {
30 | System.out.println(name + " took part in a competition.");
31 | numberOfCompetitions++;
32 | }
33 |
34 | public String getTeam() {
35 | return team;
36 | }
37 |
38 | public void setTeam(String team) {
39 | this.team = team;
40 | }
41 |
42 | public abstract String getBodyType();
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/athlete/BasketballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.athlete;
2 |
3 | import java.util.Random;
4 |
5 | public class BasketballPlayer extends Athlete {
6 |
7 | private double freeThrowPercentage;
8 | private double pointsPerGame;
9 |
10 | public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
11 | super(name, nickname, yearOfBorn, team, gamesPlayed);
12 | this.freeThrowPercentage = freeThrowPercentage;
13 | this.pointsPerGame = pointsPerGame;
14 | }
15 |
16 | public void freeThrow(){
17 | Random randomNumberGenerator = new Random();
18 | if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
19 | System.out.println(super.getName() + " failed to score free throw.");
20 | } else {
21 | System.out.println(super.getName() + " scored free throw.");
22 | }
23 | }
24 |
25 | @Override
26 | public void getBio() {
27 | super.getBio();
28 | System.out.println("Free throw percentage: " + freeThrowPercentage);
29 | System.out.println("Points per game: " + pointsPerGame);
30 | }
31 |
32 | @Override
33 | public void compete() {
34 | super.compete();
35 | freeThrow();
36 | }
37 |
38 | @Override
39 | public String getBodyType() {
40 | return "Tall and lean muscle.";
41 | }
42 |
43 | public void setFreeThrowPercentage(double freeThrowPercentage) {
44 | this.freeThrowPercentage = freeThrowPercentage;
45 | }
46 |
47 | public void setPointsPerGame(double pointsPerGame) {
48 | this.pointsPerGame = pointsPerGame;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/athlete/FootballPlayer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.athlete;
2 |
3 | public class FootballPlayer extends Athlete {
4 |
5 | private int completions;
6 | private int passingYards;
7 |
8 | public FootballPlayer(String name, String nickname, int yearOfBorn, String team, int gamesPlayed, int completions, int passingYards) {
9 | super(name, nickname, yearOfBorn, team, gamesPlayed);
10 | this.completions = completions;
11 | this.passingYards = passingYards;
12 | }
13 |
14 | @Override
15 | public void getBio() {
16 | super.getBio();
17 | System.out.println("Completions: " + completions);
18 | System.out.println("Passing yards: " + passingYards);
19 | }
20 |
21 | @Override
22 | public String getBodyType() {
23 | return "Big muscles and great endurance.";
24 | }
25 |
26 | public void increaseCompletions(int completions) {
27 | this.completions += completions;
28 | }
29 |
30 | public void increasePassingYards(int passingYards) {
31 | this.passingYards += passingYards;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/athlete/Swimmer.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.athlete;
2 |
3 | public class Swimmer extends Athlete implements Swimming {
4 |
5 | private int finaPoints;
6 |
7 | public Swimmer(String name, String nickname, int yearOfBorn, String team, int numberOfCompetitions, int finaPoints) {
8 | super(name, nickname, yearOfBorn, team, numberOfCompetitions);
9 | this.finaPoints = finaPoints;
10 | }
11 |
12 | @Override
13 | public String getBodyType() {
14 | return "Lean muscle, long torso and flexible ankles.";
15 | }
16 |
17 | @Override
18 | public void getBio() {
19 | super.getBio();
20 | System.out.println("FINA points: " + finaPoints);
21 | }
22 |
23 | @Override
24 | public void freestyle() {
25 | System.out.println("Swimming freestyle very fast.");
26 | }
27 |
28 | @Override
29 | public void freestyle(int distance) {
30 | System.out.println("Swimming " + distance + "m freestyle very fast.");
31 | }
32 |
33 | @Override
34 | public void compete() {
35 | super.compete();
36 | freestyle();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/athlete/Swimming.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.athlete;
2 |
3 | public interface Swimming {
4 | void freestyle();
5 | void freestyle(int distance);
6 | }
7 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/car/CarsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.car;
2 |
3 | public class CarsApp {
4 |
5 | public static void main(String[] args) {
6 | DodgeChallenger redDodgeChallenger = new DodgeChallenger("red", (byte)3, (short)450, (short)717, (short)7700, 40000, 15000, true);
7 | System.out.println(redDodgeChallenger.getCarName() + "'s price is $" + redDodgeChallenger.getPrice());
8 | redDodgeChallenger.setPrice(-35000);
9 | System.out.println(redDodgeChallenger.getCarName() + "'s new price is $" + redDodgeChallenger.getPrice());
10 | System.out.println("The car is in city mode.");
11 | redDodgeChallenger.startTheElectricEngine();
12 | System.out.println("The car has " + redDodgeChallenger.getMileage() + "miles");
13 | redDodgeChallenger.drive(140);
14 | System.out.println("After driving the car, it has " + redDodgeChallenger.getMileage() + "miles");
15 |
16 | System.out.println("----------------------------------------------");
17 | ToyotaSupra blackToyotaSupra = new ToyotaSupra("black", (byte)1, (short)225, (short)717, (short)3500, 40000, 15000, false);
18 | System.out.println(blackToyotaSupra.getCarName() + "'s price is $" + blackToyotaSupra.getPrice());
19 | blackToyotaSupra.setPrice(32000);
20 | System.out.println(blackToyotaSupra.getCarName() + "'s new price is $" + blackToyotaSupra.getPrice());
21 | blackToyotaSupra.startTheEngine();
22 | System.out.println("The car has " + blackToyotaSupra.getMileage() + "miles");
23 | blackToyotaSupra.drive(200);
24 | System.out.println("After driving the car, it has " + blackToyotaSupra.getMileage() + "miles");
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/car/DodgeChallenger.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.car;
2 |
3 | public class DodgeChallenger extends Car implements ElectricMode {
4 |
5 |
6 | public DodgeChallenger(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity,
7 | int price, int mileage, boolean isDamaged){
8 | super("Dodge Challenger", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
9 | }
10 |
11 | @Override
12 | public void startTheEngine() {
13 | System.out.println("A Dodge Challenger engine is started.");
14 | }
15 |
16 | @Override
17 | public void startTheElectricEngine() {
18 | System.out.println("Dodge Challenger starts its electric engine.");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/car/ElectricMode.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.car;
2 |
3 | public interface ElectricMode {
4 | void startTheElectricEngine();
5 | }
6 |
--------------------------------------------------------------------------------
/src/com/intermediate/polymorphism/car/ToyotaSupra.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.polymorphism.car;
2 |
3 | public class ToyotaSupra extends Car {
4 | public ToyotaSupra(String color, byte numberOfVehicleOwners, short power, short horsePower, short cubicCapacity, int price, int mileage, boolean isDamaged) {
5 | super("Toyota Supra", color, numberOfVehicleOwners, power, horsePower, cubicCapacity, price, mileage, isDamaged);
6 | }
7 |
8 | @Override
9 | public void startTheEngine() {
10 | System.out.println("A Toyota Supra Engine is started.");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/intermediate/statickeyword/CountriesApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.statickeyword;
2 |
3 | public class CountriesApp {
4 |
5 | public static void main(String[] args) {
6 | System.out.println("Number of countries: " + Country.getNumberOfCountries());
7 | Country brazil = new Country("Brazil", 210000000, "Brasilia");
8 | brazil.getDetails();
9 | Country germany = new Country("Germany", 83000000, "Berlin");
10 | germany.getDetails();
11 | Country japan = new Country("Japan", 12500000, "Tokyo");
12 | japan.getDetails();
13 | System.out.println("Number of countries: " + Country.getNumberOfCountries());
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/intermediate/statickeyword/Country.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.statickeyword;
2 |
3 | public class Country {
4 |
5 | private static int numberOfCountries;
6 | private final String NAME;
7 | private int population;
8 | private String capital;
9 |
10 | static {
11 | numberOfCountries = 5;
12 | }
13 |
14 | public Country(String name, int population, String capital) {
15 | NAME = name;
16 | this.population = population;
17 | this.capital = capital;
18 | numberOfCountries++;
19 | }
20 |
21 | public final void populationChange(int change){
22 | population += change;
23 | }
24 |
25 | public void getDetails() {
26 | System.out.println("Country name: " + NAME + " Population: " + population + " Capital: " + capital);
27 | }
28 |
29 | public static int getNumberOfCountries() {
30 | return numberOfCountries;
31 | }
32 |
33 | static {
34 | numberOfCountries = 0;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/intermediate/stringfunctions/StringFunctionsApp.java:
--------------------------------------------------------------------------------
1 | package com.intermediate.stringfunctions;
2 |
3 | import java.util.Scanner;
4 |
5 | public class StringFunctionsApp {
6 |
7 | public static void main(String[] args) {
8 | Scanner keyboardInput = new Scanner(System.in);
9 | String inputText = keyboardInput.nextLine();
10 |
11 | if ("Paris".equals(inputText)) {
12 | System.out.println("Paris was typed in.");
13 | } else {
14 | System.out.println("The text typed in is: " + inputText);
15 | }
16 |
17 | if (inputText.equalsIgnoreCase("Paris")) {
18 | System.out.println("Paris was typed in.");
19 | } else {
20 | System.out.println("The text typed in is: " + inputText);
21 | }
22 |
23 | if (inputText.contains("Par")) {
24 | System.out.println("The input text contains Par.");
25 | }
26 |
27 | if (inputText.isEmpty()) {
28 | System.out.println("The input text is empty.");
29 | }
30 |
31 | System.out.println("The input text's length is: " + inputText.length());
32 | System.out.println("The input text with uppercase: " + inputText.toUpperCase());
33 | System.out.println("The input text with lowercase: " + inputText.toLowerCase());
34 |
35 | if (inputText.startsWith("P") || inputText.endsWith("P")) {
36 | System.out.println("The input text starts or ends with a P letter.");
37 | }
38 |
39 | System.out.println("The replaced text: " + inputText.replace("N", "D"));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------