├── .gitignore ├── 01_metody └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── methods │ └── TemperatureCheck.java ├── 02_obiekty └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── objects │ ├── Cogwheel.java │ ├── Engine.java │ └── exercise │ ├── bird │ ├── Sparrow.java │ └── Stork.java │ └── fish │ ├── Carp.java │ └── Goldfish.java ├── 03_pierwszy_program └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── Main.java ├── 04_tablice └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── arrays │ ├── Arrays.java │ └── exercise │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise3.java │ └── Exercise4.java ├── 05_petle └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── loops │ ├── Thermometer.java │ └── exercise │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise3.java │ ├── Exercise4.java │ ├── Exercise5.java │ └── Exercise6.java ├── 06_typy_proste └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── primitivetypes │ ├── AverageTemperature.java │ ├── PrimitiveTypes.java │ └── exercise │ └── Excercise.java ├── 07_interfejsy └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── interfaces │ ├── BakingOven.java │ ├── BrokenClock.java │ ├── Clock.java │ ├── MicrowaveOven.java │ ├── Oven.java │ ├── RoastingOven.java │ ├── Thermometer.java │ ├── ZelmerMicrowaveOven.java │ ├── exercise │ ├── Addition.java │ ├── Computation.java │ ├── Main.java │ └── Multiplication.java │ └── inheritance │ ├── Cat.java │ ├── FatCat.java │ ├── Garfield.java │ └── LasagnaEater.java ├── 08_dziedziczenie └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── inheritance │ ├── bank │ ├── BankAccount.java │ ├── FraudTransfer.java │ └── Transfer.java │ ├── cars │ ├── Car.java │ ├── Engine.java │ ├── SUV.java │ ├── Truck.java │ └── Vehicle.java │ └── exercise │ ├── Animal.java │ ├── Fish.java │ ├── Goldfish.java │ ├── Human.java │ ├── Main.java │ └── Mammal.java ├── 09_wyjatki └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── exception │ ├── BasicExceptions.java │ ├── CheckedExceptions.java │ ├── ExceptionInheritance.java │ ├── FinallyExample.java │ ├── StackTraceExample.java │ └── exercise │ └── Exercise.java ├── 10_obiekty └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ ├── Null.java │ ├── ObjectFieldsChanging.java │ ├── ObjectVersusReference.java │ └── StringExample.java ├── 11_konwersja_rzutowanie └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ ├── ArithmeticConversion.java │ ├── AssignmentConversion.java │ ├── Boxing.java │ ├── NarrowingConversion.java │ ├── RuntimeType.java │ ├── WideningConversion.java │ └── zadanie │ ├── AsciiTable.java │ ├── Box.java │ ├── NumberMultiplier.java │ ├── PiMultiplier.java │ └── UnboxingExceptions.java ├── 12_dodatkowe_zadania └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ ├── arrays │ └── ArraysExcercises.java │ ├── interfaces │ ├── Female.java │ ├── Human.java │ ├── Male.java │ └── figures │ │ ├── Circle.java │ │ ├── Figure.java │ │ ├── Main.java │ │ ├── Rectangle.java │ │ └── Triangle.java │ ├── loops │ ├── ArrayFactory.java │ └── LoopsExcercises.java │ ├── methods │ └── MethodsExcercises.java │ ├── objects │ ├── Human.java │ ├── MyNumber.java │ └── Rectangle.java │ └── primitivetypes │ └── SimpleTypesExcercise.java ├── 13_typy_generyczne └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── generics │ ├── Apple.java │ ├── AppleBox.java │ ├── BoxOnSteroids.java │ ├── GenericMethod.java │ ├── Main.java │ ├── ObjectBox.java │ ├── Orange.java │ ├── OrangeBox.java │ ├── Pair.java │ ├── WildcardExamples.java │ ├── extendexample │ ├── BoxForFigures.java │ ├── Circle.java │ ├── Figure.java │ ├── Main.java │ ├── Rectangle.java │ ├── Square.java │ └── Triangle.java │ └── genericinteritance │ ├── FancyBox.java │ ├── Main.java │ └── StandardBox.java ├── 14_porownywanie_obiektow └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── equality │ ├── Chair.java │ ├── ComparisionExamples.java │ └── exercise │ └── Human.java ├── 15_kolekcje └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ ├── IterationExample.java │ ├── ListExample.java │ ├── MapExample.java │ ├── SetExample.java │ └── exercise │ ├── Exercise1.java │ └── Exercise2.java ├── 16_operacje_na_plikach └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── files │ ├── BinaryFileManipulation.java │ ├── TextFileManipulation.java │ └── exercise │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise3.java │ └── Exercise4.java ├── 17_manager_kontekstu └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── context │ ├── MyContextManager.java │ ├── MyContextManagerMain.java │ ├── TriWithResourcesExample.java │ └── exercise │ └── HtmlTag.java ├── 18_serializacja └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── serialization │ ├── Car.java │ ├── CustomProtocolSerialization.java │ ├── CustomSerialization.java │ ├── DieselEngine.java │ ├── Engine.java │ ├── Human.java │ ├── Main.java │ ├── StaticSerialization.java │ ├── Tyre.java │ └── exercise │ ├── Human.java │ └── NamesDatabase.java ├── 19_typ_wyliczeniowy └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── enums │ ├── enumclass │ └── TshirtSize.java │ ├── exercise │ ├── Computation.java │ ├── EyeColour.java │ ├── HairColour.java │ └── Human.java │ ├── simple │ ├── Tshirt.java │ └── TshirtSize.java │ └── withinlinemethods │ └── Formatter.java ├── 20_adnotacje └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── annotations │ ├── AnnotationWithDefaultValues.java │ ├── AnnotationsForCompiler.java │ ├── EqualsOverride.java │ ├── Main.java │ ├── SampleFieldAnnotation.java │ └── exercise │ ├── AnnotationProcessor.java │ └── MyDocumentation.java ├── 21_klasy_wewnetrzne └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── inner │ ├── AnonymousCheating.java │ ├── AnonymousClasses.java │ ├── Main.java │ ├── OuterClass.java │ ├── OuterClass2.java │ ├── VariablesUsedInInnerClasses.java │ └── exercise │ ├── HansRobot.java │ └── SortingExample.java ├── 22_testy_jednostkowe ├── build.gradle └── src │ ├── main │ └── java │ │ └── pl │ │ └── samouczekprogramisty │ │ └── kursjava │ │ ├── number │ │ └── Range.java │ │ └── shop │ │ └── exercise │ │ ├── Basket.java │ │ └── Item.java │ └── test │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ ├── number │ ├── RangeTest.java │ ├── RangeWithoutSetup.java │ └── TestLifecycle.java │ └── shop │ └── exercise │ ├── BasketTest.java │ └── ItemTest.java ├── 23_wyrazenia_regularne ├── build.gradle └── src │ ├── main │ └── java │ │ └── pl │ │ └── samouczekprogramisty │ │ └── kursjava │ │ └── regexp │ │ └── SimpleNameRegexp.java │ └── test │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── regexp │ ├── RegexpTest.java │ └── exercise │ └── ExerciseTest.java ├── 24_wyrazenia_regularne ├── build.gradle └── src │ └── test │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── regexp │ └── RegexpTest.java ├── 25_linia_polecen ├── build.gradle └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── commandline │ ├── CheckName.java │ └── DisplayName.java ├── 26_lancuchy_znakow ├── build.gradle └── src │ ├── main │ └── java │ │ └── pl │ │ └── samouczekprogramisty │ │ └── kursjava │ │ └── strings │ │ └── StringConcatenation.java │ └── test │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── strings │ ├── StringCacheTest.class │ └── StringCacheTest.java ├── 27_lancuchy_znakow_formatowanie └── src │ └── main │ ├── java │ └── pl │ │ └── samouczekprogramisty │ │ └── kursjava │ │ └── strings │ │ └── formatting │ │ ├── ExerciseSolution.java │ │ └── StringFormatting.java │ └── resources │ └── test.csv ├── 28_wyrazenia_lambda └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── lambdaexpressions │ ├── ArticleExamples.java │ ├── Checker.java │ ├── SideEffectMethod.java │ ├── Solution.java │ └── exercise │ ├── Human.java │ ├── HumanCreation.java │ ├── MethodReferenceExercise.java │ └── StringSorting.java ├── 29_modyfikatory_dostepu └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── accessmodifiers │ ├── encapsulated │ └── EncapsulatedVisitCounter.java │ ├── exercise │ └── bank │ │ ├── Account.java │ │ ├── Bank.java │ │ ├── BankAccount.java │ │ └── BankTransfer.java │ ├── inheritance │ ├── Oak.java │ └── Tree.java │ ├── missing_keyword │ ├── Car.java │ └── FuelStation.java │ ├── protected_keyword │ ├── Pen.java │ ├── PenOwner.java │ └── different_package │ │ └── BallPen.java │ ├── public_keyword │ ├── MaliciousUser.java │ └── PublicVisitCounter.java │ └── reflection │ ├── BankAccount.java │ └── Thief.java ├── 30_strumienie └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── streams │ ├── BoardGame.java │ ├── LazyStreams.java │ ├── StreamCreation.java │ ├── StreamsGoodPractices.java │ ├── exercise │ ├── ListFlatting.java │ ├── LoopTooStream.java │ └── MinWIthReduce.java │ └── requirements │ ├── InterferingOperation.java │ └── StatefullOperation.java ├── 31_testy_jednostkowe_junit5 ├── build.gradle └── src │ ├── main │ └── java │ │ └── pl │ │ └── samouczekprogramisty │ │ └── kursjava │ │ └── junit5 │ │ ├── exchange │ │ ├── Currency.java │ │ ├── ExchangePoint.java │ │ ├── FixedRatesProvider.java │ │ ├── FixerRatesProvider.java │ │ └── RatesProvider.java │ │ └── unit │ │ ├── Kilogram.java │ │ ├── Pound.java │ │ └── WeightUnit.java │ └── test │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── junit5 │ ├── exchange │ ├── ExchangePointTest.java │ └── FixedRatesProviderTest.java │ └── unit │ ├── SamouczekBefore.java │ ├── SamouczekExtension.java │ └── UnitConverterTest.java ├── 32_format_json ├── build.gradle └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── json │ ├── AnnotationExamples.java │ ├── JSONBExamples.java │ ├── JSONPExamples.java │ ├── Newspaper.java │ └── WithoutAnnotationExamples.java ├── 33_testy_z_mock_stub_spy ├── build.gradle └── src │ ├── main │ └── java │ │ └── pl │ │ └── samouczekprogramisty │ │ └── kursjava │ │ └── mock │ │ ├── Airline.java │ │ ├── Flight.java │ │ ├── FlightException.java │ │ └── FlightScanner.java │ └── test │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── mock │ ├── FlightScannerTestMockito.java │ ├── FlightScannerTestMocks.java │ ├── FlightScannerTestStubs.java │ └── MockitoExamplesTest.java ├── 34_watki └── src │ └── main │ └── java │ └── pl │ └── samouczekprogramisty │ └── kursjava │ └── treads │ ├── ConsumerProducer.java │ ├── Creation.java │ ├── FirstThread.java │ ├── NaiveConsumerProducer.java │ ├── RaceCondition.java │ ├── VolatileExample.java │ └── exercise │ ├── ReverseNumbers.java │ └── ThreadedHelloWorld.java ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | out 4 | build 5 | .gradle 6 | *.class 7 | *.jar 8 | -------------------------------------------------------------------------------- /01_metody/src/main/java/pl/samouczekprogramisty/kursjava/methods/TemperatureCheck.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.methods; 2 | 3 | public class TemperatureCheck { 4 | public static void main(String... args) { 5 | // this is not the best type to store temperature, stay tuned for better one ;) 6 | int positiveTemperature = 10; 7 | int negativeTemperature = -10; 8 | 9 | isTemperaturePositive(positiveTemperature); 10 | isTemperaturePositive(negativeTemperature); 11 | } 12 | 13 | private static boolean isTemperaturePositive(int temperature) { 14 | boolean isPositive = temperature > 0; 15 | 16 | if (isPositive) { 17 | System.out.println("Temperatura " + temperature + " jest dodatnia."); 18 | } 19 | else { 20 | System.out.println("Temperatura " + temperature + " nie jest dodatnia."); 21 | } 22 | 23 | return isPositive; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /02_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/objects/Cogwheel.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects; 2 | 3 | 4 | public class Cogwheel { 5 | 6 | 7 | private int size; 8 | private int numberOfCogs; 9 | 10 | public Cogwheel(int size) { 11 | this.size = size; 12 | } 13 | 14 | 15 | } 16 | 17 | -------------------------------------------------------------------------------- /02_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/objects/Engine.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects; 2 | 3 | public class Engine { 4 | 5 | private boolean started; 6 | private Cogwheel cogwheel; 7 | 8 | public Engine(Cogwheel cogwheel) { 9 | this.cogwheel = cogwheel; 10 | } 11 | 12 | public void start() { 13 | started = initiateStartingSequence(); 14 | } 15 | 16 | private boolean initiateStartingSequence() { 17 | // comment 18 | return true; 19 | } 20 | 21 | public void stop() { 22 | started = false; 23 | } 24 | 25 | public boolean isStarted() { 26 | return started; 27 | } 28 | 29 | public void setStarted(boolean started) { 30 | this.started = started; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /02_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/objects/exercise/bird/Sparrow.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects.exercise.bird; 2 | 3 | 4 | public class Sparrow { 5 | private String featherColour; 6 | 7 | public String getFeatherColour() { 8 | return featherColour; 9 | } 10 | 11 | public void setFeatherColour(String featherColour) { 12 | this.featherColour = featherColour; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /02_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/objects/exercise/bird/Stork.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects.exercise.bird; 2 | 3 | public class Stork { 4 | private int age; 5 | 6 | public int getAge() { 7 | return age; 8 | } 9 | 10 | public void setAge(int age) { 11 | this.age = age; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /02_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/objects/exercise/fish/Carp.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects.exercise.fish; 2 | 3 | public class Carp { 4 | private double swimmingSpeed; 5 | 6 | public double getSwimmingSpeed() { 7 | return swimmingSpeed; 8 | } 9 | 10 | public void setSwimmingSpeed(double swimmingSpeed) { 11 | this.swimmingSpeed = swimmingSpeed; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /02_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/objects/exercise/fish/Goldfish.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects.exercise.fish; 2 | 3 | public class Goldfish { 4 | private float weight; 5 | 6 | public float getWeight() { 7 | return weight; 8 | } 9 | 10 | public void setWeight(float weight) { 11 | this.weight = weight; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /03_pierwszy_program/src/main/java/pl/samouczekprogramisty/kursjava/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | /** 4 | * Created by mapi on 08.11.15. 5 | */ 6 | public class Main { 7 | public static void main(String[] args) { 8 | String message = "To jest mój pierwszy łańcuch znaków! Potocznie \"string\"."; 9 | System.out.println(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /04_tablice/src/main/java/pl/samouczekprogramisty/kursjava/arrays/Arrays.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.arrays; 2 | 3 | /** 4 | * Created by mapi on 09.11.15. 5 | */ 6 | public class Arrays { 7 | public static void main(String[] args) { 8 | String[] daysOfWeek = new String[7]; 9 | daysOfWeek[0] = "poniedziałek"; 10 | daysOfWeek[1] = "wtorek"; 11 | daysOfWeek[2] = "środa"; 12 | daysOfWeek[3] = "czwartek"; 13 | daysOfWeek[4] = "piątek"; 14 | daysOfWeek[5] = "sobota"; 15 | daysOfWeek[6] = "niedziela"; 16 | System.out.println(daysOfWeek[2]); 17 | System.out.println(daysOfWeek.length); 18 | 19 | String[] wintersMonths = new String[] {"grudzień", "styczeń", "luty"}; 20 | System.out.println(wintersMonths[2]); 21 | 22 | int[][] ticTacToeBoard = new int[3][]; 23 | ticTacToeBoard[0] = new int[3]; 24 | ticTacToeBoard[1] = new int[3]; 25 | ticTacToeBoard[2] = new int[3]; 26 | 27 | int[][] ticTacToeBoard2 = new int[3][3]; 28 | 29 | Object[] x = new Object[123]; 30 | x[0] = ""; 31 | x[1] = 1; 32 | x[2] = 1.23; 33 | } 34 | 35 | public void methodVarArgs1(int ... days) { 36 | } 37 | 38 | public void methodVarArgs2(boolean flag, int ... days) { 39 | } 40 | 41 | public void methodVarArgs3(int flag, int ... days) { 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /04_tablice/src/main/java/pl/samouczekprogramisty/kursjava/arrays/exercise/Exercise1.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.arrays.exercise; 2 | 3 | 4 | public class Exercise1 { 5 | public int sum(int[] numbers) { 6 | return numbers[0] + numbers[1]; 7 | } 8 | 9 | public static void main(String[] args) { 10 | Exercise1 exercise = new Exercise1(); 11 | int[] numbers = {3, 4}; 12 | System.out.println(exercise.sum(numbers)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /04_tablice/src/main/java/pl/samouczekprogramisty/kursjava/arrays/exercise/Exercise2.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.arrays.exercise; 2 | 3 | public class Exercise2 { 4 | public int biggest(int[] numbers) { 5 | int biggest = numbers[0]; 6 | if (numbers[1] > biggest) { 7 | biggest = numbers[1]; 8 | } 9 | if (numbers[2] > biggest) { 10 | biggest = numbers[2]; 11 | } 12 | return biggest; 13 | } 14 | 15 | public int biggestWithoutIf(int[] numbers) { 16 | return Math.max(numbers[0], Math.max(numbers[1], numbers[2])); 17 | } 18 | 19 | public static void main(String[] args) { 20 | Exercise2 exercise = new Exercise2(); 21 | int[] numbers = new int[]{1, 3, -5}; 22 | System.out.println(exercise.biggest(numbers)); 23 | System.out.println(exercise.biggestWithoutIf(numbers)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /04_tablice/src/main/java/pl/samouczekprogramisty/kursjava/arrays/exercise/Exercise3.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.arrays.exercise; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Exercise3 { 6 | private Integer[][] board; 7 | 8 | public Exercise3(Integer[][] board) { 9 | this.board = board; 10 | } 11 | 12 | public static Exercise3 sampleBoard() { 13 | Integer[][] board = new Integer[][] { 14 | new Integer[] {2, null, null, 6, null, 7, 5, null, null}, 15 | new Integer[] {null, null, null, null, null, null, null, 9, 6}, 16 | new Integer[] {6, null, 7, null, null, 1, 3, null, null}, 17 | 18 | new Integer[] {null, 5, null, 7, 3, 2, null, null, null}, 19 | new Integer[] {null, 7, null, null, null, null, null, 2, null}, 20 | new Integer[] {null, null, null, 1, 8, 9, null, 7, null}, 21 | 22 | new Integer[] {null, null, 3, 5, null, null, 6, null, 4}, 23 | new Integer[] {8, 4, null, null, null, null, null, null, null}, 24 | new Integer[] {null, null, 5, 2, null, 6, null, null, 8} 25 | }; 26 | return new Exercise3(board); 27 | } 28 | 29 | public static void main(String[] args) { 30 | Exercise3 sampleBoard = sampleBoard(); 31 | System.out.println(Arrays.deepToString(sampleBoard.board)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /04_tablice/src/main/java/pl/samouczekprogramisty/kursjava/arrays/exercise/Exercise4.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.arrays.exercise; 2 | 3 | 4 | import java.util.Arrays; 5 | 6 | public class Exercise4 { 7 | // Sa lepsze sposoby, jednak na tym etapie taki sposob jest OK :) 8 | // Jesli jestes ciekawy jak zrobic to lepiej poczytaj o typie wyliczeniowym. 9 | // http://www.samouczekprogramisty.pl/typ-wyliczeniowy-w-jezyku-java/ 10 | public static final int EMPTY = 0; 11 | public static final int B_PAWN = 1; 12 | public static final int B_ROOK = 2; 13 | public static final int B_BISHOP = 3; 14 | public static final int B_KNIGHT = 4; 15 | public static final int B_QUEEN = 5; 16 | public static final int B_KING = 6; 17 | 18 | public static final int W_PAWN = 7; 19 | public static final int W_ROOK = 8; 20 | public static final int W_BISHOP = 9; 21 | public static final int W_KNIGHT = 10; 22 | public static final int W_QUEEN = 11; 23 | public static final int W_KING = 12; 24 | 25 | private int[][] board = new int[8][8]; 26 | 27 | public static int[][] game5FinalState() { 28 | return new int[][] { 29 | new int[] {EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY}, 30 | new int[] {B_PAWN, B_PAWN, EMPTY, EMPTY, EMPTY, EMPTY, W_PAWN, EMPTY}, 31 | new int[] {EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY}, 32 | new int[] {EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY}, 33 | new int[] {EMPTY, B_KING, B_PAWN, EMPTY, EMPTY, W_KNIGHT, EMPTY, EMPTY}, 34 | new int[] {EMPTY, B_KNIGHT, EMPTY, EMPTY, W_ROOK, EMPTY, W_PAWN, EMPTY}, 35 | new int[] {EMPTY, EMPTY, EMPTY, B_ROOK, EMPTY, EMPTY, EMPTY, EMPTY}, 36 | new int[] {EMPTY, W_KING, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY}, 37 | }; 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[][] finalState = game5FinalState(); 42 | System.out.println(Arrays.toString(finalState)); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /05_petle/src/main/java/pl/samouczekprogramisty/kursjava/loops/exercise/Exercise1.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops.exercise; 2 | 3 | public class Exercise1 { 4 | public static void main(String[] args) { 5 | for(int number = 20; number > 9; number--) { 6 | System.out.println(number); 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /05_petle/src/main/java/pl/samouczekprogramisty/kursjava/loops/exercise/Exercise2.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops.exercise; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | int number = 10; 6 | while(number < 21) { 7 | System.out.println(number); 8 | number++; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /05_petle/src/main/java/pl/samouczekprogramisty/kursjava/loops/exercise/Exercise3.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops.exercise; 2 | 3 | public class Exercise3 { 4 | public static void main(String[] args) { 5 | for(int number = -10; number <= 40; number++) { 6 | if (number % 2 != 0) { 7 | System.out.println(number); 8 | } 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /05_petle/src/main/java/pl/samouczekprogramisty/kursjava/loops/exercise/Exercise4.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops.exercise; 2 | 3 | public class Exercise4 { 4 | public static void main(String[] args) { 5 | int oddNumber = -9; 6 | while(oddNumber < 41) { 7 | System.out.println(oddNumber); 8 | oddNumber += 2; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /05_petle/src/main/java/pl/samouczekprogramisty/kursjava/loops/exercise/Exercise5.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops.exercise; 2 | 3 | public class Exercise5 { 4 | 5 | public static void main(String[] args) { 6 | int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7}; 7 | System.out.println(sumArray(numbers)); 8 | } 9 | 10 | private static int sumArray(int[] numbers) { 11 | int sum = 0; 12 | for (int number : numbers) { 13 | sum += number; 14 | } 15 | return sum; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /05_petle/src/main/java/pl/samouczekprogramisty/kursjava/loops/exercise/Exercise6.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops.exercise; 2 | 3 | public class Exercise6 { 4 | 5 | public static void main(String[] args) { 6 | int[][] numbers = new int[][] {new int[] {1, 2}, new int[] {3, 4}, new int[] {5, 6, 7}}; 7 | System.out.println(sumArray(numbers)); 8 | } 9 | 10 | private static int sumArray(int[][] numbers) { 11 | int sum = 0; 12 | for (int[] otherNumbers : numbers) { 13 | for (int number : otherNumbers) { 14 | sum += number; 15 | } 16 | } 17 | return sum; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /06_typy_proste/src/main/java/pl/samouczekprogramisty/kursjava/primitivetypes/AverageTemperature.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.primitivetypes; 2 | 3 | import java.util.Scanner; 4 | 5 | 6 | public class AverageTemperature { 7 | public static void main(String[] args) { 8 | double[] temperature = new double[7]; 9 | Scanner inputScanner = new Scanner(System.in); 10 | 11 | for(int i = 0; i < temperature.length; i++) { 12 | System.out.println("Wprowadź liczbę " + i); 13 | temperature[i] = inputScanner.nextDouble(); 14 | } 15 | 16 | double summarizedTemp = 0; 17 | for (double temp : temperature) { 18 | summarizedTemp += temp; 19 | } 20 | 21 | int numberOfClasses = 3; 22 | int numberOfNotes = 4; 23 | for (int classIndex = 0; classIndex < numberOfClasses; numberOfClasses++) { 24 | for (int noteIndex = 0; noteIndex < numberOfNotes; noteIndex++) { 25 | 26 | } 27 | } 28 | 29 | System.out.println("Średnia temperatura wynosi " + (summarizedTemp / temperature.length)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /06_typy_proste/src/main/java/pl/samouczekprogramisty/kursjava/primitivetypes/PrimitiveTypes.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.primitivetypes; 2 | 3 | 4 | public class PrimitiveTypes { 5 | public static void main(String[] args) { 6 | byte b1 = 10; 7 | Byte b2 = Byte.valueOf((byte) 10); 8 | Byte b3 = 10; 9 | 10 | short s1 = 10; 11 | Short s2 = Short.valueOf((short) 10); 12 | Short s3 = 10; 13 | 14 | int i1 = 10; 15 | Integer i2 = Integer.valueOf(10); 16 | Integer i3 = 10; 17 | 18 | long l1 = 10L; 19 | Long l2 = Long.valueOf(10L); 20 | Long l3 = 10L; 21 | long l4 = l2; 22 | 23 | boolean bo1 = true; 24 | Boolean bo2 = Boolean.valueOf(true); 25 | Boolean bo3 = true; 26 | 27 | char c1 = 'c'; 28 | Character c2 = Character.valueOf('c'); 29 | Character c3 = 'c'; 30 | 31 | float f1 = 1.2F; 32 | Float f2 = Float.valueOf(1.2F); 33 | Float f3 = 1.2F; 34 | 35 | double d1 = 1.2; 36 | Double d2 = Double.valueOf(1.2); 37 | Double d3 = 1.2; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /06_typy_proste/src/main/java/pl/samouczekprogramisty/kursjava/primitivetypes/exercise/Excercise.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.primitivetypes.exercise; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Excercise { 6 | 7 | private int[][] notes; 8 | 9 | public Excercise(int numberOfClasses, int numberOfNotes) { 10 | notes = new int[numberOfClasses][numberOfNotes]; 11 | } 12 | 13 | public void getNotesFromUser() { 14 | Scanner scanner = new Scanner(System.in); 15 | for (int classIndex = 0; classIndex < notes.length; classIndex++) { 16 | for (int noteIndex = 0; noteIndex < notes[classIndex].length; noteIndex++) { 17 | System.out.println("Podaj ocenę numer " + (noteIndex + 1) + " dla przedmiotu numer " + (classIndex + 1) + ": "); 18 | notes[classIndex][noteIndex] = scanner.nextInt(); 19 | } 20 | } 21 | } 22 | 23 | public void printAverate() { 24 | float totalAverage = 0; 25 | for (int classIndex = 0; classIndex < notes.length; classIndex++) { 26 | float classAverage = 0; 27 | for (int note : notes[classIndex]) { 28 | classAverage += note; 29 | } 30 | classAverage /= notes[classIndex].length; 31 | System.out.println("Średnia dla przedmiotu numer " + (classIndex + 1) + " wynosi: " + classAverage); 32 | totalAverage += classAverage; 33 | } 34 | totalAverage /= notes.length; 35 | System.out.println("Średnia dla wszystkich przedmiotów wynosi: " + totalAverage); 36 | } 37 | 38 | public static void main(String[] args) { 39 | int numberOfClasses = 3; 40 | int numberOfNotes = 4; 41 | Excercise excercise = new Excercise(numberOfClasses, numberOfNotes); 42 | excercise.getNotesFromUser(); 43 | excercise.printAverate(); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/BakingOven.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public interface BakingOven { 4 | void bakeCookies(); 5 | void bakeBread(); 6 | } 7 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/BrokenClock.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | import java.io.Serializable; 4 | import java.time.LocalDateTime; 5 | 6 | public class BrokenClock implements Clock, Serializable { 7 | @Override 8 | public long secondsElapsedSince(LocalDateTime date) { 9 | return 300; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/Clock.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public interface Clock { 6 | long secondsElapsedSince(LocalDateTime date); 7 | } 8 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/MicrowaveOven.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | import java.time.Duration; 4 | 5 | public interface MicrowaveOven { 6 | 7 | void start(); 8 | 9 | void setDuration(int durationInSeconds); 10 | 11 | boolean isFinished(); 12 | 13 | void setPower(int power); 14 | 15 | default String getName() { 16 | return "MicrovaweOwen"; 17 | } 18 | 19 | default Duration getRecommendedDefrostTime(double foodWeightInGrams) { 20 | double frostRate = 0.8; 21 | int power = 300; 22 | return getRecommendedTime(power, frostRate, foodWeightInGrams); 23 | } 24 | 25 | default Duration getRecommendedWarmingUpTime(double foodWeightInGrams) { 26 | double frostRate = 0.2; 27 | int power = 700; 28 | return getRecommendedTime(power, frostRate, foodWeightInGrams); 29 | } 30 | 31 | private Duration getRecommendedTime(int power, double frostRate, double foodWeightInGrams) { 32 | double durationInMinutes = foodWeightInGrams / ((1 - frostRate) * power); 33 | long durationInSeconds = (long) (durationInMinutes * 60); 34 | return Duration.ofSeconds(durationInSeconds); 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/Oven.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public class Oven implements BakingOven, RoastingOven { 4 | 5 | private int time; 6 | private int temperature; 7 | 8 | @Override 9 | public void bakeBread() { 10 | temperature = 200; 11 | time = 120; 12 | turnOn(); 13 | } 14 | 15 | @Override 16 | public void bakeCookies() { 17 | temperature = 180; 18 | time = 90; 19 | turnOn(); 20 | } 21 | 22 | @Override 23 | public void roastChicken() { 24 | temperature = 130; 25 | time = 240; 26 | turnOn(); 27 | } 28 | 29 | private void turnOn() { 30 | System.out.println(String.format("Start. Heat up to %s and work for %d minutes.", temperature, time)); 31 | } 32 | 33 | public static void main(String[] args) { 34 | Oven oven = new Oven(); 35 | BakingOven bakingOven = oven; 36 | RoastingOven roastingOven = oven; 37 | 38 | bakingOven.bakeBread(); 39 | bakingOven.bakeCookies(); 40 | roastingOven.roastChicken(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/RoastingOven.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public interface RoastingOven { 4 | void roastChicken(); 5 | } 6 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/Thermometer.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public interface Thermometer { 4 | double getCurrentTemperatureFor(String city); 5 | } 6 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/ZelmerMicrowaveOven.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | 7 | public class ZelmerMicrowaveOven implements MicrowaveOven { 8 | 9 | private int durationInSeconds = 90; 10 | private int power = 600; 11 | private LocalDateTime start = null; 12 | 13 | private Clock clock; 14 | 15 | public ZelmerMicrowaveOven(Clock clock) { 16 | this.clock = clock; 17 | } 18 | 19 | @Override 20 | public void start() { 21 | start = LocalDateTime.now(); 22 | } 23 | 24 | @Override 25 | public String getName() { 26 | return MicrowaveOven.super.getName(); 27 | } 28 | 29 | @Override 30 | public void setDuration(int durationInSeconds) { 31 | this.durationInSeconds = durationInSeconds; 32 | } 33 | 34 | @Override 35 | public void setPower(int power) { 36 | this.power = power; 37 | } 38 | 39 | @Override 40 | public boolean isFinished() { 41 | if (start == null) { 42 | return false; 43 | } 44 | return clock.secondsElapsedSince(start) >= durationInSeconds; 45 | } 46 | 47 | public static void main(String[] args) { 48 | Clock clock = new BrokenClock(); 49 | MicrowaveOven oven = new ZelmerMicrowaveOven(clock); 50 | System.out.println(oven.isFinished()); 51 | oven.start(); 52 | System.out.println(oven.isFinished()); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/exercise/Addition.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.exercise; 2 | 3 | public class Addition implements Computation { 4 | @Override 5 | public double compute(double arg1, double arg2) { 6 | return arg1 + arg2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/exercise/Computation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.exercise; 2 | 3 | /** 4 | * Created by mapi on 15.12.15. 5 | */ 6 | public interface Computation { 7 | double compute(double arg1, double arg2); 8 | } 9 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/exercise/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.exercise; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | 7 | private Scanner scanner = new Scanner(System.in); 8 | 9 | public static void main(String[] args) { 10 | Main main = new Main(); 11 | Computation computation; 12 | 13 | if (main.shouldMultiply()) { 14 | computation = new Multiplication(); 15 | } 16 | else { 17 | computation = new Addition(); 18 | } 19 | 20 | double argument1 = main.getArgument(); 21 | double argument2 = main.getArgument(); 22 | 23 | double result = computation.compute(argument1, argument2); 24 | System.out.println("Wynik: " + result); 25 | } 26 | 27 | private boolean shouldMultiply() { 28 | System.out.println("Jaka operacje chcesz wykonac? Napisz M jesli ma to byc mnozenie i nacisnij . Mazdy inny wybor oznacza dodawanie."); 29 | return scanner.next().equals("M"); 30 | } 31 | 32 | private double getArgument() { 33 | System.out.print("Podaj liczbe: "); 34 | return scanner.nextDouble(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/exercise/Multiplication.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.exercise; 2 | 3 | public class Multiplication implements Computation { 4 | @Override 5 | public double compute(double arg1, double arg2) { 6 | return arg1 * arg2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/inheritance/Cat.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.inheritance; 2 | 3 | /** 4 | * Created by mapi on 15.12.15. 5 | */ 6 | public interface Cat { 7 | String getName(); 8 | } 9 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/inheritance/FatCat.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.inheritance; 2 | 3 | /** 4 | * Created by mapi on 15.12.15. 5 | */ 6 | public interface FatCat extends Cat, LasagnaEater { 7 | double getWeight(); 8 | } -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/inheritance/Garfield.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.inheritance; 2 | 3 | /** 4 | * Created by mapi on 15.12.15. 5 | */ 6 | public class Garfield implements FatCat { 7 | 8 | @Override 9 | public double getWeight() { 10 | return 0; 11 | } 12 | 13 | @Override 14 | public String getName() { 15 | return null; 16 | } 17 | 18 | @Override 19 | public String getLasagnaRecipe() { 20 | return null; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Cat cat = new Garfield(); 25 | LasagnaEater lasagnaEater = new Garfield(); 26 | FatCat fatCat = new Garfield(); 27 | Garfield garfield = new Garfield(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /07_interfejsy/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/inheritance/LasagnaEater.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.inheritance; 2 | 3 | /** 4 | * Created by mapi on 15.12.15. 5 | */ 6 | public interface LasagnaEater { 7 | int size = 123; 8 | 9 | String getLasagnaRecipe(); 10 | } 11 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/bank/BankAccount.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.bank; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public interface BankAccount { 6 | void deposit(BigDecimal amount); 7 | void withdraw(BigDecimal amount); 8 | } 9 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/bank/FraudTransfer.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.bank; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class FraudTransfer extends Transfer{ 6 | public void transferMoney(BankAccount source, BankAccount destination, BigDecimal amount) { 7 | destination.deposit(amount); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/bank/Transfer.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.bank; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Transfer { 6 | public void transferMoney(BankAccount source, BankAccount destination, BigDecimal amount) { 7 | source.withdraw(amount); 8 | destination.deposit(amount); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/cars/Car.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.cars; 2 | 3 | 4 | public class Car extends Vehicle { 5 | private static final int NUMBER_OF_WHEELS = 4; 6 | protected int canUse = 10; 7 | private int cantUse = 11; 8 | 9 | public Car(Engine engine) { 10 | super(engine, NUMBER_OF_WHEELS); 11 | } 12 | 13 | public final void startEngine() { 14 | super.startEngine(); 15 | System.out.println("Force driver to fasten seat belts."); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/cars/Engine.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.cars; 2 | 3 | /** 4 | * Created by mapi on 24.01.16. 5 | */ 6 | public interface Engine { 7 | } 8 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/cars/SUV.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.cars; 2 | 3 | class X { 4 | 5 | } 6 | public final class SUV extends Car { 7 | public SUV(Engine engine) { 8 | super(engine); 9 | } 10 | 11 | public static void main(String[] args) { 12 | System.out.println(new X()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/cars/Truck.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.cars; 2 | 3 | public class Truck extends Vehicle { 4 | private static final int NUMBER_OF_WHEELS = 12; 5 | 6 | public Truck(Engine engine) { 7 | super(engine, NUMBER_OF_WHEELS); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/cars/Vehicle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.cars; 2 | 3 | 4 | public abstract class Vehicle { 5 | private int numberOfWheels; 6 | private Engine engine; 7 | 8 | public Vehicle(Engine engine, int numberOfWheels) { 9 | this.engine = engine; 10 | this.numberOfWheels = numberOfWheels; 11 | } 12 | 13 | public int getNumberOfWheels() { 14 | return numberOfWheels; 15 | } 16 | 17 | public void startEngine() { 18 | System.out.println("Engine starts. Brum brum brum."); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/exercise/Animal.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.exercise; 2 | 3 | public abstract class Animal { 4 | } 5 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/exercise/Fish.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.exercise; 2 | 3 | public abstract class Fish extends Animal { 4 | } 5 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/exercise/Goldfish.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.exercise; 2 | 3 | public class Goldfish extends Fish { 4 | @Override 5 | public String toString() { 6 | return "I'm a goldfish. I like to swim :)."; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/exercise/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.exercise; 2 | 3 | public class Human extends Mammal { 4 | @Override 5 | public String toString() { 6 | return "I'm a human :)."; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/exercise/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.exercise; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Animal human = new Human(); 6 | Animal fish = new Goldfish(); 7 | 8 | System.out.println(human); 9 | System.out.println(fish); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /08_dziedziczenie/src/main/java/pl/samouczekprogramisty/kursjava/inheritance/exercise/Mammal.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inheritance.exercise; 2 | 3 | public abstract class Mammal extends Animal { 4 | } 5 | -------------------------------------------------------------------------------- /09_wyjatki/src/main/java/pl/samouczekprogramisty/kursjava/exception/BasicExceptions.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exception; 2 | 3 | public class BasicExceptions { 4 | public int getNumberOfSeconds(int hour) { 5 | if (hour < 0) { 6 | throw new IllegalArgumentException("Hour must be >= 0: " + hour); 7 | } 8 | return hour * 60 * 60; 9 | } 10 | 11 | public static void main(String[] args) { 12 | System.out.println(Math.sqrt(-1)); 13 | BasicExceptions instance = new BasicExceptions(); 14 | int argument = -3; 15 | int numberOfSeconds = 0; 16 | try { 17 | numberOfSeconds = instance.getNumberOfSeconds(argument); 18 | } 19 | catch (IllegalArgumentException e) { 20 | numberOfSeconds = instance.getNumberOfSeconds(argument * -1); 21 | } 22 | System.out.println(numberOfSeconds); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /09_wyjatki/src/main/java/pl/samouczekprogramisty/kursjava/exception/CheckedExceptions.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exception; 2 | 3 | import java.io.IOException; 4 | 5 | public class CheckedExceptions { 6 | public static void main(String[] args) { 7 | CheckedExceptions instance = new CheckedExceptions(); 8 | try { 9 | instance.methodWithCheckedException(); 10 | } 11 | catch (IOException e) { 12 | e.printStackTrace(); 13 | } 14 | } 15 | 16 | private void methodWithCheckedException() throws IOException { 17 | throw new IOException(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /09_wyjatki/src/main/java/pl/samouczekprogramisty/kursjava/exception/ExceptionInheritance.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exception; 2 | 3 | public class ExceptionInheritance { 4 | public static void main(String[] args) { 5 | multipleCatchBlocks(); 6 | multipleExceptionsInOneCatch(); 7 | } 8 | 9 | private static void multipleExceptionsInOneCatch() { 10 | try { 11 | someMagicMethod(); 12 | } 13 | catch (ArithmeticException | IllegalArgumentException exception) { 14 | // handle exception 15 | } 16 | } 17 | 18 | private static void someMagicMethod() { 19 | } 20 | 21 | private static void multipleCatchBlocks() { 22 | try { 23 | throw new IllegalArgumentException(); 24 | } 25 | catch (ArithmeticException exception) { 26 | // 1 27 | } 28 | catch (RuntimeException exception) { 29 | // 2 30 | } 31 | catch (Exception exception) { 32 | // 3 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /09_wyjatki/src/main/java/pl/samouczekprogramisty/kursjava/exception/FinallyExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exception; 2 | 3 | public class FinallyExample { 4 | public static void main(String[] args) { 5 | try { 6 | throw new RuntimeException(); 7 | } 8 | finally { 9 | System.out.println("Surprise!"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /09_wyjatki/src/main/java/pl/samouczekprogramisty/kursjava/exception/StackTraceExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exception; 2 | 3 | public class StackTraceExample { 4 | public static void main(String[] args) { 5 | StackTraceExample example = new StackTraceExample(); 6 | example.method1(); 7 | } 8 | 9 | public void method1() { 10 | method2(); 11 | } 12 | 13 | public void method2() { 14 | method3(); 15 | } 16 | 17 | public void method3() { 18 | throw new RuntimeException("BUM! BUM! BUM!"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /09_wyjatki/src/main/java/pl/samouczekprogramisty/kursjava/exception/exercise/Exercise.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exception.exercise; 2 | 3 | import java.util.InputMismatchException; 4 | import java.util.Scanner; 5 | 6 | public class Exercise { 7 | public static void main(String[] args) { 8 | System.out.println("Podaj liczbę: "); 9 | Scanner input = new Scanner(System.in); 10 | double userInput = 0; 11 | while (true) { 12 | try { 13 | userInput = input.nextDouble(); 14 | break; 15 | } 16 | catch (InputMismatchException e) { 17 | System.out.println("Podaj poprawną liczbę!"); 18 | // ignoring wrong token 19 | input.next(); 20 | } 21 | } 22 | 23 | if (userInput < 0) { 24 | throw new IllegalArgumentException(String.format("Pierwiastek kwadratowy z liczby rzeczywistej %.4f nie istnieje!", userInput)); 25 | } 26 | 27 | System.out.print(String.format("Pierwieastek z %.4f to %.4f.", userInput, Math.sqrt(userInput))); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /10_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/Null.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class Null { 4 | public static void main(String[] args) { 5 | Object variable = null; 6 | System.out.println(variable.toString() ); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /10_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/ObjectFieldsChanging.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class ObjectFieldsChanging { 4 | private int attribute; 5 | 6 | public ObjectFieldsChanging(int attribute) { 7 | this.attribute = attribute; 8 | } 9 | 10 | public int getAttribute() { 11 | return attribute; 12 | } 13 | 14 | public void setAttribute(int attribute) { 15 | this.attribute = attribute; 16 | } 17 | 18 | public static void main(String[] args) { 19 | ObjectFieldsChanging reference1 = new ObjectFieldsChanging(123); 20 | ObjectFieldsChanging reference2 = reference1; 21 | 22 | System.out.println(reference1.getAttribute()); 23 | System.out.println(reference2.getAttribute()); 24 | 25 | reference1.setAttribute(1); 26 | 27 | System.out.println(reference1.getAttribute()); 28 | System.out.println(reference2.getAttribute()); 29 | 30 | reference2 = new ObjectFieldsChanging(3); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /10_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/ObjectVersusReference.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class ObjectVersusReference { 4 | public static void main(String[] args) { 5 | Object referenceToObjectX = new Object(); 6 | Object anotherReferenceToObjectX = referenceToObjectX; 7 | Object refferenceToObjectY = new Object(); 8 | 9 | System.out.println(referenceToObjectX.toString()); 10 | System.out.println(anotherReferenceToObjectX.toString()); 11 | System.out.println(refferenceToObjectY.toString()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /10_obiekty/src/main/java/pl/samouczekprogramisty/kursjava/StringExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class StringExample { 4 | @Override 5 | public boolean equals(Object obj) { 6 | return super.equals(obj); 7 | } 8 | 9 | public static void main(String[] args) { 10 | String x1 = new String("x"); 11 | String x2 = new String("x"); 12 | String x3 = "x"; 13 | String x4 = "x"; 14 | 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/ArithmeticConversion.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class ArithmeticConversion { 4 | public static void main(String[] args) { 5 | short shortValue = 1; 6 | int intValue = 1; 7 | long longValue = 2; 8 | float floatValue = 3.1F; 9 | double doubleValue = 4.1; 10 | 11 | System.out.println(intValue + doubleValue); 12 | System.out.println(intValue + floatValue); 13 | System.out.println(intValue + longValue); 14 | System.out.println(shortValue + shortValue); 15 | 16 | System.out.println(1 / 0.5); 17 | System.out.println(5/2.); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/AssignmentConversion.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class AssignmentConversion { 4 | public static void main(String[] args) { 5 | long longValue = 123; 6 | int intValue = (short) 123; 7 | float floatValue = 12.12F; 8 | double doubleValue = floatValue; 9 | 10 | System.out.println(longValue); 11 | System.out.println(intValue); 12 | System.out.println(floatValue); 13 | System.out.println(doubleValue); 14 | } 15 | 16 | private static void stringConversion() { 17 | String x = "123" + new Object(); 18 | String y = new Object() + "123"; 19 | String z = 1 + "123"; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/Boxing.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class Boxing { 4 | public static void main(String[] args) { 5 | autounboxing(); 6 | autoboxing(); 7 | } 8 | 9 | private static void autounboxing() { 10 | int primitiveInt = Integer.valueOf(123); 11 | long primitiveLong = Long.valueOf(123L); 12 | float primitiveFloat = Float.valueOf(123.123F); 13 | double primitiveDouble = Double.valueOf(123.123); 14 | boolean primitiveBoolean = Boolean.valueOf(true); 15 | } 16 | 17 | private static void autoboxing() { 18 | Integer objectInteger = 123; 19 | Long objectLong = 123L; 20 | Float objectFloat = 123.123F; 21 | Double objectDouble = 123.123; 22 | Boolean objectBoolean = true; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/NarrowingConversion.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class NarrowingConversion { 4 | public static void main(String[] args) { 5 | NarrowingConversion conversion = new NarrowingConversion(); 6 | int intVariable = Integer.MAX_VALUE; 7 | long longVariable = Long.MAX_VALUE; 8 | long longVariableWithoutLoosingInformation = Integer.MAX_VALUE; // automatic conversion from int to long 9 | 10 | conversion.methodIntArgument(intVariable); 11 | conversion.methodIntArgument((int) longVariable); 12 | conversion.methodIntArgument((int) longVariableWithoutLoosingInformation); 13 | } 14 | 15 | public void methodIntArgument(int argument) { 16 | System.out.println(argument); 17 | } 18 | 19 | public void narrowingConversion() { 20 | int intValue = (int) 123.123F; 21 | long longValue = (long) 456.456; 22 | char x = 'x'; 23 | int xx = x; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/RuntimeType.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class RuntimeType { 4 | public static void main(String[] args) { 5 | Object[] someMysteriousObjects = new Object[] {"1234", new Object()}; 6 | 7 | String castedString = (String) someMysteriousObjects[0]; 8 | String classCastException = (String) someMysteriousObjects[1]; 9 | } 10 | 11 | public void differentTypes() { 12 | Object objectInstance = new Object(); 13 | Object stringInstance = "string"; 14 | 15 | String realString = (String) stringInstance; 16 | realString.length(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/WideningConversion.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | public class WideningConversion { 4 | public static void main(String[] args) { 5 | WideningConversion conversion = new WideningConversion(); 6 | int intVariable = Integer.MAX_VALUE; 7 | long longVariable = Long.MAX_VALUE; 8 | 9 | conversion.methodLongArgument(intVariable); 10 | conversion.methodLongArgument(longVariable); 11 | } 12 | 13 | public void methodLongArgument(long argument) { 14 | System.out.println(argument); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/zadanie/AsciiTable.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.zadanie; 2 | 3 | public class AsciiTable { 4 | public static void main(String[] args) { 5 | char aAsChar = 'a'; 6 | System.out.println(aAsChar); 7 | int aAsInt = aAsChar; 8 | System.out.println(aAsInt); 9 | 10 | int ninetyEightAsInt = 98; 11 | System.out.println(ninetyEightAsInt); 12 | char ninetyoneAsChar = (char) ninetyEightAsInt; 13 | System.out.println(ninetyoneAsChar); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/zadanie/Box.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.zadanie; 2 | 3 | public class Box { 4 | private final T attribute; 5 | 6 | public Box(T attribute) { 7 | this.attribute = attribute; 8 | } 9 | 10 | public T getAttribute() { 11 | return attribute; 12 | } 13 | } -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/zadanie/NumberMultiplier.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.zadanie; 2 | 3 | import java.util.Scanner; 4 | 5 | public class NumberMultiplier { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int number1 = PiMultiplier.getNumberFromUser(scanner); 9 | double number2 = PiMultiplier.getNumberFromUser(scanner); 10 | System.out.println(number1 / number2); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/zadanie/PiMultiplier.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.zadanie; 2 | 3 | import java.util.NoSuchElementException; 4 | import java.util.Scanner; 5 | 6 | public class PiMultiplier { 7 | 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | int number = getNumberFromUser(scanner); 11 | System.out.println(number * Math.PI); 12 | System.out.println((int) (number * Math.PI)); 13 | } 14 | 15 | public static int getNumberFromUser(Scanner scanner) { 16 | System.out.println("Podaj liczbę całkowitą"); 17 | while(true) { 18 | try { 19 | return scanner.nextInt(); 20 | } 21 | catch (NoSuchElementException | IllegalStateException exception) { 22 | System.out.println("Wpwowadziłeś niepoprawną liczbę, spróbuj jeszcze raz..."); 23 | scanner.next(); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /11_konwersja_rzutowanie/src/main/java/pl/samouczekprogramisty/kursjava/zadanie/UnboxingExceptions.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.zadanie; 2 | 3 | 4 | public class UnboxingExceptions { 5 | @SuppressWarnings("unchecked") 6 | public static void main(String[] args) { 7 | Box box = new Box<>(new Object()); 8 | Box box2 = (Box) box; 9 | int attribute = box2.getAttribute(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/arrays/ArraysExcercises.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.arrays; 2 | 3 | public class ArraysExcercises { 4 | public static void main(String[] args) { 5 | get5AlphabetLetters(); 6 | revertArray(new double[] {1, 2, 3}); 7 | } 8 | 9 | private static String[] get5AlphabetLetters() { 10 | return new String[] {"a", "ą", "b", "c", "ć"}; 11 | } 12 | 13 | private static double[] revertArray(double[] array) { 14 | return new double[] {array[2], array[1], array[0]}; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/Female.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public class Female implements Human{ 4 | private int age; 5 | private double weight; 6 | private double height; 7 | private String name; 8 | private boolean isMale; 9 | 10 | public Female(int age, double weight, double height, String name) { 11 | this.age = age; 12 | this.weight = weight; 13 | this.height = height; 14 | this.name = name; 15 | isMale = false; 16 | } 17 | 18 | public int getAge() { 19 | return age; 20 | } 21 | 22 | public double getWeight() { 23 | return weight; 24 | } 25 | 26 | public double getHeight() { 27 | return height; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public boolean isMale() { 35 | return isMale; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public interface Human { 4 | boolean isMale(); 5 | 6 | String getName(); 7 | 8 | double getWeight(); 9 | 10 | double getHeight(); 11 | 12 | int getAge(); 13 | } -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/Male.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces; 2 | 3 | public class Male implements Human { 4 | private int age; 5 | private double weight; 6 | private double height; 7 | private String name; 8 | private boolean isMale; 9 | 10 | public Male(int age, double weight, double height, String name) { 11 | this.age = age; 12 | this.weight = weight; 13 | this.height = height; 14 | this.name = name; 15 | isMale = true; 16 | } 17 | 18 | public int getAge() { 19 | return age; 20 | } 21 | 22 | public double getWeight() { 23 | return weight; 24 | } 25 | 26 | public double getHeight() { 27 | return height; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public boolean isMale() { 35 | return isMale; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/figures/Circle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.figures; 2 | 3 | 4 | public class Circle implements Figure { 5 | private double radius; 6 | 7 | public Circle(double radius) { 8 | this.radius = radius; 9 | } 10 | 11 | public double getPerimeter() { 12 | return 2 * Math.PI * radius; 13 | } 14 | 15 | public double getArea() { 16 | return Math.PI * radius * radius; 17 | } 18 | 19 | public String getType() { 20 | return "circle"; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/figures/Figure.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.figures; 2 | 3 | public interface Figure { 4 | double getPerimeter(); 5 | double getArea(); 6 | String getType(); 7 | } 8 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/figures/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.figures; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Figure[] figures = new Figure[3]; 8 | 9 | Scanner scanner = new Scanner(System.in); 10 | System.out.println("Podaj promień"); 11 | figures[0] = new Circle(scanner.nextDouble()); 12 | 13 | System.out.println("Podaj 2 boki trójkąta"); 14 | figures[1] = new Triangle(scanner.nextDouble(), scanner.nextDouble()); 15 | 16 | System.out.println("Podaj 2 boki prostokąta"); 17 | figures[2] = new Rectangle(scanner.nextDouble(), scanner.nextDouble()); 18 | 19 | for (Figure figure : figures) { 20 | System.out.println(figure.getType()); 21 | System.out.println("pole " + figure.getArea()); 22 | System.out.println("obwód " + figure.getPerimeter()); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/figures/Rectangle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.figures; 2 | 3 | public class Rectangle extends pl.samouczekprogramisty.kursjava.objects.Rectangle implements Figure { 4 | 5 | public Rectangle(double sideA, double sideB) { 6 | super(sideA, sideB); 7 | } 8 | 9 | public String getType() { 10 | return "rectangle"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/interfaces/figures/Triangle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.interfaces.figures; 2 | 3 | public class Triangle implements Figure { 4 | private double a; 5 | private double b; 6 | private double hypotenuse; 7 | 8 | public Triangle(double a, double b) { 9 | this.a = a; 10 | this.b = b; 11 | this.hypotenuse = Math.sqrt(a * a + b * b); 12 | } 13 | 14 | public double getPerimeter() { 15 | return a + b + hypotenuse; 16 | } 17 | 18 | public double getArea() { 19 | return a * b / 2; 20 | } 21 | 22 | public String getType() { 23 | return "triangle"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/loops/ArrayFactory.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.loops; 2 | 3 | public class ArrayFactory { 4 | 5 | private final int size; 6 | 7 | public ArrayFactory(int size) { 8 | this.size = size; 9 | } 10 | 11 | public int[] buildOneDimension() { 12 | return new int[size]; 13 | } 14 | 15 | public int[][] buildTwoDimensions() { 16 | int[][] array = new int[size][]; 17 | for(int i = 0; i < size; i++) { 18 | array[i] = new int[size]; 19 | } 20 | return array; 21 | } 22 | 23 | public int[][] buildTwoDimensionsInOneLine() { 24 | return new int[size][size]; 25 | } 26 | 27 | public int[][] identityMatrix() { 28 | int[][] matrix = buildTwoDimensions(); 29 | for (int i = 0; i < size; i++) { 30 | for (int j = 0; j < size; j++) { 31 | if (i == j) { 32 | matrix[i][j] = 1; 33 | } 34 | else { 35 | // that line is superfluous, arrays are initialized with default value, 0 in case of int type 36 | matrix[i][j] = 0; 37 | } 38 | } 39 | } 40 | return matrix; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/objects/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects; 2 | 3 | public class Human { 4 | private int age; 5 | private double weight; 6 | private double height; 7 | private String name; 8 | private boolean isMale; 9 | 10 | public Human(int age, double weight, double height, String name, boolean isMale) { 11 | this.age = age; 12 | this.weight = weight; 13 | this.height = height; 14 | this.name = name; 15 | this.isMale = isMale; 16 | } 17 | 18 | public boolean isMale() { 19 | return isMale; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public double getWeight() { 27 | return weight; 28 | } 29 | 30 | public double getHeight() { 31 | return height; 32 | } 33 | 34 | public int getAge() { 35 | return age; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/objects/MyNumber.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects; 2 | 3 | public class MyNumber { 4 | private double value; 5 | 6 | public MyNumber(double value) { 7 | this.value = value; 8 | } 9 | 10 | public boolean isOdd() { 11 | return ! isEven(); 12 | } 13 | 14 | public boolean isEven() { 15 | return value % 2 == 0; 16 | } 17 | 18 | public double sqrt() { 19 | return Math.sqrt(value); 20 | } 21 | 22 | public MyNumber pow(MyNumber pow) { 23 | return new MyNumber(Math.pow(value, pow.value)); 24 | } 25 | 26 | public MyNumber add(MyNumber otherValue) { 27 | return new MyNumber(value + otherValue.value); 28 | } 29 | 30 | public MyNumber subract(MyNumber otherValue) { 31 | return new MyNumber(value - otherValue.value); 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return String.valueOf(value); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/objects/Rectangle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.objects; 2 | 3 | public class Rectangle { 4 | private double sideA; 5 | private double sideB; 6 | 7 | public Rectangle(double sideA, double sideB) { 8 | this.sideA = sideA; 9 | this.sideB = sideB; 10 | } 11 | 12 | public double getSideA() { 13 | return sideA; 14 | } 15 | 16 | public double getSideB() { 17 | return sideB; 18 | } 19 | 20 | public double getArea() { 21 | return sideA * sideB; 22 | } 23 | 24 | public double getPerimeter() { 25 | return 2 * sideA + 2 * sideB; 26 | } 27 | 28 | public double getDiagonal() { 29 | return Math.sqrt(sideA * sideA + sideB * sideB); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /12_dodatkowe_zadania/src/main/java/pl/samouczekprogramisty/kursjava/primitivetypes/SimpleTypesExcercise.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.primitivetypes; 2 | 3 | import pl.samouczekprogramisty.kursjava.loops.LoopsExcercises; 4 | 5 | import java.util.Scanner; 6 | 7 | public class SimpleTypesExcercise { 8 | public static void main(String[] args) { 9 | // printBinaryEnteredByUser(); 10 | instantiateArray(); 11 | } 12 | 13 | private static void printBinaryEnteredByUser() { 14 | Scanner scanner = new Scanner(System.in); 15 | System.out.println("Podaj liczbe calkowita"); 16 | LoopsExcercises.printBinary(scanner.nextInt()); 17 | } 18 | 19 | private static void instantiateArray() { 20 | Scanner scanner = new Scanner(System.in); 21 | System.out.println("Podaj długość tablicy"); 22 | int arrayLenght = scanner.nextInt(); 23 | int[] numbers = new int[arrayLenght]; 24 | for (int i = 0; i < numbers.length; i++) { 25 | System.out.println("Podaj liczbę na " + (i + 1) + " element tablicy"); 26 | numbers[i] = scanner.nextInt(); 27 | } 28 | LoopsExcercises.bubbleSort(numbers); 29 | LoopsExcercises.printArray(numbers); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/Apple.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class Apple { 4 | } 5 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/AppleBox.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class AppleBox { 4 | private Apple apple; 5 | 6 | public AppleBox(Apple apple) { 7 | this.apple = apple; 8 | } 9 | 10 | public Apple getApple() { 11 | return apple; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/BoxOnSteroids.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class BoxOnSteroids { 4 | public T fruit; 5 | 6 | public BoxOnSteroids(T fruit) { 7 | this.fruit = fruit; 8 | } 9 | 10 | public T getFruit() { 11 | return fruit; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/GenericMethod.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class GenericMethod { 4 | public K add(K first, K second) { 5 | if (first == null) { 6 | return second; 7 | } 8 | return first; 9 | } 10 | 11 | public static void print(K arg1, K arg2) { 12 | System.out.println(arg1); 13 | System.out.println(arg2); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | import pl.samouczekprogramisty.kursjava.generics.genericinteritance.FancyBox; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | AppleBox appleBox1 = new AppleBox(new Apple()); 8 | OrangeBox orangeBox1 = new OrangeBox(new Orange()); 9 | 10 | ObjectBox fruitBox = new ObjectBox(new Orange()); 11 | Orange fruit1 = (Orange) fruitBox.getFruit(); 12 | 13 | BoxOnSteroids appleBox2 = new BoxOnSteroids<>(new Apple()); 14 | BoxOnSteroids orangeBox2 = new BoxOnSteroids<>(new Orange()); 15 | 16 | Orange fruit2 = orangeBox2.getFruit(); 17 | 18 | nestedGenerics(); 19 | 20 | // genericClassCastException(); 21 | 22 | genericMethods(); 23 | } 24 | 25 | private static void nestedGenerics() { 26 | Pair, BoxOnSteroids> pairOfBoxes = 27 | new Pair<>( 28 | new BoxOnSteroids<>(new Orange()), 29 | new BoxOnSteroids<>(new Apple()) 30 | ); 31 | } 32 | 33 | @SuppressWarnings({"unchecked", "unused"}) 34 | private static void genericClassCastException() { 35 | BoxOnSteroids boxWithoutType = new BoxOnSteroids(new Apple()); 36 | BoxOnSteroids boxWithApple = boxWithoutType; 37 | BoxOnSteroids boxWithOrange = boxWithoutType; 38 | Apple apple = boxWithApple.getFruit(); 39 | Orange orange = boxWithOrange.getFruit(); // ClassCastException 40 | 41 | System.out.println(boxWithApple.getFruit()); 42 | System.out.println(boxWithOrange.getFruit()); 43 | } 44 | 45 | @SuppressWarnings("unused") 46 | public static void compilationError() { 47 | FancyBox box = new FancyBox<>("object"); 48 | box.object = null; 49 | // box.object = "xxx"; // CompilationError 50 | } 51 | 52 | private static void genericMethods() { 53 | GenericMethod genericMethod = new GenericMethod(); 54 | GenericMethod.print(1L, new Apple()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/ObjectBox.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class ObjectBox { 4 | private Object fruit; 5 | 6 | public ObjectBox(Object fruit) { 7 | this.fruit = fruit; 8 | } 9 | 10 | public Object getFruit() { 11 | return fruit; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/Orange.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class Orange { 4 | } 5 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/OrangeBox.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class OrangeBox { 4 | private Orange orange; 5 | 6 | public OrangeBox(Orange orange) { 7 | this.orange = orange; 8 | } 9 | 10 | public Orange getOrange() { 11 | return orange; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/Pair.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics; 2 | 3 | public class Pair { 4 | private T first; 5 | private S second; 6 | 7 | public Pair(T first, S second) { 8 | this.first = first; 9 | this.second = second; 10 | } 11 | 12 | public T getFirst() { 13 | return first; 14 | } 15 | 16 | public S getSecond() { 17 | return second; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/BoxForFigures.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public class BoxForFigures { 4 | private T element; 5 | 6 | public BoxForFigures(T element) { 7 | this.element = element; 8 | } 9 | 10 | public T getElement() { 11 | return element; 12 | } 13 | 14 | public String getElementName() { 15 | return element.getName(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/Circle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public class Circle implements Figure { 4 | public String getName() { 5 | return "circle"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/Figure.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public interface Figure { 4 | String getName(); 5 | } 6 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | compilationError(); 6 | BoxForFigures triangleBox = new BoxForFigures<>(new Triangle()); 7 | //BoxForFigures rectangleBox = new BoxForFigures<>(new Rectangle()); 8 | BoxForFigures squareBox = new BoxForFigures<>(new Square()); 9 | 10 | compilationError2(); 11 | } 12 | 13 | private static void compilationError2() { 14 | Rectangle rectangle = new Square(); 15 | //BoxForFigures rectangleBox = new BoxForFigures(new Square()); 16 | } 17 | 18 | private static void compilationError() { 19 | BoxForFigures circleBox = new BoxForFigures<>(new Circle()); 20 | // BoxForFigures appleBox; // complilation failure 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/Rectangle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public class Rectangle implements Figure { 4 | public String getName() { 5 | return "rectangle"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/Square.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public class Square extends Rectangle { 4 | public String getName() { 5 | return "square"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/extendexample/Triangle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.extendexample; 2 | 3 | public class Triangle implements Figure { 4 | public String getName() { 5 | return "triangle"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/genericinteritance/FancyBox.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.genericinteritance; 2 | 3 | public class FancyBox extends StandardBox { 4 | public FancyBox(T object) { 5 | super(object); 6 | } 7 | public void saySomethingFancy() { 8 | System.out.println("our " + object + " is cool!"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/genericinteritance/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.genericinteritance; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | FancyBox box = new FancyBox<>("something"); 6 | box.saySomethingFancy(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /13_typy_generyczne/src/main/java/pl/samouczekprogramisty/kursjava/generics/genericinteritance/StandardBox.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.generics.genericinteritance; 2 | 3 | public class StandardBox { 4 | public T object; 5 | 6 | public StandardBox(T object) { 7 | this.object = object; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /14_porownywanie_obiektow/src/main/java/pl/samouczekprogramisty/kursjava/equality/Chair.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.equality; 2 | 3 | public class Chair { 4 | private String model; 5 | private String manufacturer; 6 | private int productionYear; 7 | 8 | public Chair(String model, String manufacturer, int productionYear) { 9 | this.model = model; 10 | this.manufacturer = manufacturer; 11 | this.productionYear = productionYear; 12 | } 13 | 14 | public String getModel() { 15 | return model; 16 | } 17 | 18 | public String getManufacturer() { 19 | return manufacturer; 20 | } 21 | 22 | public int getProductionYear() { 23 | return productionYear; 24 | } 25 | 26 | @Override 27 | public boolean equals(Object obj) { 28 | if (obj == null) { 29 | return false; 30 | } 31 | if (obj instanceof Chair) { 32 | Chair otherChair = (Chair) obj; 33 | return model.equals(otherChair.model) && 34 | manufacturer.equals(otherChair.manufacturer) && 35 | productionYear == otherChair.productionYear; 36 | } 37 | return false; 38 | 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return 17 * model.hashCode() + 31 * manufacturer.hashCode() + 7 * productionYear; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /14_porownywanie_obiektow/src/main/java/pl/samouczekprogramisty/kursjava/equality/ComparisionExamples.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.equality; 2 | 3 | import pl.samouczekprogramisty.kursjava.equality.Chair; 4 | 5 | public class ComparisionExamples { 6 | 7 | public static void main(String[] args) { 8 | rawTypesComparison(); 9 | rawFloatingPointComparison(); 10 | objectsComparison(); 11 | customObjectsComparison(); 12 | } 13 | 14 | private static void customObjectsComparison() { 15 | Chair chair1 = new Chair("Adde", "IKEA", 2016); 16 | Chair chair2 = new Chair("Janinge", "IKEA", 2016); 17 | Chair chair3 = new Chair("Adde", "IKEA", 2015); 18 | Chair chair4 = new Chair("Adde", "IKEA", 2016); 19 | 20 | System.out.println("chair1.equals(chair2): " + chair1.equals(chair2)); 21 | System.out.println("chair1.equals(chair3): " + chair1.equals(chair3)); 22 | System.out.println("chair1.equals(chair4): " + chair1.equals(chair4)); 23 | System.out.println("chair1.equals(null): " + chair1.equals(null)); 24 | } 25 | 26 | private static void objectsComparison() { 27 | System.out.println("test == test: " + (new String("test") == new String("test"))); 28 | System.out.println("test equals test: " + new String("test").equals(new String("test"))); 29 | 30 | String reference1 = new String("something"); 31 | String reference2 = reference1; 32 | System.out.println("reference1 == reference2: " + (reference1 == reference2)); 33 | } 34 | 35 | private static void rawFloatingPointComparison() { 36 | System.out.println("0.3 == 0.1 + 0.2: " + (0.3 == 0.1 + 0.2)); // !!! 37 | System.out.println("0.3 == 0.1 + 0.2: " + (Math.abs(0.3 - (0.1 + 0.2)) < 0.000001)); 38 | } 39 | 40 | private static void rawTypesComparison() { 41 | System.out.println("10 == 10: " + (10 == 10)); 42 | System.out.println("10 != 10: " + (10 != 10)); 43 | System.out.println("true == true: " + (true == true)); 44 | System.out.println("true != true: " + (true != true)); 45 | System.out.println("'a' == 'a': " + ('a' == 'a')); 46 | System.out.println("'a' != 'a': " + ('a' != 'a')); 47 | System.out.println("500L == 500L: " + (500L == 500L)); 48 | System.out.println("500L != 500L: " + (500L != 500L)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /14_porownywanie_obiektow/src/main/java/pl/samouczekprogramisty/kursjava/equality/exercise/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.equality.exercise; 2 | 3 | public class Human { 4 | private final String name; 5 | private final String surname; 6 | private final String pesel; 7 | 8 | public Human(String name, String surname, String pesel) { 9 | this.name = name; 10 | this.surname = surname; 11 | if (pesel == null) { 12 | throw new IllegalArgumentException("Every human needs to have PESEL!"); 13 | } 14 | this.pesel = pesel; 15 | } 16 | 17 | @Override 18 | public int hashCode() { 19 | return 17 * pesel.hashCode(); 20 | } 21 | 22 | @Override 23 | public boolean equals(Object obj) { 24 | if (obj == null) { 25 | return false; 26 | } 27 | if (!(obj instanceof Human)) { 28 | return false; 29 | } 30 | 31 | Human otherHuman = (Human) obj; 32 | return pesel.equals(otherHuman.getPesel()); 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return name + " " + surname + " " + pesel; 38 | } 39 | 40 | public String getSurname() { 41 | return surname; 42 | } 43 | 44 | public String getName() { 45 | return name; 46 | } 47 | 48 | public String getPesel() { 49 | return pesel; 50 | } 51 | 52 | public static void main(String[] args) { 53 | Human human1 = new Human("Jan", "Kowalski", "850223000000"); 54 | Human human2 = new Human("Jan", "Kowalski", "891213000000"); 55 | Human human3 = new Human("Jan", "Kowalski", "850223000000"); 56 | 57 | System.out.println(human1 + " == " + human2 + " " + human1.equals(human2)); 58 | System.out.println(human2 + " == " + human3 + " " + human2.equals(human3)); 59 | System.out.println(human1 + " == " + human3 + " " + human1.equals(human3)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /15_kolekcje/src/main/java/pl/samouczekprogramisty/kursjava/ListExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | public class ListExample { 8 | public static void main(String[] args) { 9 | List listWithNames = new LinkedList<>(); 10 | listWithNames.add("Piotrek"); 11 | listWithNames.add("Krzysiek"); 12 | 13 | List otherListWithNames = new LinkedList<>(); 14 | otherListWithNames.add("Marek"); 15 | otherListWithNames.addAll(listWithNames); 16 | otherListWithNames.add("Marek"); 17 | 18 | System.out.println(otherListWithNames.contains("Marek")); 19 | System.out.println(otherListWithNames.get(0)); 20 | System.out.println(otherListWithNames.isEmpty()); 21 | System.out.println(otherListWithNames.size()); 22 | System.out.println(otherListWithNames.indexOf("Marek")); 23 | System.out.println(otherListWithNames.lastIndexOf("Marek")); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /15_kolekcje/src/main/java/pl/samouczekprogramisty/kursjava/MapExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MapExample { 7 | public static void main(String[] args) { 8 | Map pairsMap = new HashMap<>(); 9 | pairsMap.put("Marcin", "Adela"); 10 | pairsMap.put("Marek", "Magda"); 11 | 12 | Map otherPairsMap = new HashMap<>(); 13 | otherPairsMap.put("Marek", "Ewa"); 14 | otherPairsMap.put("Adam", "Ewa"); 15 | 16 | pairsMap.putAll(otherPairsMap); 17 | 18 | System.out.println(pairsMap.get("Marek")); 19 | System.out.println(pairsMap.remove("Marek")); 20 | System.out.println(pairsMap.size()); 21 | System.out.println(pairsMap.isEmpty()); 22 | System.out.println(pairsMap.containsKey("Jan")); 23 | System.out.println(pairsMap.containsValue("Adela")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /15_kolekcje/src/main/java/pl/samouczekprogramisty/kursjava/SetExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class SetExample { 7 | public static void main(String[] args) { 8 | Set setWithNames = new HashSet<>(); 9 | setWithNames.add("Marcin"); 10 | setWithNames.add("Marek"); 11 | setWithNames.add("Marcin"); 12 | 13 | Set otherSet = new HashSet<>(); 14 | otherSet.add("Zenon"); 15 | otherSet.add("Marek"); 16 | 17 | setWithNames.addAll(otherSet); 18 | 19 | System.out.println(setWithNames.isEmpty()); 20 | System.out.println(setWithNames.size()); 21 | System.out.println(setWithNames.contains("Marcin")); 22 | System.out.println(setWithNames.remove("Janusz")); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /15_kolekcje/src/main/java/pl/samouczekprogramisty/kursjava/exercise/Exercise1.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exercise; 2 | 3 | import java.util.HashSet; 4 | import java.util.Scanner; 5 | import java.util.Set; 6 | 7 | public class Exercise1 { 8 | 9 | public static final String NO_MORE_NAMES = "-"; 10 | 11 | public static void main(String[] args) { 12 | String name; 13 | Set names = new HashSet<>(); 14 | Scanner input = new Scanner(System.in); 15 | do { 16 | System.out.println("Podaj imie: "); 17 | name = input.next(); 18 | if (!name.equals(NO_MORE_NAMES)) { 19 | names.add(name); 20 | } 21 | } while (!name.equals(NO_MORE_NAMES)); 22 | 23 | 24 | System.out.println("Wprowadziles " + names.size() + " unikalnych imion."); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /15_kolekcje/src/main/java/pl/samouczekprogramisty/kursjava/exercise/Exercise2.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.exercise; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class Exercise2 { 8 | public static void main(String[] args) { 9 | Map pairs = new HashMap<>(); 10 | Scanner input = new Scanner(System.in); 11 | String name1, name2; 12 | 13 | while(true) { 14 | System.out.println("Podaj imie partnera: "); 15 | name1 = input.next(); 16 | if (name1.equals("-")) { 17 | break; 18 | } 19 | System.out.println("Podaj imie partnerki: "); 20 | name2 = input.next(); 21 | if (name2.equals("-")) { 22 | break; 23 | } 24 | pairs.put(name1, name2); 25 | } 26 | 27 | System.out.println("Podaj imie partnera do sprawdzenia: "); 28 | name1 = input.next(); 29 | System.out.println("Partnerka dla " + name1 + " to " + pairs.get(name1)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /16_operacje_na_plikach/src/main/java/pl/samouczekprogramisty/kursjava/files/BinaryFileManipulation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.files; 2 | 3 | import java.io.DataInputStream; 4 | import java.io.DataOutputStream; 5 | import java.io.FileInputStream; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | 9 | public class BinaryFileManipulation { 10 | public static void main(String[] args) throws IOException { 11 | int numberToWrite = 1234567; 12 | 13 | String filePath = "test_binary_file.bin"; 14 | writeToBinaryFile(filePath, numberToWrite); 15 | System.out.println(readFromBinaryFila(filePath)); 16 | } 17 | 18 | private static int readFromBinaryFila(String filePath) throws IOException { 19 | DataInputStream inputStream = null; 20 | try { 21 | inputStream = new DataInputStream(new FileInputStream(filePath)); 22 | return inputStream.readInt(); 23 | } finally { 24 | if (inputStream != null) { 25 | inputStream.close(); 26 | } 27 | } 28 | } 29 | 30 | private static void writeToBinaryFile(String filePath, int number) throws IOException { 31 | DataOutputStream outputStream = null; 32 | try { 33 | outputStream = new DataOutputStream(new FileOutputStream(filePath)); 34 | outputStream.writeInt(number); 35 | } finally { 36 | if (outputStream != null) { 37 | outputStream.close(); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /16_operacje_na_plikach/src/main/java/pl/samouczekprogramisty/kursjava/files/TextFileManipulation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.files; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | 9 | public class TextFileManipulation { 10 | public static void main(String[] args) throws IOException { 11 | int numberToWrite = 1234567; 12 | String filePath = "test_text_file.txt"; 13 | writeToTextFile(filePath, numberToWrite); 14 | System.out.println(readFromTextFile(filePath)); 15 | } 16 | 17 | private static int readFromTextFile(String filePath) throws IOException { 18 | BufferedReader fileReader = null; 19 | try { 20 | fileReader = new BufferedReader(new FileReader(filePath)); 21 | String number = fileReader.readLine(); 22 | return Integer.parseInt(number); 23 | } finally { 24 | if (fileReader != null) { 25 | fileReader.close(); 26 | } 27 | } 28 | } 29 | 30 | private static void writeToTextFile(String filePath, int number) throws IOException { 31 | FileWriter fileWriter = null; 32 | try { 33 | fileWriter = new FileWriter(filePath); 34 | fileWriter.write(Integer.toString(number)); 35 | } finally { 36 | if (fileWriter != null) { 37 | fileWriter.close(); 38 | } 39 | } 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /16_operacje_na_plikach/src/main/java/pl/samouczekprogramisty/kursjava/files/exercise/Exercise1.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.files.exercise; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | import java.util.Scanner; 6 | 7 | public class Exercise1 { 8 | public static void main(String[] args) throws IOException { 9 | Scanner input = new Scanner(System.in); 10 | FileWriter output = null; 11 | String line; 12 | 13 | System.out.println("Podaj sciezke pliku wyjsciowego: "); 14 | try { 15 | output = new FileWriter(input.nextLine()); 16 | System.out.println("Podaj zawartosc pliku: "); 17 | 18 | while (true) { 19 | line = input.nextLine(); 20 | if (line.equals("-")) { 21 | break; 22 | } 23 | output.write(line); 24 | output.write(System.lineSeparator()); 25 | } 26 | } 27 | finally { 28 | if (output != null) { 29 | output.close(); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /16_operacje_na_plikach/src/main/java/pl/samouczekprogramisty/kursjava/files/exercise/Exercise2.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.files.exercise; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | import java.util.Scanner; 8 | 9 | public class Exercise2 { 10 | public static void main(String[] args) throws IOException { 11 | Scanner input = new Scanner(System.in); 12 | BufferedReader inputFile = null; 13 | int numberOfLines = 0; 14 | String line; 15 | 16 | System.out.println("Podaj sciezke pliku wejsciowego: "); 17 | try { 18 | inputFile = new BufferedReader(new FileReader(input.next())); 19 | System.out.println("Zawartosc pliku: "); 20 | 21 | while (true) { 22 | line = inputFile.readLine(); 23 | if (line == null) { 24 | break; 25 | } 26 | numberOfLines++; 27 | System.out.println(line); 28 | } 29 | } 30 | finally { 31 | if (inputFile != null) { 32 | inputFile.close(); 33 | } 34 | } 35 | System.out.println("Plik ma " + numberOfLines + " linii."); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /16_operacje_na_plikach/src/main/java/pl/samouczekprogramisty/kursjava/files/exercise/Exercise3.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.files.exercise; 2 | 3 | import java.io.DataOutputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | public class Exercise3 { 9 | public static void main(String[] args) throws IOException { 10 | Scanner input = new Scanner(System.in); 11 | 12 | System.out.println("Podaj sciezke do pliku: "); 13 | String filePath = input.nextLine(); 14 | 15 | System.out.println("Podaj dzien urodzenia: "); 16 | int birthDay = input.nextInt(); 17 | 18 | System.out.println("Podaj miesiac urodzenia: "); 19 | int birthMonth = input.nextInt(); 20 | 21 | System.out.println("Podaj rok urodzenia: "); 22 | int birthYear = input.nextInt(); 23 | 24 | DataOutputStream output = null; 25 | try { 26 | output = new DataOutputStream(new FileOutputStream(filePath)); 27 | output.writeInt(birthDay); 28 | output.writeInt(birthMonth); 29 | output.writeInt(birthYear); 30 | } finally { 31 | if (output != null) { 32 | output.close(); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /16_operacje_na_plikach/src/main/java/pl/samouczekprogramisty/kursjava/files/exercise/Exercise4.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.files.exercise; 2 | 3 | import java.io.DataInputStream; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | public class Exercise4 { 9 | public static void main(String[] args) throws IOException { 10 | Scanner input = new Scanner(System.in); 11 | System.out.println("Podaj sciezke pliku wejsciowego: "); 12 | String filePath = input.nextLine(); 13 | DataInputStream inputFile = null; 14 | int birthDay = 0; 15 | int birthMonth = 0; 16 | int birthYear = 0; 17 | 18 | try { 19 | inputFile = new DataInputStream(new FileInputStream(filePath)); 20 | birthDay = inputFile.readInt(); 21 | birthMonth = inputFile.readInt(); 22 | birthYear = inputFile.readInt(); 23 | } finally { 24 | if (inputFile != null) { 25 | inputFile.close(); 26 | } 27 | } 28 | 29 | System.out.println("Data urodzenia to " + birthDay + "." + birthMonth + "." + birthYear + "."); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /17_manager_kontekstu/src/main/java/pl/samouczekprogramisty/kursjava/context/MyContextManager.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.context; 2 | 3 | public class MyContextManager implements AutoCloseable { 4 | public MyContextManager() { 5 | System.out.println("Wlasnie sie tworze!"); 6 | } 7 | 8 | public void doSomething() { 9 | System.out.println("Wlasnie cos robie :)"); 10 | } 11 | 12 | public void close() { 13 | System.out.println("Ktos mnie teraz zamyka!"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /17_manager_kontekstu/src/main/java/pl/samouczekprogramisty/kursjava/context/MyContextManagerMain.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.context; 2 | 3 | public class MyContextManagerMain { 4 | public static void main(String[] args) { 5 | try (MyContextManager manager = new MyContextManager()) { 6 | manager.doSomething(); 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /17_manager_kontekstu/src/main/java/pl/samouczekprogramisty/kursjava/context/exercise/HtmlTag.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.context.exercise; 2 | 3 | public class HtmlTag implements AutoCloseable { 4 | private final String tag; 5 | 6 | public HtmlTag(String tag) { 7 | this.tag = tag; 8 | System.out.println("<" + tag + ">"); 9 | } 10 | 11 | public void body(String body) { 12 | System.out.println(body); 13 | } 14 | 15 | public void close() { 16 | System.out.println(""); 17 | } 18 | 19 | public static void main(String[] args) { 20 | try ( 21 | HtmlTag h1 = new HtmlTag("h1"); 22 | HtmlTag em = new HtmlTag("em") 23 | ) { 24 | em.body("moj tekst"); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/Car.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Car implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | 8 | private Engine engine; 9 | private Tyre[] tyres; 10 | 11 | public Car(Engine engine, Tyre[] tyres) { 12 | this.engine = engine; 13 | this.tyres = tyres; 14 | } 15 | 16 | public Engine getEngine() { 17 | return engine; 18 | } 19 | 20 | public Tyre[] getTyres() { 21 | return tyres; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/CustomProtocolSerialization.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.Externalizable; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.ObjectInput; 8 | import java.io.ObjectInputStream; 9 | import java.io.ObjectOutput; 10 | import java.io.ObjectOutputStream; 11 | 12 | public class CustomProtocolSerialization implements Externalizable { 13 | private String field; 14 | 15 | public CustomProtocolSerialization() { 16 | } 17 | 18 | public CustomProtocolSerialization(String field) { 19 | this.field = field; 20 | } 21 | 22 | public static void main(String[] args) throws IOException, ClassNotFoundException { 23 | CustomProtocolSerialization object = new CustomProtocolSerialization("field value"); 24 | 25 | try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("externalizable.bin"))) { 26 | output.writeObject(object); 27 | } 28 | 29 | try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("externalizable.bin"))) { 30 | CustomProtocolSerialization readObject = (CustomProtocolSerialization) input.readObject(); 31 | System.out.println(readObject.field); 32 | } 33 | } 34 | 35 | @Override 36 | public void writeExternal(ObjectOutput out) throws IOException { 37 | out.writeUTF(field); 38 | } 39 | 40 | @Override 41 | public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { 42 | field = in.readUTF(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/CustomSerialization.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | import java.util.Calendar; 10 | 11 | public class CustomSerialization implements Serializable { 12 | private static final long serialVersionUID = 1L; 13 | 14 | private transient int someField; 15 | private String otherField; 16 | 17 | public CustomSerialization(int someField, String otherField) { 18 | this.someField = someField; 19 | this.otherField = otherField; 20 | } 21 | 22 | public static void main(String[] args) throws IOException, ClassNotFoundException { 23 | CustomSerialization writtenObject = new CustomSerialization(10, "something"); 24 | 25 | try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("custom-serialization.bin"))) { 26 | outputStream.writeObject(writtenObject); 27 | } 28 | 29 | try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("custom-serialization.bin" ))) { 30 | CustomSerialization readObject = (CustomSerialization) inputStream.readObject(); 31 | System.out.println(readObject.someField); 32 | System.out.println(readObject.otherField); 33 | } 34 | } 35 | 36 | private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 37 | stream.defaultReadObject(); 38 | someField = stream.readInt(); 39 | } 40 | 41 | private void writeObject(ObjectOutputStream stream) throws IOException { 42 | stream.defaultWriteObject(); 43 | stream.writeInt(someField + 1000); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/DieselEngine.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.IOException; 4 | import java.io.NotSerializableException; 5 | import java.io.ObjectInputStream; 6 | import java.io.ObjectOutputStream; 7 | 8 | public class DieselEngine extends Engine { 9 | public DieselEngine() { 10 | super("diesel"); 11 | } 12 | 13 | private void writeObject(ObjectOutputStream out) throws IOException { 14 | throw new NotSerializableException("DieselEngine isn't serializable!"); 15 | } 16 | 17 | private void readObject(ObjectInputStream in) throws IOException { 18 | throw new NotSerializableException("DieselEngine isn't serializable!"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/Engine.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Engine implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | 8 | private String model; 9 | 10 | public Engine(String model) { 11 | this.model = model; 12 | } 13 | 14 | public String getModel() { 15 | return model; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | 10 | public class Human implements Serializable { 11 | private static final long serialVersionUID = 1L; 12 | 13 | private transient Integer age; 14 | private String name; 15 | 16 | public Human(String name, Integer age) { 17 | this.age = age; 18 | this.name = name; 19 | } 20 | 21 | public Integer getAge() { 22 | return age; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public static void main(String[] args) throws IOException, ClassNotFoundException { 30 | Human human = new Human("Krzysiek", 21); 31 | 32 | try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("human.bin"))) { 33 | output.writeObject(human); 34 | } 35 | 36 | try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("human.bin"))) { 37 | Human readHuman = (Human) input.readObject(); 38 | System.out.println(readHuman.getName()); 39 | System.out.println(readHuman.getAge()); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | 9 | public class Main { 10 | public static void main(String[] args) throws IOException, ClassNotFoundException { 11 | simpleSerialization(); 12 | graphSerialisation(); 13 | } 14 | 15 | private static void graphSerialisation() throws IOException, ClassNotFoundException { 16 | Tyre[] tyres = new Tyre[] {new Tyre(16), new Tyre(16), new Tyre(16), new Tyre(16)}; 17 | Engine engine = new Engine("some model"); 18 | Car serializedCar = new Car(engine, tyres); 19 | try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("object-graph.bin"))) { 20 | outputStream.writeObject(serializedCar); 21 | } 22 | 23 | Car deserializedCar = null; 24 | try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("object-graph.bin"))) { 25 | deserializedCar = (Car) inputStream.readObject(); 26 | System.out.println(deserializedCar.getEngine().getModel()); 27 | System.out.println(deserializedCar.getTyres().length); 28 | } 29 | 30 | System.out.println(serializedCar == deserializedCar); 31 | } 32 | 33 | private static void simpleSerialization() throws IOException, ClassNotFoundException { 34 | try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("objects.bin"))) { 35 | outputStream.writeObject(Integer.valueOf(1)); 36 | outputStream.writeObject(Integer.valueOf(2)); 37 | } 38 | 39 | try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("objects.bin"))) { 40 | Integer number = (Integer) inputStream.readObject(); 41 | System.out.println(number); 42 | number = (Integer) inputStream.readObject(); 43 | System.out.println(number); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/StaticSerialization.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | 10 | public class StaticSerialization implements Serializable{ 11 | private static final long serialVersionUID = 1L; 12 | 13 | public static int someField = 100; 14 | 15 | public static void main(String[] args) throws IOException, ClassNotFoundException { 16 | firstExecution(); 17 | secondExecution(); 18 | } 19 | 20 | private static void secondExecution() throws IOException, ClassNotFoundException { 21 | try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("static.bin"))) { 22 | StaticSerialization otherObject = (StaticSerialization) input.readObject(); 23 | System.out.println(otherObject.someField); 24 | } 25 | } 26 | 27 | private static void firstExecution() throws IOException { 28 | StaticSerialization object = new StaticSerialization(); 29 | object.someField = 200; 30 | System.out.println(object.someField); 31 | 32 | try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("static.bin"))) { 33 | output.writeObject(object); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/Tyre.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Tyre implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | 8 | private int size; 9 | private boolean isFlat; 10 | 11 | public Tyre(int size) { 12 | this.size = size; 13 | } 14 | 15 | public int getSize() { 16 | return size; 17 | } 18 | 19 | public boolean isFlat() { 20 | return isFlat; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/exercise/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization.exercise; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | import java.util.Calendar; 10 | 11 | public class Human implements Serializable { 12 | private String name; 13 | private transient int age; 14 | 15 | public Human(String name, int age) { 16 | this.name = name; 17 | this.age = age; 18 | } 19 | 20 | public static void main(String[] args) throws IOException, ClassNotFoundException { 21 | try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("age.bin"))) { 22 | output.writeObject(new Human("Piotrek", 23)); 23 | } 24 | try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("age.bin"))) { 25 | Human human = (Human) input.readObject(); 26 | System.out.println(human.name); 27 | System.out.println(human.age); 28 | } 29 | } 30 | 31 | private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 32 | stream.defaultReadObject(); 33 | int birthYear = stream.readInt(); 34 | age = Calendar.getInstance().get(Calendar.YEAR) - birthYear; 35 | } 36 | 37 | private void writeObject(ObjectOutputStream stream) throws IOException { 38 | stream.defaultWriteObject(); 39 | int birthYear = Calendar.getInstance().get(Calendar.YEAR) - age; 40 | stream.writeInt(birthYear); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /18_serializacja/src/main/java/pl/samouczekprogramisty/kursjava/serialization/exercise/NamesDatabase.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.serialization.exercise; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.Scanner; 11 | 12 | public class NamesDatabase { 13 | private static final String STOP = "-"; 14 | 15 | @SuppressWarnings("unchecked") 16 | public static void main(String[] args) throws IOException, ClassNotFoundException { 17 | try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("names.db"))) { 18 | output.writeObject(getNamesFromUser()); 19 | } 20 | List names = null; 21 | try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("names.db"))) { 22 | names = (List) input.readObject(); 23 | } 24 | for (String name : names) { 25 | System.out.println(name); 26 | } 27 | } 28 | 29 | private static List getNamesFromUser() throws IOException { 30 | Scanner input = new Scanner(System.in); 31 | String name = null; 32 | List names = new LinkedList<>(); 33 | while (true) { 34 | System.out.println("Podaj imie: "); 35 | name = input.nextLine(); 36 | if (name.equals(STOP)) { 37 | break; 38 | } 39 | names.add(name); 40 | } 41 | return names; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/enumclass/TshirtSize.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.enumclass; 2 | 3 | public enum TshirtSize { 4 | S(48, 71, 36), 5 | M(52, 74, 38), 6 | L(56, 76, 41), 7 | XL(61, 79, 41); 8 | 9 | private int chestWidth; 10 | private int shirtLength; 11 | private int sleeveLength; 12 | 13 | TshirtSize(int chestWidth, int shirtLength, int sleeveLength) { 14 | this.chestWidth = chestWidth; 15 | this.shirtLength = shirtLength; 16 | this.sleeveLength = sleeveLength; 17 | } 18 | 19 | public int getChestWidth() { 20 | return chestWidth; 21 | } 22 | 23 | public int getShirtLength() { 24 | return shirtLength; 25 | } 26 | 27 | public int getSleeveLength() { 28 | return sleeveLength; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/exercise/Computation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.exercise; 2 | 3 | public enum Computation { 4 | ADDITION { 5 | public double perform(double x, double y) { 6 | return x + y; 7 | } 8 | }, 9 | SUBTRACTION { 10 | public double perform(double x, double y) { 11 | return x - y; 12 | } 13 | }, 14 | MULTIPLICATION { 15 | public double perform(double x, double y) { 16 | return x * y; 17 | } 18 | }, 19 | DIVISION { 20 | public double perform(double x, double y) { 21 | return x / y; 22 | } 23 | }; 24 | 25 | public abstract double perform(double x, double y); 26 | 27 | public static void main(String[] args) { 28 | System.out.println("3 + 4 = " + Computation.ADDITION.perform(3, 4)); 29 | System.out.println("3 - 4 = " + Computation.SUBTRACTION.perform(3, 4)); 30 | System.out.println("3 * 4 = " + Computation.MULTIPLICATION.perform(3, 4)); 31 | System.out.println("3 / 4 = " + Computation.DIVISION.perform(3, 4)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/exercise/EyeColour.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.exercise; 2 | 3 | public enum EyeColour { 4 | GREEN, 5 | BLUE, 6 | GRAY, 7 | BROWN 8 | } 9 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/exercise/HairColour.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.exercise; 2 | 3 | public enum HairColour { 4 | BLACK, 5 | BLONDE, 6 | BROWN, 7 | GRAY, 8 | GINGER 9 | } 10 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/exercise/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.exercise; 2 | 3 | public class Human { 4 | private String name; 5 | private int age; 6 | private EyeColour eyeColour; 7 | private HairColour hairColour; 8 | 9 | public Human(String name, int age, EyeColour eyeColour, HairColour hairColour) { 10 | this.name = name; 11 | this.age = age; 12 | this.eyeColour = eyeColour; 13 | this.hairColour = hairColour; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public int getAge() { 21 | return age; 22 | } 23 | 24 | public EyeColour getEyeColour() { 25 | return eyeColour; 26 | } 27 | 28 | public HairColour getHairColour() { 29 | return hairColour; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Human marcin = new Human("Marcin", 31, EyeColour.BLUE, HairColour.BLONDE); 34 | 35 | System.out.println(marcin.getName()); 36 | System.out.println(marcin.getEyeColour()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/simple/Tshirt.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.simple; 2 | 3 | public class Tshirt { 4 | private TshirtSize size; 5 | private String manufacturer; 6 | 7 | public Tshirt(TshirtSize size, String manufacturer) { 8 | this.size = size; 9 | this.manufacturer = manufacturer; 10 | } 11 | 12 | public static void main(String[] args) { 13 | Tshirt tshirt = new Tshirt(TshirtSize.L, "Polex"); 14 | System.out.println(tshirt.size); 15 | 16 | System.out.println(TshirtSize.L == TshirtSize.L); 17 | System.out.println(TshirtSize.L.equals(TshirtSize.L)); 18 | 19 | switch (tshirt.size) { 20 | case S: 21 | System.out.println("Kupiles koszulke w rozmiarze small"); 22 | break; 23 | case M: 24 | System.out.println("Kupiles koszulke w rozmiarze medium"); 25 | break; 26 | case L: 27 | System.out.println("Kupiles koszulke w rozmiarze large"); 28 | break; 29 | case XL: 30 | System.out.println("Kupiles koszulke w rozmiarze extra large"); 31 | break; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/simple/TshirtSize.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.simple; 2 | 3 | public enum TshirtSize { 4 | S, 5 | M, 6 | L, 7 | XL 8 | 9 | } 10 | -------------------------------------------------------------------------------- /19_typ_wyliczeniowy/src/main/java/pl/samouczekprogramisty/kursjava/enums/withinlinemethods/Formatter.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.enums.withinlinemethods; 2 | 3 | public enum Formatter { 4 | CALM { 5 | public String format(String message) { 6 | return "Here is your message: " + message; 7 | } 8 | }, 9 | NERVOUS { 10 | public String format(String message) { 11 | return "ARGH! STOP BOTHERING ME WITH YOUR MESSAGE! " + message + " I'M NOT GOING TO ACCEPT ANYTHING MORE!"; 12 | } 13 | }; 14 | 15 | public abstract String format(String message); 16 | 17 | public static void main(String[] args) { 18 | System.out.println(Formatter.CALM.format("I'm calm :)")); 19 | System.out.println(Formatter.NERVOUS.format("I'm nervous :[")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/AnnotationWithDefaultValues.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD}) 10 | public @interface AnnotationWithDefaultValues { 11 | String firstElement() default "someDefaultValue"; 12 | int [] secondElement() default {1, 2, 3}; 13 | float thirdElement(); 14 | } 15 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/AnnotationsForCompiler.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class AnnotationsForCompiler { 7 | public static void main(String[] args) { 8 | List listOfUndefinedObjects = new ArrayList(); 9 | @SuppressWarnings("uncecked") 10 | List listOfIntegers = (List) listOfUndefinedObjects; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/EqualsOverride.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations; 2 | 3 | 4 | public class EqualsOverride { 5 | public boolean equal(Object obj) { 6 | return true; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations; 2 | 3 | public class Main { 4 | 5 | /** 6 | * Multipies number by 2 7 | * @param parameter number that should be multipied 8 | * @return parameter multipied by 2 9 | */ 10 | public int timesTwo(int parameter) { 11 | return parameter * 2; 12 | } 13 | 14 | @Override 15 | public boolean equals(Object obj) { 16 | return super.equals(obj); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/SampleFieldAnnotation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations; 2 | 3 | 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Target; 6 | 7 | @Target(ElementType.FIELD) 8 | public @interface SampleFieldAnnotation { 9 | String id(); 10 | } 11 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/exercise/AnnotationProcessor.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations.exercise; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | @MyDocumentation(comment = "Sample for exercise") 10 | public class AnnotationProcessor { 11 | 12 | private static List SKIP_METHODS = Arrays.asList("equals", "toString", "hashCode", "annotationType"); 13 | 14 | public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { 15 | for (Annotation classAnnotation : AnnotationProcessor.class.getDeclaredAnnotations()) { 16 | printAnnotationDetails(classAnnotation); 17 | } 18 | } 19 | 20 | private static void printAnnotationDetails(Annotation annotation) throws InvocationTargetException, IllegalAccessException { 21 | System.out.println("Znalazłem adnotacje: " + annotation); 22 | for (Method method : annotation.annotationType().getMethods()) { 23 | if (SKIP_METHODS.contains(method.getName())) { 24 | continue; 25 | } 26 | System.out.println("Nazwa elementu: " + method.getName()); 27 | System.out.println("Wartosc domyslna elementu: " + method.getDefaultValue()); 28 | System.out.println(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /20_adnotacje/src/main/java/pl/samouczekprogramisty/kursjava/annotations/exercise/MyDocumentation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.annotations.exercise; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.TYPE, ElementType.METHOD}) 10 | public @interface MyDocumentation { 11 | String author() default "Marcin Pietraszek"; 12 | String comment(); 13 | } 14 | -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/AnonymousCheating.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner; 2 | 3 | import java.lang.reflect.InvocationTargetException; 4 | 5 | public class AnonymousCheating { 6 | 7 | private interface SomeInterface { 8 | void doSomethingUseful(); 9 | } 10 | 11 | public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { 12 | SomeInterface anonymousInstance = new SomeInterface() { 13 | @Override 14 | public void doSomethingUseful() { 15 | System.out.println("I'm doing something useful!"); 16 | } 17 | }; 18 | 19 | anonymousInstance.doSomethingUseful(); 20 | System.out.println(anonymousInstance.getClass()); 21 | } 22 | } -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/AnonymousClasses.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner; 2 | 3 | public class AnonymousClasses { 4 | public static class Robot { 5 | private final GreetingModule greetingModule; 6 | 7 | public Robot(GreetingModule greetingModule) { 8 | this.greetingModule = greetingModule; 9 | } 10 | 11 | public void saySomething() { 12 | greetingModule.sayHello(); 13 | } 14 | } 15 | 16 | public interface GreetingModule { 17 | void sayHello(); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Robot jan = new Robot(new GreetingModule() { 22 | @Override 23 | public void sayHello() { 24 | System.out.println("dzien dobry"); 25 | } 26 | }); 27 | 28 | Robot john = new Robot(new GreetingModule() { 29 | @Override 30 | public void sayHello() { 31 | System.out.println("good morning" ); 32 | } 33 | }); 34 | 35 | jan.saySomething(); 36 | john.saySomething(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/Main.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | innerClassInstantiation(); 10 | staticInnerClassInstantiation(); 11 | localClassInstantiation(args); 12 | mapIterationExampe(); 13 | } 14 | 15 | private static void mapIterationExampe() { 16 | Map dayInMonths = new HashMap<>(); 17 | dayInMonths.put("styczen", 31); 18 | dayInMonths.put("luty", 28); 19 | dayInMonths.put("marzec", 31); 20 | 21 | for(Map.Entry entry : dayInMonths.entrySet()) { 22 | System.out.println(entry.getKey() + " ma " + entry.getValue() + " dni."); 23 | } 24 | } 25 | 26 | private static void localClassInstantiation(String[] args) { 27 | class LocalClass { 28 | @Override 29 | public String toString() { 30 | return "Argumenty metody: " + Arrays.toString(args); 31 | } 32 | } 33 | LocalClass localClassInstance = new LocalClass(); 34 | System.out.println(localClassInstance); 35 | } 36 | 37 | private static void innerClassInstantiation() { 38 | OuterClass outerClass = new OuterClass(); 39 | OuterClass.InnerClass instance1 = outerClass.instantiate(); 40 | OuterClass.InnerClass instance2 = outerClass.new InnerClass(); 41 | } 42 | 43 | private static void staticInnerClassInstantiation() { 44 | OuterClass2 outerClass = new OuterClass2(); 45 | OuterClass2.InnerClass2 instance1 = outerClass.instantiate(); 46 | OuterClass2.InnerClass2 instance2 = new OuterClass2.InnerClass2(); 47 | } 48 | } -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/OuterClass.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner; 2 | 3 | public class OuterClass { 4 | public class InnerClass { 5 | } 6 | 7 | public enum InnerEnum { 8 | } 9 | 10 | public interface InnerInterface { 11 | } 12 | 13 | public InnerClass instantiate() { 14 | return new InnerClass(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/OuterClass2.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner; 2 | 3 | public class OuterClass2 { 4 | public static class InnerClass2 { 5 | } 6 | 7 | public InnerClass2 instantiate() { 8 | return new InnerClass2(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/VariablesUsedInInnerClasses.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner; 2 | 3 | public class VariablesUsedInInnerClasses { 4 | public static void main(String[] args) { 5 | final String finalVariable = "final variable"; 6 | String effectivelyFinalVariable = "effectively final variable"; 7 | String nonFinalVariable = "non final variable"; 8 | 9 | class InnerClass { 10 | public void saySomething() { 11 | System.out.println(finalVariable); 12 | System.out.println(effectivelyFinalVariable); 13 | } 14 | } 15 | 16 | InnerClass instance = new InnerClass(); 17 | instance.saySomething(); 18 | 19 | nonFinalVariable = "new value"; 20 | } 21 | } 22 | 23 | 24 | class Sprawdzacz { 25 | final String finalVariable = "final variable"; 26 | String effectivelyFinalVariable = "effectively final variable"; 27 | String nonFinalVariable = "non final variable"; 28 | 29 | public class InnerClass { 30 | public void saySomething() { 31 | System.out.println(finalVariable); 32 | System.out.println(effectivelyFinalVariable); 33 | System.out.println(nonFinalVariable); 34 | } 35 | } 36 | 37 | public void someMethod(){ 38 | InnerClass innerClass = new InnerClass(); 39 | innerClass.saySomething(); 40 | nonFinalVariable = "new value"; 41 | innerClass.saySomething(); 42 | } 43 | 44 | public static void main(String[] args) { 45 | Sprawdzacz sprawdzacz = new Sprawdzacz(); 46 | sprawdzacz.someMethod(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/exercise/HansRobot.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner.exercise; 2 | 3 | import pl.samouczekprogramisty.kursjava.inner.AnonymousClasses; 4 | 5 | public class HansRobot { 6 | public static void main(String[] args) { 7 | AnonymousClasses.Robot hans = new AnonymousClasses.Robot(new AnonymousClasses.GreetingModule() { 8 | @Override 9 | public void sayHello() { 10 | System.out.println("guten morgen"); 11 | } 12 | }); 13 | 14 | hans.saySomething(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /21_klasy_wewnetrzne/src/main/java/pl/samouczekprogramisty/kursjava/inner/exercise/SortingExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.inner.exercise; 2 | 3 | import java.util.Collections; 4 | import java.util.Comparator; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import java.util.Scanner; 8 | 9 | public class SortingExample { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | int counter = 5; 13 | List words = new LinkedList<>(); 14 | 15 | while(counter != 0) { 16 | System.out.println("Podaj slowo: "); 17 | words.add(input.next()); 18 | counter--; 19 | } 20 | 21 | System.out.println("Przed sortowaniem: "); 22 | printList(words); 23 | Collections.sort(words, new Comparator() { 24 | @Override 25 | public int compare(String word1, String word2) { 26 | return word1.length() - word2.length(); 27 | } 28 | }); 29 | System.out.println("Po sortowaniu: "); 30 | printList(words); 31 | } 32 | 33 | private static void printList(List words) { 34 | for(String word : words) { 35 | System.out.println(word); 36 | } 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /22_testy_jednostkowe/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | testCompile group: 'junit', name: 'junit', version: '4.12' 3 | } -------------------------------------------------------------------------------- /22_testy_jednostkowe/src/main/java/pl/samouczekprogramisty/kursjava/number/Range.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.number; 2 | 3 | public class Range { 4 | private final long lowerBound; 5 | private final long upperBound; 6 | 7 | public Range(long lowerBound, long upperBound) { 8 | if (lowerBound > upperBound) { 9 | throw new IllegalArgumentException("lowerBound is bigger than upperBound!"); 10 | } 11 | this.lowerBound = lowerBound; 12 | this.upperBound = upperBound; 13 | } 14 | 15 | public boolean isInRange(long number) { 16 | return number >= lowerBound && number <= upperBound; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /22_testy_jednostkowe/src/main/java/pl/samouczekprogramisty/kursjava/shop/exercise/Item.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.shop.exercise; 2 | 3 | public final class Item implements Comparable { 4 | private final String name; 5 | private final double price; 6 | 7 | public Item(String name, double price) { 8 | this.name = name; 9 | this.price = price; 10 | } 11 | 12 | public double getPrice() { 13 | return price; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | @Override 21 | public boolean equals(Object otherObject) { 22 | if (this == otherObject) { 23 | return true; 24 | } 25 | if (otherObject == null || ! (otherObject instanceof Item)) { 26 | return false; 27 | } 28 | 29 | Item item = (Item) otherObject; 30 | 31 | if (Double.compare(item.price, price) != 0) { 32 | return false; 33 | } 34 | return name.equals(item.name); 35 | } 36 | 37 | @Override 38 | public int hashCode() { 39 | return 31 * name.hashCode(); 40 | } 41 | 42 | @Override 43 | public int compareTo(Item other) { 44 | if (other == null) { 45 | return 1; 46 | } 47 | int comparision = this.getName().compareTo(other.getName()); 48 | if (comparision != 0) { 49 | return comparision; 50 | } 51 | return Double.compare(this.getPrice(), other.getPrice()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /22_testy_jednostkowe/src/test/java/pl/samouczekprogramisty/kursjava/number/RangeTest.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.number; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | import static org.junit.Assert.assertFalse; 8 | import static org.junit.Assert.assertTrue; 9 | import static org.junit.Assert.fail; 10 | 11 | public class RangeTest { 12 | private Range range; 13 | 14 | @Before 15 | public void setUp() { 16 | range = new Range(10, 20); 17 | } 18 | 19 | @Test 20 | public void shouldSayThat15rIsInRange() { 21 | assertTrue(range.isInRange(15)); 22 | } 23 | 24 | @Test 25 | public void shouldSayThat5IsntInRange() { 26 | assertFalse(range.isInRange(5)); 27 | } 28 | 29 | @Test(expected = IllegalArgumentException.class) 30 | public void shouldThrownIllegalArgumentExceptionOnWrongParameters() { 31 | new Range(20, 10); 32 | } 33 | 34 | @Test 35 | public void shouldHaveProperErrorMessage() { 36 | try { 37 | new Range(20, 10); 38 | fail("Exception wasn't thrown!"); 39 | } 40 | catch (IllegalArgumentException exception) { 41 | assertEquals("lowerBound is bigger than upperBound!", exception.getMessage()); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /22_testy_jednostkowe/src/test/java/pl/samouczekprogramisty/kursjava/number/RangeWithoutSetup.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.number; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertFalse; 6 | import static org.junit.Assert.assertTrue; 7 | 8 | public class RangeWithoutSetup { 9 | @Test 10 | public void shouldSayThat15rIsInRange() { 11 | Range range = new Range(10, 20); 12 | assertTrue(range.isInRange(15)); 13 | } 14 | 15 | @Test 16 | public void shouldSayThat5IsntInRange() { 17 | Range range = new Range(10, 20); 18 | assertFalse(range.isInRange(5)); 19 | } 20 | } -------------------------------------------------------------------------------- /22_testy_jednostkowe/src/test/java/pl/samouczekprogramisty/kursjava/number/TestLifecycle.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.number; 2 | 3 | import org.junit.After; 4 | import org.junit.AfterClass; 5 | import org.junit.Before; 6 | import org.junit.BeforeClass; 7 | import org.junit.Test; 8 | 9 | public class TestLifecycle { 10 | @Before 11 | public void setUp() { 12 | System.out.println("set up"); 13 | System.out.flush(); 14 | } 15 | 16 | @After 17 | public void tearDown() { 18 | System.out.println("tear down"); 19 | System.out.flush(); 20 | } 21 | 22 | @BeforeClass 23 | public static void setUpClass() { 24 | System.out.println("set up class"); 25 | System.out.flush(); 26 | } 27 | 28 | @AfterClass 29 | public static void tearDownClass() { 30 | System.out.println("tear down class"); 31 | System.out.flush(); 32 | } 33 | 34 | @Test 35 | public void test1() { 36 | System.out.println("test 1"); 37 | System.out.flush(); 38 | } 39 | 40 | @Test 41 | public void test2() { 42 | System.out.println("test 2"); 43 | System.out.flush(); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /22_testy_jednostkowe/src/test/java/pl/samouczekprogramisty/kursjava/shop/exercise/ItemTest.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.shop.exercise; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | import static org.junit.Assert.assertNotEquals; 7 | 8 | 9 | public class ItemTest { 10 | 11 | @Test 12 | public void twoItemsWIthTheSamePriceAndNameShouldBeEqual() { 13 | assertEquals(new Item("item", 123.12), new Item("item", 123.12)); 14 | } 15 | 16 | @Test 17 | public void itemsWithDifferentNamesArentEaual() { 18 | assertNotEquals(new Item("item1", 123.12), new Item("item2", 123.12)); 19 | } 20 | 21 | @Test 22 | public void itemsWithDifferentPriceArentEaual() throws Exception { 23 | assertNotEquals(new Item("item", 123.21), new Item("item", 123.12)); 24 | } 25 | 26 | @Test 27 | public void itemsWithTheSameNameShouldHaveTheSameHashCode() { 28 | assertEquals(new Item("item", 123).hashCode(), new Item("item", 321).hashCode()); 29 | } 30 | 31 | @Test 32 | public void itemsWithDifferentNameShouldHaveDifferentHashCode() { 33 | assertNotEquals(new Item("item1", 123).hashCode(), new Item("item2", 321).hashCode()); 34 | } 35 | 36 | @Test 37 | public void itemsWithDifferentPriceAndTheSameNameShouldBeOrdered() { 38 | assertEquals(-1, new Item("item1", 0.1).compareTo(new Item("item1", 0.2))); 39 | } 40 | } -------------------------------------------------------------------------------- /23_wyrazenia_regularne/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | testCompile group: 'junit', name: 'junit', version: '4.12' 3 | } -------------------------------------------------------------------------------- /23_wyrazenia_regularne/src/main/java/pl/samouczekprogramisty/kursjava/regexp/SimpleNameRegexp.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.regexp; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | public class SimpleNameRegexp { 7 | public static void main(String[] args) { 8 | simplePatternUsage(); 9 | } 10 | 11 | private static void simplePatternUsage() { 12 | Pattern compiledPattern = Pattern.compile("Marcin"); 13 | Matcher matcher = compiledPattern.matcher("Nazywam sie Marcin Pietraszek"); 14 | 15 | System.out.println(matcher.find()); 16 | System.out.println(matcher.matches()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /23_wyrazenia_regularne/src/test/java/pl/samouczekprogramisty/kursjava/regexp/exercise/ExerciseTest.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.regexp.exercise; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.regex.Pattern; 6 | 7 | import static org.junit.Assert.assertFalse; 8 | import static org.junit.Assert.assertTrue; 9 | 10 | public class ExerciseTest { 11 | @Test 12 | public void shouldValidateFloatingpointNumber() { 13 | Pattern pattern = Pattern.compile("-?\\d+(,\\d+)?"); 14 | assertTrue(pattern.matcher("123,2341515132135").matches()); 15 | assertTrue(pattern.matcher("-10").matches()); 16 | assertFalse(pattern.matcher("18-12").matches()); 17 | assertFalse(pattern.matcher("123,").matches()); 18 | } 19 | 20 | @Test 21 | public void shouldValidateHouseNumber() { 22 | Pattern pattern = Pattern.compile("\\d+[A-Z]?\\\\\\d+[A-Z]?"); 23 | assertTrue(pattern.matcher("123\\2A").matches()); 24 | assertTrue(pattern.matcher("24B\\3").matches()); 25 | assertTrue(pattern.matcher("12\\5").matches()); 26 | assertFalse(pattern.matcher("abc\\cba").matches()); 27 | assertFalse(pattern.matcher("12").matches()); 28 | } 29 | 30 | @Test 31 | public void shouldValidateCityName() { 32 | Pattern pattern = Pattern.compile("[A-Z][a-z]+([ -][A-Z][a-z]+)?"); 33 | assertTrue(pattern.matcher("Wroclaw").matches()); 34 | assertTrue(pattern.matcher("Zielona Gora").matches()); 35 | assertTrue(pattern.matcher("Bielsko-Biala").matches()); 36 | assertFalse(pattern.matcher("Ptysiow123").matches()); 37 | assertFalse(pattern.matcher("wroclaw").matches()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /24_wyrazenia_regularne/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | testCompile group: 'junit', name: 'junit', version: '4.12' 3 | } -------------------------------------------------------------------------------- /25_linia_polecen/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.5' 3 | } 4 | 5 | -------------------------------------------------------------------------------- /25_linia_polecen/src/main/java/pl/samouczekprogramisty/commandline/CheckName.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.commandline; 2 | 3 | 4 | import java.util.Scanner; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | 8 | public class CheckName { 9 | public static void main(String ... args) { 10 | System.out.println("Podaj zdanie"); 11 | Scanner scanner = new Scanner(System.in); 12 | String sentence = scanner.nextLine(); 13 | 14 | if (StringUtils.containsIgnoreCase(sentence, "Marcin")) { 15 | System.out.println("To zdanie zawiera moje imie!"); 16 | } 17 | else { 18 | System.out.println("To zdanie nie zawiera mojego imienia!"); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /25_linia_polecen/src/main/java/pl/samouczekprogramisty/commandline/DisplayName.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.commandline; 2 | 3 | public class DisplayName { 4 | public static void main(String ... args) { 5 | System.out.println("Marcin pakiet"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /26_lancuchy_znakow/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | testCompile group: 'junit', name: 'junit', version: '4.12' 3 | } -------------------------------------------------------------------------------- /26_lancuchy_znakow/src/main/java/pl/samouczekprogramisty/kursjava/strings/StringConcatenation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.strings; 2 | 3 | public class StringConcatenation { 4 | 5 | public void intermediaryStringObjects() { 6 | String some = "some"; 7 | String space = " "; 8 | String random = "random"; 9 | String string = "string"; 10 | 11 | String someString = some + space + random + space + string; 12 | } 13 | 14 | public void plusSingnBehaviour() { 15 | System.out.println(1 + 2 + "test"); // 3test 16 | System.out.println("test" + 1 + 2); // test12 17 | } 18 | 19 | public void compilerConcatenationFiddling() { 20 | String some = "some"; 21 | String space = " "; 22 | String random = "random"; 23 | String string = "string"; 24 | 25 | StringBuilder x = new StringBuilder(); 26 | x.append(some); 27 | x.append(space); 28 | x.append(random); 29 | x.append(space); 30 | x.append(string); 31 | 32 | String someString = x.toString(); 33 | } 34 | 35 | public void loopWithoutCompilerIngerence() { 36 | String finalString = ""; 37 | for (int counter = 0; counter < 1000000; counter++) { 38 | finalString = finalString + " " + counter; 39 | } 40 | } 41 | 42 | public void loopWithCompilerIngerence() { 43 | String finalString = ""; 44 | for (int counter = 0; counter < 1000000; counter++) { 45 | StringBuilder x = new StringBuilder(); 46 | x.append(finalString); 47 | x.append(" "); 48 | x.append(counter); 49 | finalString = x.toString(); 50 | } 51 | } 52 | 53 | public void optimizedLoop() { 54 | StringBuilder finalStringBuilder = new StringBuilder(); 55 | for (int counter = 0; counter < 1000000; counter++) { 56 | finalStringBuilder.append(" "); 57 | finalStringBuilder.append(counter); 58 | } 59 | String finalString = finalStringBuilder.toString(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /26_lancuchy_znakow/src/test/java/pl/samouczekprogramisty/kursjava/strings/StringCacheTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SamouczekProgramisty/KursJava/30d5b6d46982d023672ec75d506e7b1db1bdac9d/26_lancuchy_znakow/src/test/java/pl/samouczekprogramisty/kursjava/strings/StringCacheTest.class -------------------------------------------------------------------------------- /26_lancuchy_znakow/src/test/java/pl/samouczekprogramisty/kursjava/strings/StringCacheTest.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.strings; 2 | 3 | 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | import static org.junit.Assert.assertNotSame; 8 | import static org.junit.Assert.assertSame; 9 | 10 | public class StringCacheTest { 11 | 12 | @Test 13 | public void twoLiterals() { 14 | String someVariable = "samouczek programisty"; 15 | String otherVariable = "samouczek programisty"; 16 | 17 | assertEquals(someVariable, otherVariable); 18 | assertSame(someVariable, otherVariable); 19 | } 20 | 21 | @Test 22 | public void twoNewObjects() { 23 | String someVariable = new String("samouczek programisty"); 24 | String otherVariable = new String("samouczek programisty"); 25 | 26 | assertEquals(someVariable, otherVariable); 27 | assertNotSame(someVariable, otherVariable); 28 | } 29 | 30 | @Test 31 | public void literalAndInternedObject() { 32 | String someVariable = "samouczek programisty"; 33 | String otherVariable = new String("samouczek programisty").intern(); 34 | 35 | assertEquals(someVariable, otherVariable); 36 | assertSame(someVariable, otherVariable); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /27_lancuchy_znakow_formatowanie/src/main/java/pl/samouczekprogramisty/kursjava/strings/formatting/ExerciseSolution.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.strings.formatting; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.InputStreamReader; 8 | import java.net.URL; 9 | import java.util.Iterator; 10 | 11 | public class ExerciseSolution implements Iterable{ 12 | 13 | private final BufferedReader reader; 14 | 15 | private Object[] currentLine; 16 | 17 | public ExerciseSolution(InputStream inputStream) { 18 | reader = new BufferedReader(new InputStreamReader(inputStream)); 19 | } 20 | 21 | public static void main(String[] args) throws IOException { 22 | URL resource = ExerciseSolution.class.getResource(File.separator + "test.csv"); 23 | try (InputStream inputStream = resource.openStream()) { 24 | for (Object[] columns : new ExerciseSolution(inputStream)) { 25 | System.out.format("| %-8s | %7.2f | %12s |%n", columns); 26 | } 27 | } 28 | } 29 | 30 | @Override 31 | public Iterator iterator() { 32 | return new Iterator() { 33 | @Override 34 | public boolean hasNext() { 35 | String line = null; 36 | try { 37 | line = reader.readLine(); 38 | } catch (IOException e) { 39 | throw new RuntimeException(e); 40 | } 41 | if (line == null) { 42 | currentLine = null; 43 | return false; 44 | } 45 | String[] splittedLine = line.split(","); 46 | currentLine = new Object[] { 47 | splittedLine[0], 48 | Float.valueOf(splittedLine[1]), 49 | splittedLine[2] 50 | }; 51 | 52 | return true; 53 | } 54 | 55 | @Override 56 | public Object[] next() { 57 | return currentLine; 58 | } 59 | }; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /27_lancuchy_znakow_formatowanie/src/main/java/pl/samouczekprogramisty/kursjava/strings/formatting/StringFormatting.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.strings.formatting; 2 | 3 | import java.util.Formatter; 4 | import java.util.Locale; 5 | 6 | public class StringFormatting { 7 | 8 | public static void main(String[] args) { 9 | simpleFormatterExample(); 10 | simplifiedFormatterExample(); 11 | indexArgument(); 12 | widthArgument(); 13 | precisionArgument(); 14 | localeExamples(); 15 | } 16 | 17 | private static void localeExamples() { 18 | double someNumber = 12345.12; 19 | System.out.format(Locale.US, "%,.2f%n", someNumber); 20 | System.out.format(Locale.GERMAN, "%,.2f%n", someNumber); 21 | System.out.format(Locale.forLanguageTag("PL"), "%,.2f%n", someNumber); 22 | } 23 | 24 | private static void simpleFormatterExample() { 25 | Formatter formatter = new Formatter(); 26 | formatter.format("Samouczek Programisty istnieje od %d roku. Wszystkie artykuły pisze %s.", 2015, "Marcin"); 27 | String formattedString = formatter.toString(); 28 | System.out.println(formattedString); 29 | } 30 | 31 | private static void simplifiedFormatterExample() { 32 | System.out.format("Samouczek Programisty istnieje od %d roku. Wszystkie artykuły pisze %s.%n", 2015, "Marcin"); 33 | } 34 | 35 | private static void complicatedExample() { 36 | System.out.format("%2$08.3f %3$(,08.3f %s", 123, -1.234567, -2.123456, 123); 37 | System.out.println(); 38 | } 39 | 40 | private static void indexArgument() { 41 | System.out.format("%2$s %1$s %1$s%n", "[pierwszy argument]", "[drugi argument]"); 42 | } 43 | 44 | private static void widthArgument() { 45 | System.out.format("[%10s] [%3s]%n", "test", "test"); 46 | } 47 | 48 | private static void precisionArgument() { 49 | double x = 1.1234567890123; 50 | System.out.format("[%.10f] [%.3f] [%f]%n", x, x, x); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /27_lancuchy_znakow_formatowanie/src/main/resources/test.csv: -------------------------------------------------------------------------------- 1 | Piotrek,123.12,poniedziałek 2 | Tomek,321.3,wtorek 3 | Marcin,-123.12,środa 4 | Wojtek,-3.123,czwartek -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/Checker.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions; 2 | 3 | public interface Checker { 4 | 5 | boolean check(T object); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/SideEffectMethod.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions; 2 | 3 | public interface SideEffectMethod { 4 | void sideEffectMethod(); 5 | } 6 | -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/Solution.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public static void main(String[] args) throws IOException { 13 | 14 | try (InputStream in = new FileInputStream("/home/mapi/Desktop/04_input.txt")) { 15 | Scanner scanner = new Scanner(in); 16 | // Scanner scanner = new Scanner(System.in); 17 | int howManyTests = scanner.nextInt(); 18 | System.out.println(howManyTests); 19 | for (int testIndex = 0; testIndex < howManyTests; testIndex++) { 20 | int howManyBoxes = scanner.nextInt(); 21 | long possibleMoves = 0; 22 | for (int boxIndex = 0; boxIndex < howManyBoxes; boxIndex++) { 23 | int coinsInBox = scanner.nextInt(); 24 | possibleMoves += (boxIndex * coinsInBox) % 2; 25 | possibleMoves %= 2; 26 | } 27 | if (possibleMoves == 0) { 28 | System.out.println("First"); 29 | } 30 | else if (possibleMoves % 2 == 0) { 31 | System.out.println("Second"); 32 | } 33 | else { 34 | System.out.println("First"); 35 | } 36 | } 37 | } 38 | 39 | System.out.println(3 / 2); 40 | System.out.println(3 % 2); 41 | System.out.println(4 / 2); 42 | System.out.println(4 % 2); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/exercise/Human.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions.exercise; 2 | 3 | public class Human { 4 | 5 | private int age; 6 | private String name; 7 | 8 | Human(int age, String name) { 9 | this.age = age; 10 | this.name = name; 11 | } 12 | 13 | int getAge() { 14 | return age; 15 | } 16 | 17 | String getName() { 18 | return name; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/exercise/HumanCreation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions.exercise; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | public class HumanCreation { 6 | 7 | public static void main(String[] args) { 8 | BiFunction humanConstructor = Human::new; 9 | Human human = humanConstructor.apply(25, "Zenek"); 10 | System.out.println(human.getAge()); 11 | System.out.println(human.getName()); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/exercise/MethodReferenceExercise.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions.exercise; 2 | 3 | import java.util.function.BiPredicate; 4 | import java.util.function.Predicate; 5 | import java.util.function.Supplier; 6 | 7 | public class MethodReferenceExercise { 8 | 9 | public static void main(String[] args) { 10 | Supplier objectCreator = Object::new; 11 | // same as new Object() 12 | Object objectInstance = objectCreator.get(); 13 | System.out.println(objectInstance); 14 | 15 | BiPredicate equalsMethodOnClass = Object::equals; 16 | // same as objectInstace.equals(new Ojbect()) 17 | System.out.println(equalsMethodOnClass.test(objectInstance, new Object())); 18 | 19 | Predicate equalsMethodOnObject = objectInstance::equals; 20 | // same as objectInstace.equals(new Ojbect()) 21 | System.out.println(equalsMethodOnObject.test(new Object())); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /28_wyrazenia_lambda/src/main/java/pl/samouczekprogramisty/kursjava/lambdaexpressions/exercise/StringSorting.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.lambdaexpressions.exercise; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | public class StringSorting { 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | System.out.println("Podaj 4 lancuchy znakow oddzielajac je znakiem nowej linii:"); 12 | List strings = new ArrayList<>(); 13 | 14 | for (int i = 0; i < 4; i++) { 15 | strings.add(scanner.nextLine()); 16 | } 17 | 18 | System.out.println(strings); 19 | strings.sort((a, b) -> b.length() - a.length()); 20 | // strings.sort(Comparator.comparingInt(String::length).reversed()); 21 | System.out.println(strings); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/encapsulated/EncapsulatedVisitCounter.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.encapsulated; 2 | 3 | public class EncapsulatedVisitCounter { 4 | 5 | private int userCount = 0; 6 | 7 | public void increment() { 8 | userCount++; 9 | } 10 | 11 | public int getUserCount() { 12 | return userCount; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/exercise/bank/Account.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.exercise.bank; 2 | 3 | public interface Account { 4 | 5 | void deposit(int amount); 6 | 7 | void withdraw(int amount); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/exercise/bank/Bank.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.exercise.bank; 2 | 3 | public class Bank implements BankTransfer { 4 | 5 | public final int TRANSFER_FEE = 1; 6 | 7 | @Override 8 | public void transfer(BankAccount from, BankAccount to, int amount) { 9 | if (from.balance < amount + TRANSFER_FEE) { 10 | throw new IllegalStateException("Niewystarczajaca ilosc scrodkow!"); 11 | } 12 | from.withdraw(amount + TRANSFER_FEE); 13 | to.deposit(amount); 14 | } 15 | 16 | public BankAccount openAccount() { 17 | return new BankAccount(); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Bank bank = new Bank(); 22 | BankAccount account1 = bank.openAccount(); 23 | BankAccount account2 = bank.openAccount(); 24 | 25 | account1.deposit(100); 26 | account2.deposit(50); 27 | 28 | bank.transfer(account1, account2, 65); 29 | 30 | System.out.println(account1.getBalance()); 31 | System.out.println(account2.getBalance()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/exercise/bank/BankAccount.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.exercise.bank; 2 | 3 | class BankAccount implements Account { 4 | 5 | int balance; 6 | 7 | BankAccount() { 8 | this(0); 9 | } 10 | 11 | BankAccount(int balance) { 12 | this.balance = balance; 13 | } 14 | 15 | @Override 16 | public void deposit(int amount) { 17 | if (amount <= 0) { 18 | throw new IllegalArgumentException("ammount must be > 0"); 19 | } 20 | balance += amount; 21 | } 22 | 23 | @Override 24 | public void withdraw(int amount) { 25 | if (amount <= 0) { 26 | throw new IllegalArgumentException("ammount must be > 0"); 27 | } 28 | balance -= amount; 29 | } 30 | 31 | public int getBalance() { 32 | return balance; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/exercise/bank/BankTransfer.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.exercise.bank; 2 | 3 | public interface BankTransfer { 4 | 5 | void transfer(BankAccount from, BankAccount to, int amount); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/inheritance/Oak.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.inheritance; 2 | 3 | public class Oak extends Tree { 4 | 5 | @Override 6 | public void prune() { 7 | super.prune(); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/inheritance/Tree.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.inheritance; 2 | 3 | public class Tree { 4 | 5 | protected int height = 12; 6 | 7 | protected void prune() { 8 | if (height > 15) { 9 | height -= 1; 10 | } 11 | } 12 | 13 | public void grow() { 14 | height += 1; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/missing_keyword/Car.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.missing_keyword; 2 | 3 | public class Car { 4 | public static final double FUEL_TANK_CAPACITY = 50.0; 5 | 6 | double fuelLevel = 12.5; 7 | 8 | } 9 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/missing_keyword/FuelStation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.missing_keyword; 2 | 3 | public class FuelStation { 4 | 5 | public void fillUp(Car car) { 6 | double toFill = Car.FUEL_TANK_CAPACITY - car.fuelLevel; 7 | System.out.println("Tankuje " + toFill + " litrow."); 8 | car.fuelLevel = Car.FUEL_TANK_CAPACITY; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/protected_keyword/Pen.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.protected_keyword; 2 | 3 | public class Pen { 4 | 5 | protected String color; 6 | 7 | public Pen(String color) { 8 | this.color = color; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/protected_keyword/PenOwner.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.protected_keyword; 2 | 3 | public class PenOwner { 4 | 5 | private Pen pen; 6 | 7 | public PenOwner(Pen pen) { 8 | this.pen = pen; 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return "Mam pioro w kolorze " + pen.color; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/protected_keyword/different_package/BallPen.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.protected_keyword.different_package; 2 | 3 | import pl.samouczekprogramisty.kursjava.accessmodifiers.protected_keyword.Pen; 4 | 5 | public class BallPen extends Pen { 6 | 7 | protected String manufacturer; 8 | 9 | public BallPen(String color, String manufacturer) { 10 | super(color); 11 | this.manufacturer = manufacturer; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return manufacturer + " " + color; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/public_keyword/MaliciousUser.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.public_keyword; 2 | 3 | public class MaliciousUser { 4 | 5 | public void countMyVisit(PublicVisitCounter counter) { 6 | counter.increment(); 7 | counter.userCount = -10; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/public_keyword/PublicVisitCounter.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.public_keyword; 2 | 3 | public class PublicVisitCounter { 4 | 5 | public int userCount = 0; 6 | 7 | public void increment() { 8 | userCount++; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/reflection/BankAccount.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.reflection; 2 | 3 | public class BankAccount { 4 | 5 | private int balance = 100; 6 | 7 | public int getBalance() { 8 | return balance; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /29_modyfikatory_dostepu/src/main/java/pl/samouczekprogramisty/kursjava/accessmodifiers/reflection/Thief.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.accessmodifiers.reflection; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | public class Thief { 6 | 7 | public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { 8 | BankAccount account = new BankAccount(); 9 | System.out.println("Stan konta: " + account.getBalance()); 10 | 11 | Field balance = BankAccount.class.getDeclaredField("balance"); 12 | balance.setAccessible(true); 13 | balance.set(account, -5000); 14 | 15 | System.out.println("Stan konta: " + account.getBalance()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/LazyStreams.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class LazyStreams { 6 | 7 | public static void main(String[] args) { 8 | IntStream numbersStream = IntStream.range(0, 8); 9 | System.out.println("Przed"); 10 | numbersStream = numbersStream.filter(n -> n % 2 == 0); 11 | System.out.println("W trakcie 1"); 12 | numbersStream = numbersStream.map(n -> { 13 | System.out.println("> " + n); 14 | return n; 15 | }); 16 | System.out.println("W trakcie 2"); 17 | numbersStream = numbersStream.limit(2); 18 | System.out.println("W trakcie 3"); 19 | numbersStream.forEach(System.out::println); 20 | System.out.println("Po"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/StreamCreation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.FileReader; 8 | import java.io.Reader; 9 | import java.util.Arrays; 10 | import java.util.LinkedList; 11 | import java.util.Random; 12 | import java.util.regex.Pattern; 13 | import java.util.stream.DoubleStream; 14 | import java.util.stream.IntStream; 15 | import java.util.stream.LongStream; 16 | import java.util.stream.Stream; 17 | 18 | public class StreamCreation { 19 | 20 | public static void main(String[] args) throws FileNotFoundException { 21 | Stream stream1 = new LinkedList().stream(); 22 | Stream stream2 = Arrays.stream(new Integer[]{}); 23 | Stream stream3 = Pattern.compile(".").splitAsStream("some longer sentence"); 24 | 25 | DoubleStream doubles = DoubleStream.of(1, 2, 3); 26 | IntStream ints = IntStream.range(0, 123); 27 | LongStream longs = LongStream.generate(() -> 1L); 28 | 29 | DoubleStream randomDoubles = new Random().doubles(); 30 | IntStream randomInts = new Random().ints(); 31 | LongStream randomLongs = new Random().longs(); 32 | 33 | Stream.empty(); 34 | 35 | try (Stream lines = new BufferedReader(new FileReader("file.txt")).lines()) { 36 | // 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/StreamsGoodPractices.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class StreamsGoodPractices { 6 | public static void main(String[] args) { 7 | readabilityMatters(); 8 | orderMatters(); 9 | } 10 | 11 | private static void readabilityMatters() { 12 | IntStream.range(1950, 2150) 13 | .filter(StreamsGoodPractices::isLeapYear) 14 | .forEach(System.out::println); 15 | 16 | System.out.println("vs"); 17 | 18 | IntStream.range(1950, 2150) 19 | .filter(y -> (y % 4 == 0 && y % 100 != 0) || y % 400 == 0) 20 | .forEach(System.out::println); 21 | } 22 | 23 | public static boolean isLeapYear(int year) { 24 | boolean every4Years = year % 4 == 0; 25 | boolean notEvery100Years = year % 100 != 0; 26 | boolean every400Years = year % 400 == 0; 27 | 28 | return (every4Years && notEvery100Years) || every400Years; 29 | } 30 | 31 | public static void orderMatters() { 32 | int fastNumber = IntStream.range(1950, 2150) 33 | .filter(n -> n == 2000) 34 | .map(StreamsGoodPractices::timeConsumingTransformation) 35 | .sum(); 36 | 37 | System.out.println("fast " + fastNumber); 38 | 39 | int slowNumber = IntStream.range(1950, 2150) 40 | .map(StreamsGoodPractices::timeConsumingTransformation) 41 | .filter(n -> n == 2000) 42 | .sum(); 43 | 44 | System.out.println("slow " + slowNumber); 45 | } 46 | 47 | public static int timeConsumingTransformation(int number) { 48 | try { 49 | Thread.sleep(100); 50 | } catch (InterruptedException e) { 51 | e.printStackTrace(); 52 | } 53 | return number; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/exercise/ListFlatting.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams.exercise; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | public class ListFlatting { 9 | public static void main(String[] args) { 10 | List> listOfLists = Arrays.asList( 11 | Arrays.asList("1", "2", "3"), 12 | Arrays.asList("a", "b", "c"), 13 | Arrays.asList("A", "B", "C"), 14 | Arrays.asList("!", "@", "#") 15 | ); 16 | List flatten = flatten(listOfLists); 17 | System.out.println(flatten); 18 | } 19 | 20 | private static List flatten(List> listOfLists) { 21 | return listOfLists.stream() 22 | .flatMap(Collection::stream) 23 | .collect(Collectors.toList()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/exercise/LoopTooStream.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams.exercise; 2 | 3 | import pl.samouczekprogramisty.kursjava.streams.BoardGame; 4 | 5 | import java.util.Comparator; 6 | 7 | public class LoopTooStream { 8 | 9 | public static void main(String[] args) { 10 | loopVersion(); 11 | streamVersion(); 12 | } 13 | 14 | private static void loopVersion() { 15 | double highestRanking = 0; 16 | BoardGame bestGame = null; 17 | for (BoardGame game : BoardGame.GAMES) { 18 | if (game.name.contains("a")) { 19 | if (game.rating > highestRanking) { 20 | highestRanking = game.rating; 21 | bestGame = game; 22 | } 23 | } 24 | } 25 | System.out.println(bestGame.name); 26 | } 27 | 28 | private static void streamVersion() { 29 | BoardGame bestGame = BoardGame.GAMES 30 | .stream() 31 | .filter(g -> g.name.contains("a")) 32 | .max(Comparator.comparingDouble(g1 -> g1.rating)).get(); 33 | System.out.println(bestGame.name); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/exercise/MinWIthReduce.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams.exercise; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collection; 5 | import java.util.Comparator; 6 | import java.util.Optional; 7 | import java.util.function.BinaryOperator; 8 | 9 | public class MinWIthReduce { 10 | 11 | public static void main(String[] args) { 12 | Collection names = Arrays.asList("Marcin", "Marek", "Mariusz", "Marian"); 13 | Optional name = min(names, Comparator.comparingInt(String::length)); 14 | System.out.println(name.get()); 15 | } 16 | 17 | public static Optional min(Collection collection, Comparator comparator) { 18 | return collection.stream().reduce(BinaryOperator.minBy(comparator)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/requirements/InterferingOperation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams.requirements; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class InterferingOperation { 7 | public static void main(String[] args) { 8 | List numbers = new ArrayList<>(); 9 | numbers.add(1); 10 | numbers.add(2); 11 | 12 | numbers.stream() 13 | .map(v -> numbers.add(v) ? 1 : 0) 14 | .forEach(System.out::println); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /30_strumienie/src/main/java/pl/samouczekprogramisty/kursjava/streams/requirements/StatefullOperation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.streams.requirements; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | import java.util.stream.Stream; 6 | 7 | public class StatefullOperation { 8 | 9 | private final Set seen = new HashSet<>(); 10 | 11 | private int modify(int number) { 12 | if (seen.contains(number)) { 13 | return number; 14 | } 15 | seen.add(number); 16 | return 0; 17 | } 18 | 19 | public static void main(String[] args) { 20 | for (int i = 0; i < 3; i++) { 21 | Stream numbers = Stream.of(1, 2, 3, 1, 2, 3, 1, 2, 3); 22 | StatefullOperation requriements = new StatefullOperation(); 23 | int sum = numbers.parallel() 24 | .map(requriements::modify) 25 | .mapToInt(n -> n.intValue()).sum(); 26 | System.out.println(sum); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.3.2' 3 | testImplementation group: 'org.hamcrest', name: 'hamcrest', version: '2.1' 4 | testImplementation group: 'org.mockito', name: 'mockito-core', version: '3.0.0' 5 | testImplementation group: 'org.mockito', name: 'mockito-junit-jupiter', version: '3.0.0' 6 | testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.3.2' 7 | 8 | compile group: 'jakarta.json.bind', name: 'jakarta.json.bind-api', version: '1.0.2' 9 | compile group: 'org.eclipse', name: 'yasson', version: '1.0.5' 10 | } 11 | 12 | test { 13 | useJUnitPlatform() 14 | } 15 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/exchange/Currency.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.exchange; 2 | 3 | public enum Currency { 4 | PLN, 5 | EUR, 6 | USD 7 | } 8 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/exchange/ExchangePoint.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.exchange; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | 6 | public class ExchangePoint { 7 | 8 | private static final int SCALE = 4; 9 | private static final RoundingMode ROUNDING_MODE = RoundingMode.HALF_EVEN; 10 | 11 | private final RatesProvider ratesProvider; 12 | private final BigDecimal askSpread; 13 | private final BigDecimal bidSpread; 14 | 15 | public ExchangePoint(BigDecimal spread, RatesProvider ratesProvider) { 16 | if (spread.compareTo(BigDecimal.ZERO) < 0) { 17 | throw new IllegalArgumentException(String.format("Spread %s is illegal! Spread must be positive!", spread)); 18 | } 19 | if (spread.compareTo(BigDecimal.ONE) >= 0) { 20 | throw new IllegalArgumentException(String.format("Spread %s is illegal! Spread must be smaller than 1!", spread)); 21 | } 22 | this.askSpread = BigDecimal.ONE.add(spread).setScale(SCALE, ROUNDING_MODE); 23 | this.bidSpread = BigDecimal.ONE.subtract(spread).setScale(SCALE, ROUNDING_MODE); 24 | this.ratesProvider = ratesProvider; 25 | } 26 | 27 | public BigDecimal getBidPrice(BigDecimal amount, Currency from, Currency to) { 28 | return getExchangePrice(amount, from, to, bidSpread); 29 | } 30 | 31 | public BigDecimal getAskPrice(BigDecimal amount, Currency from, Currency to) { 32 | return getExchangePrice(amount, from, to, askSpread); 33 | } 34 | 35 | private BigDecimal getExchangePrice(BigDecimal amount, Currency from, Currency to, BigDecimal spread) { 36 | BigDecimal rate = ratesProvider.getRate(from, to); 37 | BigDecimal amountInDesiredCurrency = amount.multiply(rate); 38 | return amountInDesiredCurrency.multiply(spread); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/exchange/FixedRatesProvider.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.exchange; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.Objects; 8 | 9 | public class FixedRatesProvider implements RatesProvider { 10 | 11 | private static final int SCALE = 4; 12 | private static final RoundingMode ROUNDING_MODE = RoundingMode.HALF_EVEN; 13 | 14 | private static class ExchangePair { 15 | private Currency from; 16 | private Currency to; 17 | 18 | private ExchangePair(Currency from, Currency to) { 19 | this.from = from; 20 | this.to = to; 21 | } 22 | 23 | @Override 24 | public boolean equals(Object o) { 25 | if (this == o) return true; 26 | if (o == null || getClass() != o.getClass()) return false; 27 | ExchangePair that = (ExchangePair) o; 28 | return from == that.from && 29 | to == that.to; 30 | } 31 | 32 | @Override 33 | public int hashCode() { 34 | return Objects.hash(from, to); 35 | } 36 | } 37 | 38 | private final Map rates = new HashMap<>(); 39 | 40 | public void setRate(Currency from, Currency to, BigDecimal rate) { 41 | rates.put(new ExchangePair(from, to), rate.setScale(SCALE, ROUNDING_MODE)); 42 | rates.put(new ExchangePair(to, from), BigDecimal.ONE.divide(rate, SCALE, ROUNDING_MODE)); 43 | } 44 | 45 | @Override 46 | public BigDecimal getRate(Currency from, Currency to) { 47 | ExchangePair pair = new ExchangePair(from, to); 48 | if (!rates.containsKey(pair)) { 49 | throw new IllegalArgumentException(String.format("Rate for currency pair (%s, %s) is unknown!", from, to)); 50 | } 51 | return rates.get(pair); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/exchange/RatesProvider.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.exchange; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public interface RatesProvider { 6 | BigDecimal getRate(Currency from, Currency to); 7 | } 8 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/unit/Kilogram.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.unit; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Kilogram implements WeightUnit { 6 | public final BigDecimal value; 7 | 8 | public Kilogram(BigDecimal value) { 9 | if (BigDecimal.ZERO.compareTo(value) > 0) { 10 | throw new IllegalArgumentException("Weight can't be negative!"); 11 | } 12 | this.value = value.setScale(SCALE, ROUNDING_MODE); 13 | } 14 | 15 | public Pound toPounds() { 16 | return new Pound(value.divide(Pound.POUND_TO_KILOGRAM_RATIO, SCALE, ROUNDING_MODE)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/unit/Pound.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.unit; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Pound implements WeightUnit { 6 | public static final BigDecimal POUND_TO_KILOGRAM_RATIO = new BigDecimal("0.453592").setScale(SCALE, ROUNDING_MODE); 7 | 8 | public final BigDecimal value; 9 | 10 | public Pound(BigDecimal value) { 11 | if (BigDecimal.ZERO.compareTo(value) > 0) { 12 | throw new IllegalArgumentException("Weight can't be negative!"); 13 | } 14 | this.value = value.setScale(SCALE, ROUNDING_MODE); 15 | } 16 | 17 | public Kilogram toKilograms() { 18 | return new Kilogram(value.multiply(POUND_TO_KILOGRAM_RATIO).setScale(SCALE, ROUNDING_MODE)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/main/java/pl/samouczekprogramisty/kursjava/junit5/unit/WeightUnit.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.unit; 2 | 3 | import java.math.RoundingMode; 4 | 5 | public interface WeightUnit { 6 | int SCALE = 4; 7 | RoundingMode ROUNDING_MODE = RoundingMode.CEILING; 8 | } 9 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/test/java/pl/samouczekprogramisty/kursjava/junit5/exchange/FixedRatesProviderTest.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.exchange; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.BeforeEach; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import java.math.BigDecimal; 8 | 9 | import static org.hamcrest.MatcherAssert.assertThat; 10 | import static org.hamcrest.Matchers.is; 11 | 12 | class FixedRatesProviderTest { 13 | 14 | private FixedRatesProvider rates; 15 | 16 | @BeforeEach 17 | void setUp() { 18 | rates = new FixedRatesProvider(); 19 | } 20 | 21 | @Test 22 | void shouldReturnKnownRate() { 23 | rates.setRate(Currency.EUR, Currency.PLN, new BigDecimal("4.3727")); 24 | assertThat(rates.getRate(Currency.EUR, Currency.PLN), is(new BigDecimal("4.3727"))); 25 | } 26 | 27 | @Test 28 | void shouldReturnReversedRate() { 29 | rates.setRate(Currency.EUR, Currency.PLN, new BigDecimal("4.3727")); 30 | assertThat(rates.getRate(Currency.PLN, Currency.EUR), is(new BigDecimal("0.2287"))); 31 | } 32 | 33 | @Test 34 | void shouldThrowExceptionOnIllegalRatePair() { 35 | IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> { 36 | rates.getRate(Currency.PLN, Currency.EUR); 37 | }); 38 | assertThat(exception.getMessage(), is("Rate for currency pair (PLN, EUR) is unknown!")); 39 | } 40 | 41 | @Test 42 | void shouldRoundAndScaleRate() { 43 | rates.setRate(Currency.EUR, Currency.PLN, new BigDecimal("4.37274")); 44 | assertThat(rates.getRate(Currency.EUR, Currency.PLN), is(new BigDecimal("4.3727"))); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/test/java/pl/samouczekprogramisty/kursjava/junit5/unit/SamouczekBefore.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.unit; 2 | 3 | import org.junit.jupiter.api.extension.ExtendWith; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | @Target({ ElementType.TYPE, ElementType.METHOD }) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @ExtendWith(SamouczekExtension.class) 13 | public @interface SamouczekBefore { 14 | } 15 | -------------------------------------------------------------------------------- /31_testy_jednostkowe_junit5/src/test/java/pl/samouczekprogramisty/kursjava/junit5/unit/SamouczekExtension.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.junit5.unit; 2 | 3 | import org.junit.jupiter.api.extension.BeforeEachCallback; 4 | import org.junit.jupiter.api.extension.ExtensionContext; 5 | 6 | public class SamouczekExtension implements BeforeEachCallback { 7 | @Override 8 | public void beforeEach(ExtensionContext context) { 9 | System.out.println("Samouczek extension :)"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /32_format_json/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | sourceCompatibility = 1.8 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | dependencies { 10 | // json-p specification 11 | compile group: 'javax.json', name: 'javax.json-api', version: '1.1.2' 12 | // json-b specification 13 | compile group: 'javax.json.bind', name: 'javax.json.bind-api', version: '1.0' 14 | 15 | // json-p implementation 16 | compile group: 'org.glassfish', name: 'javax.json', version: '1.1.2' 17 | // json-b implementation 18 | compile group: 'org.eclipse', name: 'yasson', version: '1.0.1' 19 | 20 | } 21 | -------------------------------------------------------------------------------- /32_format_json/src/main/java/pl/samouczekprogramisty/kursjava/json/AnnotationExamples.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.json; 2 | 3 | import javax.json.bind.annotation.JsonbNumberFormat; 4 | import javax.json.bind.annotation.JsonbProperty; 5 | import javax.json.bind.annotation.JsonbPropertyOrder; 6 | import javax.json.bind.annotation.JsonbTransient; 7 | 8 | @JsonbPropertyOrder({"ccc", "bbb", "aaa"}) 9 | public class AnnotationExamples { 10 | @JsonbTransient 11 | private String skipped; 12 | 13 | @JsonbProperty(nillable=true) 14 | private String a1; 15 | 16 | private String a2; 17 | 18 | @JsonbNumberFormat("0.0000") 19 | private double bbb; 20 | 21 | @JsonbProperty("other_name") 22 | private String ccc; 23 | 24 | public String getSkipped() { 25 | return skipped; 26 | } 27 | 28 | public void setSkipped(String skipped) { 29 | this.skipped = skipped; 30 | } 31 | 32 | public String getA1() { 33 | return a1; 34 | } 35 | 36 | public void setA1(String a1) { 37 | this.a1 = a1; 38 | } 39 | 40 | public String getA2() { 41 | return a2; 42 | } 43 | 44 | public void setA2(String a2) { 45 | this.a2 = a2; 46 | } 47 | 48 | public double getBbb() { 49 | return bbb; 50 | } 51 | 52 | public void setBbb(double bbb) { 53 | this.bbb = bbb; 54 | } 55 | 56 | public String getCcc() { 57 | return ccc; 58 | } 59 | 60 | public void setCcc(String ccc) { 61 | this.ccc = ccc; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /32_format_json/src/main/java/pl/samouczekprogramisty/kursjava/json/JSONBExamples.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.json; 2 | 3 | import javax.json.bind.Jsonb; 4 | import javax.json.bind.JsonbBuilder; 5 | import java.time.LocalDate; 6 | 7 | public class JSONBExamples { 8 | private static final Newspaper newspaper = new Newspaper("Samouczek Programisty", 100_000, LocalDate.of(2018, 9, 13)); 9 | 10 | private static final Jsonb jsonb = JsonbBuilder.create(); 11 | 12 | public static void main(String[] args) { 13 | objectWriting(); 14 | objectReading(); 15 | annotationsWriting(); 16 | } 17 | 18 | private static void annotationsWriting() { 19 | AnnotationExamples annotationExamples = new AnnotationExamples(); 20 | annotationExamples.setBbb(123.45); 21 | annotationExamples.setCcc("ccc"); 22 | annotationExamples.setSkipped("skipped"); 23 | 24 | WithoutAnnotationExamples withoutAnnotationExamples = new WithoutAnnotationExamples(); 25 | withoutAnnotationExamples.setBbb(123.45); 26 | withoutAnnotationExamples.setCcc("ccc"); 27 | withoutAnnotationExamples.setSkipped("skipped"); 28 | 29 | System.out.println(jsonb.toJson(annotationExamples)); 30 | System.out.println(jsonb.toJson(withoutAnnotationExamples)); 31 | } 32 | 33 | private static void objectWriting() { 34 | String newspaperRepresentation = jsonb.toJson(newspaper); 35 | System.out.println(newspaperRepresentation); 36 | } 37 | 38 | private static void objectReading() { 39 | String newspaperRepresentation = jsonb.toJson(newspaper); 40 | 41 | Newspaper otherNewspaper = jsonb.fromJson(newspaperRepresentation, Newspaper.class); 42 | System.out.println(otherNewspaper.getIssueDate()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /32_format_json/src/main/java/pl/samouczekprogramisty/kursjava/json/Newspaper.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.json; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class Newspaper { 6 | private String title; 7 | private int circulation; 8 | private LocalDate issueDate; 9 | 10 | @SuppressWarnings("unused") 11 | public Newspaper() { 12 | } 13 | 14 | public Newspaper(String title, int circulation, LocalDate issueDate) { 15 | this.title = title; 16 | this.circulation = circulation; 17 | this.issueDate = issueDate; 18 | } 19 | 20 | public String getTitle() { 21 | return title; 22 | } 23 | 24 | public void setTitle(String title) { 25 | this.title = title; 26 | } 27 | 28 | public int getCirculation() { 29 | return circulation; 30 | } 31 | 32 | public void setCirculation(int circulation) { 33 | this.circulation = circulation; 34 | } 35 | 36 | public LocalDate getIssueDate() { 37 | return issueDate; 38 | } 39 | 40 | public void setIssueDate(LocalDate issueDate) { 41 | this.issueDate = issueDate; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /32_format_json/src/main/java/pl/samouczekprogramisty/kursjava/json/WithoutAnnotationExamples.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.json; 2 | 3 | public class WithoutAnnotationExamples { 4 | private String skipped; 5 | 6 | private String a1; 7 | 8 | private String a2; 9 | 10 | private double bbb; 11 | 12 | private String ccc; 13 | 14 | public String getSkipped() { 15 | return skipped; 16 | } 17 | 18 | public void setSkipped(String skipped) { 19 | this.skipped = skipped; 20 | } 21 | 22 | public String getA1() { 23 | return a1; 24 | } 25 | 26 | public void setA1(String a1) { 27 | this.a1 = a1; 28 | } 29 | 30 | public String getA2() { 31 | return a2; 32 | } 33 | 34 | public void setA2(String a2) { 35 | this.a2 = a2; 36 | } 37 | 38 | public double getBbb() { 39 | return bbb; 40 | } 41 | 42 | public void setBbb(double bbb) { 43 | this.bbb = bbb; 44 | } 45 | 46 | public String getCcc() { 47 | return ccc; 48 | } 49 | 50 | public void setCcc(String ccc) { 51 | this.ccc = ccc; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.3.1' 3 | testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.3.1' 4 | 5 | testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3' 6 | testCompile group: 'org.mockito', name: 'mockito-core', version: '2.22.0' 7 | testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.22.0' 8 | } 9 | 10 | test { 11 | useJUnitPlatform() 12 | } 13 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/src/main/java/pl/samouczekprogramisty/kursjava/mock/Airline.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.mock; 2 | 3 | import java.time.LocalDate; 4 | import java.util.List; 5 | 6 | public interface Airline { 7 | List findFlight(String departureAirport, String destinationAirport, LocalDate flightDate) throws FlightException; 8 | } 9 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/src/main/java/pl/samouczekprogramisty/kursjava/mock/Flight.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.mock; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Flight { 6 | private final String flightNumber; 7 | private final BigDecimal price; 8 | private final String departureAirport; 9 | private final String arrivalAirport; 10 | 11 | public Flight(String flightNumber, BigDecimal price, String departureAirport, String arrivalAirport) { 12 | this.flightNumber = flightNumber; 13 | this.price = price; 14 | this.departureAirport = departureAirport; 15 | this.arrivalAirport = arrivalAirport; 16 | } 17 | 18 | public String getFlightNumber() { 19 | return flightNumber; 20 | } 21 | 22 | public BigDecimal getPrice() { 23 | return price; 24 | } 25 | 26 | public String getDepartureAirport() { 27 | return departureAirport; 28 | } 29 | 30 | public String getArrivalAirport() { 31 | return arrivalAirport; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/src/main/java/pl/samouczekprogramisty/kursjava/mock/FlightException.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.mock; 2 | 3 | import java.io.IOException; 4 | 5 | public class FlightException extends IOException { 6 | public FlightException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/src/main/java/pl/samouczekprogramisty/kursjava/mock/FlightScanner.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.mock; 2 | 3 | import java.time.LocalDate; 4 | import java.util.*; 5 | 6 | public class FlightScanner { 7 | 8 | private final Airline[] airlines; 9 | 10 | public FlightScanner(Airline... airlines) { 11 | this.airlines = airlines; 12 | } 13 | 14 | public Flight findCheapestFlight(String departure, String destination, LocalDate flightDate) { 15 | Optional cheapestFlight = Arrays.stream(airlines) 16 | .map(a -> { 17 | try { 18 | return a.findFlight(departure, destination, flightDate); 19 | } catch (FlightException e) { 20 | // log 21 | List empty = Collections.emptyList(); 22 | return empty; 23 | } 24 | }) 25 | .flatMap(List::stream) 26 | .min(Comparator.comparing(Flight::getPrice)); 27 | 28 | return cheapestFlight.orElse(null); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/src/test/java/pl/samouczekprogramisty/kursjava/mock/FlightScannerTestMockito.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.mock; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.mockito.Mockito; 5 | 6 | import java.time.LocalDate; 7 | 8 | class FlightScannerTestMockito { 9 | @Test 10 | void shouldFindLowestPrice() throws FlightException { 11 | String departureAirport = "departure"; 12 | String destinationAirport = "arrival"; 13 | LocalDate day = LocalDate.of(2018, 9, 22); 14 | Airline mock1 = Mockito.mock(Airline.class); 15 | Airline mock2 = Mockito.mock(Airline.class); 16 | 17 | FlightScanner flightScanner = new FlightScanner(mock1, mock2); 18 | flightScanner.findCheapestFlight(departureAirport, destinationAirport, day); 19 | 20 | Mockito.verify(mock1).findFlight(departureAirport, destinationAirport, day); 21 | Mockito.verify(mock2).findFlight(departureAirport, destinationAirport, day); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /33_testy_z_mock_stub_spy/src/test/java/pl/samouczekprogramisty/kursjava/mock/FlightScannerTestStubs.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.mock; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.Collections; 7 | 8 | import static org.hamcrest.MatcherAssert.assertThat; 9 | import static org.hamcrest.Matchers.is; 10 | 11 | class FlightScannerTestStubs { 12 | 13 | private Airline stub1 = (departureAirport, destinationAirport, flightDate) -> Collections.singletonList( 14 | new Flight("AB1234", new BigDecimal(100), "WRO", "BCN") 15 | ); 16 | 17 | private Airline stub2 = (departureAirport, destinationAirport, flightDate) -> Collections.singletonList( 18 | new Flight("AB2345", new BigDecimal(200), "WRO", "BCN") 19 | ); 20 | 21 | private Airline stub3 = (departureAirport, destinationAirport, flightDate) -> { throw new FlightException("BOOM!"); }; 22 | 23 | @Test 24 | void shouldFindLowestPrice() { 25 | FlightScanner flightScanner = new FlightScanner(stub1, stub2, stub3); 26 | assertThat(flightScanner.findCheapestFlight("not", "important", null).getFlightNumber(), is("AB1234")); 27 | } 28 | } -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/ConsumerProducer.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads; 2 | 3 | 4 | import java.time.Duration; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | import java.util.Random; 8 | 9 | public class ConsumerProducer { 10 | private static final Random generator = new Random(); 11 | private static final Queue queue = new LinkedList<>(); 12 | 13 | public static void main(String[] args) { 14 | int itemCount = 5; 15 | Thread producer = new Thread(() -> { 16 | for (int i = 0; i < itemCount; i++) { 17 | try { 18 | Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis()); 19 | } catch (InterruptedException e) { 20 | throw new RuntimeException(e); 21 | } 22 | synchronized (queue) { 23 | queue.add("Item no. " + i); 24 | queue.notify(); 25 | } 26 | } 27 | }); 28 | Thread consumer = new Thread(() -> { 29 | int itemsLeft = itemCount; 30 | long rounds = 0; 31 | while (itemsLeft > 0) { 32 | rounds++; 33 | String item; 34 | synchronized (queue) { 35 | while (queue.isEmpty()) { 36 | try { 37 | queue.wait(); 38 | } catch (InterruptedException e) { 39 | throw new RuntimeException(e); 40 | } 41 | } 42 | item = queue.poll(); 43 | } 44 | itemsLeft--; 45 | System.out.println("Consumer got item: " + item); 46 | } 47 | System.out.println("I had " + rounds + " rounds!"); 48 | }); 49 | 50 | consumer.start(); 51 | producer.start(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/Creation.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads; 2 | 3 | public class Creation { 4 | 5 | public static class MyThread extends Thread { 6 | @Override 7 | public void run() { 8 | System.out.println("I'm inside thread (" + Thread.currentThread().getName() + ")!"); 9 | } 10 | } 11 | 12 | public static class MyRunnable implements Runnable { 13 | @Override 14 | public void run() { 15 | System.out.println("I'm inside runnable (" + Thread.currentThread().getName() + ")!"); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | Thread thread1 = new MyThread(); 21 | Thread thread2 = new Thread(new MyRunnable()); 22 | Thread thread3 = new Thread(() -> System.out.println("I'm also inside runnable implemented with lambda (" + Thread.currentThread().getName() + ")!")); 23 | 24 | System.out.println("Am I a thread? (" + Thread.currentThread().getName() + ")"); 25 | 26 | thread1.start(); 27 | thread2.start(); 28 | thread3.start(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/FirstThread.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads; 2 | 3 | public class FirstThread { 4 | public static void main(String[] args) { 5 | System.out.println("MT start"); 6 | Thread thread = new Thread(() -> { 7 | System.out.println("T0 start"); 8 | for (int i = 0; i < 5; i++) { 9 | System.out.println("T0 " + i); 10 | } 11 | System.out.println("T0 stop"); 12 | }); 13 | thread.start(); 14 | for (int i = 0; i < 5; i++) { 15 | System.out.println("MT " + i); 16 | } 17 | System.out.println("MT stop"); 18 | } 19 | } -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/NaiveConsumerProducer.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads; 2 | 3 | 4 | import java.time.Duration; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | import java.util.Random; 8 | 9 | public class NaiveConsumerProducer { 10 | private static final Random generator = new Random(); 11 | private static final Queue queue = new LinkedList<>(); 12 | 13 | public static void main(String[] args) { 14 | int itemCount = 5; 15 | Thread producer = new Thread(() -> { 16 | for (int i = 0; i < itemCount; i++) { 17 | try { 18 | Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis()); 19 | } catch (InterruptedException e) { 20 | throw new RuntimeException(e); 21 | } 22 | synchronized (queue) { 23 | queue.add("Item no. " + i); 24 | } 25 | } 26 | }); 27 | Thread consumer = new Thread(() -> { 28 | int itemsLeft = itemCount; 29 | long rounds = 0; 30 | while (itemsLeft > 0) { 31 | rounds++; 32 | String item; 33 | synchronized (queue) { 34 | if (queue.isEmpty()) { 35 | continue; 36 | } 37 | item = queue.poll(); 38 | } 39 | itemsLeft--; 40 | System.out.println("Consumer got item: " + item); 41 | } 42 | System.out.println("I had " + rounds + " rounds!"); 43 | }); 44 | 45 | consumer.start(); 46 | producer.start(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/RaceCondition.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads; 2 | 3 | class Counter { 4 | private int value; 5 | 6 | public synchronized void increment() { 7 | value += 1; 8 | } 9 | 10 | public void incrementRaceCondition() { 11 | value += 1; 12 | } 13 | 14 | public static void sampleStaticMethod() { 15 | synchronized (Counter.class) { 16 | System.out.println("xxx"); 17 | } 18 | } 19 | 20 | public synchronized static void otherVersionSampleStaticMethod() { 21 | System.out.println("xxx"); 22 | } 23 | 24 | public int getValue() { 25 | return value; 26 | } 27 | } 28 | 29 | public class RaceCondition { 30 | public static void main(String[] args) throws InterruptedException { 31 | Counter c = new Counter(); 32 | Runnable r = () -> { 33 | for (int i = 0; i < 100_000; i++) { 34 | c.incrementRaceCondition(); 35 | } 36 | }; 37 | 38 | Thread t1 = new Thread(r); 39 | Thread t2 = new Thread(r); 40 | Thread t3 = new Thread(r); 41 | 42 | t1.start(); 43 | t2.start(); 44 | t3.start(); 45 | 46 | t1.join(); 47 | t2.join(); 48 | t3.join(); 49 | 50 | System.out.println(c.getValue()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/VolatileExample.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads; 2 | 3 | import java.time.Duration; 4 | import java.time.LocalDateTime; 5 | import java.time.temporal.ChronoUnit; 6 | 7 | public class VolatileExample { 8 | private static volatile boolean isDone = false; 9 | 10 | public static void main(String[] args) { 11 | Thread backgroundJob = new Thread(() -> { 12 | try { 13 | Thread.sleep(Duration.ofSeconds(2).toMillis()); 14 | } catch (InterruptedException e) { 15 | throw new RuntimeException(e); 16 | } 17 | System.out.println("I'm done with my job!"); 18 | isDone = true; 19 | }); 20 | Thread heavyWorker = new Thread(() -> { 21 | LocalDateTime start = LocalDateTime.now(); 22 | while (!isDone) { 23 | // constantly doing some important stuff 24 | } 25 | long durationInMillis = ChronoUnit.MILLIS.between(start, LocalDateTime.now()); 26 | System.out.println("I've been notified about finished job after " + durationInMillis + " milliseconds."); 27 | }); 28 | 29 | heavyWorker.start(); 30 | backgroundJob.start(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/exercise/ReverseNumbers.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads.exercise; 2 | 3 | class ReversedNestedThread extends Thread { 4 | private final int children; 5 | 6 | ReversedNestedThread(int children) { 7 | this.children = children; 8 | } 9 | 10 | @Override 11 | public void run() { 12 | if (children > 0) { 13 | ReversedNestedThread childThread = new ReversedNestedThread(children - 1); 14 | childThread.start(); 15 | try { 16 | childThread.join(); 17 | } catch (InterruptedException e) { 18 | throw new RuntimeException(e); 19 | } 20 | System.out.println(getName()); 21 | } 22 | } 23 | } 24 | 25 | class NestedThread extends Thread { 26 | private final int children; 27 | 28 | NestedThread(int children) { 29 | this.children = children; 30 | } 31 | 32 | @Override 33 | public void run() { 34 | if (children > 0) { 35 | NestedThread childThread = new NestedThread(children - 1); 36 | System.out.println(getName()); 37 | childThread.start(); 38 | } 39 | } 40 | } 41 | 42 | public class ReverseNumbers { 43 | public static void main(String[] args) { 44 | startThreads(3); 45 | // startReversedThreads(3); 46 | } 47 | 48 | static void startThreads(int howManyChildren) { 49 | new NestedThread(howManyChildren).start(); 50 | } 51 | 52 | static void startReversedThreads(int howManyChildren) { 53 | new ReversedNestedThread(howManyChildren).start(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /34_watki/src/main/java/pl/samouczekprogramisty/kursjava/treads/exercise/ThreadedHelloWorld.java: -------------------------------------------------------------------------------- 1 | package pl.samouczekprogramisty.kursjava.treads.exercise; 2 | 3 | interface ConsoleWriter { 4 | void write(); 5 | } 6 | 7 | class Counter { 8 | private int count = 0; 9 | 10 | synchronized void increment() { 11 | count += 1; 12 | notify(); 13 | } 14 | 15 | synchronized void waitUntil(int desiredCount) { 16 | try { 17 | while (desiredCount > count) { 18 | wait(); 19 | } 20 | } catch (InterruptedException e) { 21 | throw new RuntimeException(e); 22 | } 23 | } 24 | } 25 | 26 | public class ThreadedHelloWorld { 27 | private static final int ITERATIONS = 5; 28 | 29 | public static void main(String[] args) { 30 | Counter helloLock = new Counter(); 31 | Counter worldLock = new Counter(); 32 | Counter exclamationLock = new Counter(); 33 | 34 | Thread t1 = new Thread(new SequentialRunnable(helloLock, worldLock, () -> System.out.print("Hello "))); 35 | Thread t2 = new Thread(new SequentialRunnable(worldLock, exclamationLock, () -> System.out.print("world"))); 36 | Thread t3 = new Thread(new SequentialRunnable(exclamationLock, helloLock, () -> System.out.println("!"))); 37 | 38 | t1.start(); 39 | t2.start(); 40 | t3.start(); 41 | 42 | helloLock.increment(); 43 | } 44 | 45 | private static class SequentialRunnable implements Runnable { 46 | private final ConsoleWriter writer; 47 | private Counter current; 48 | private Counter next; 49 | 50 | SequentialRunnable(Counter current, Counter next, ConsoleWriter writer) { 51 | this.current = current; 52 | this.next = next; 53 | this.writer = writer; 54 | } 55 | 56 | public void run() { 57 | for (int i = 0; i < ITERATIONS; i++) { 58 | current.waitUntil(i + 1); 59 | writer.write(); 60 | next.increment(); 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kurs Programowania Java 2 | Na stronie Samouczek Programisty możesz przeczytać artykuły z serii "[kurs programowania Java](http://www.samouczekprogramisty.pl)". 3 | 4 | W tym repozytorium znajdzesz przykłady użyte w artykułach prezentowanych w ramach tego kursu. 5 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | subprojects { 2 | apply plugin: 'java' 3 | apply plugin: 'idea' 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | group = 'pl.samouczekprogramisty.kursjava' 10 | version = '1.0-SNAPSHOT' 11 | 12 | gradle.projectsEvaluated { 13 | tasks.withType(JavaCompile) { 14 | options.compilerArgs << "-Xlint:deprecation" 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SamouczekProgramisty/KursJava/30d5b6d46982d023672ec75d506e7b1db1bdac9d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip 6 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'KursJava' 2 | 3 | include '01_metody' 4 | include '02_obiekty' 5 | include '03_pierwszy_program' 6 | include '04_tablice' 7 | include '05_petle' 8 | include '06_typy_proste' 9 | include '07_interfejsy' 10 | include '08_dziedziczenie' 11 | include '09_wyjatki' 12 | include '10_obiekty' 13 | include '11_konwersja_rzutowanie' 14 | include '12_dodatkowe_zadania' 15 | include '13_typy_generyczne' 16 | include '14_porownywanie_obiektow' 17 | include '15_kolekcje' 18 | include '15_struktury_danych' 19 | include '16_operacje_na_plikach' 20 | include '17_manager_kontekstu' 21 | include '18_serializacja' 22 | include '19_typ_wyliczeniowy' 23 | include '20_adnotacje' 24 | include '21_klasy_wewnetrzne' 25 | include '22_testy_jednostkowe' 26 | include '23_wyrazenia_regularne' 27 | include '24_wyrazenia_regularne' 28 | include '25_linia_polecen' 29 | include '26_lancuchy_znakow' 30 | include '27_lancuchy_znakow_formatowanie' 31 | include '28_wyrazenia_lambda' 32 | include '29_modyfikatory_dostepu' 33 | include '30_strumienie' 34 | include '31_testy_jednostkowe_junit5' 35 | include '32_format_json' 36 | include '33_testy_z_mock_stub_spy' 37 | include '34_watki' 38 | 39 | --------------------------------------------------------------------------------