├── .gitignore ├── a ├── asciireadDemo.txt ├── asd ├── demoIO12 ├── demoIO13 ├── demoIo.txt ├── eagles-group-io-demo.txt ├── eagles-group-io-demo2.txt ├── esenin.txt ├── git-usefull-commands.txt ├── niotest.txt ├── niotest2.txt ├── part6.txt ├── result.csv ├── serial ├── serialFile ├── some └── textEditor.txt ├── someDir └── file.txt ├── someFile.txt ├── src ├── MyClass.java ├── annotations │ ├── BusinessLogic.java │ ├── DemoTest.java │ ├── RequestForEnhancement.java │ ├── TestA.java │ ├── Todo.java │ └── TodoReport.java ├── arrays │ ├── ArraysStream.java │ ├── MatrixRotation.java │ └── NastiasMatrixRotation.java ├── collections │ ├── Demo1.java │ ├── Demo2.java │ ├── DemoCollections.java │ ├── DemoSet.java │ ├── LRUCache.java │ ├── Lesson1.java │ ├── Lesson11.java │ ├── Lesson112.java │ ├── LessonTest.java │ ├── MapDemo.java │ └── QueueDemo.java ├── date │ └── DemoTest.java ├── encoding │ └── EncodeDemo.java ├── exceptions │ ├── CustomCheckedException.java │ ├── CustomException.java │ └── Demo.java ├── generic │ ├── GenericDemo.java │ ├── GenericDemo1.java │ ├── GenericDemo2.java │ ├── GenericDemo3.java │ ├── InterestingTest.java │ ├── Main.java │ └── TestDemo.java ├── io │ ├── ByteStreams.java │ ├── Demo.java │ ├── DemoFile.java │ ├── DemoIo.java │ ├── FileAttributes.java │ ├── FileDemo.java │ ├── NioDemo.java │ ├── ReadingFiles.java │ ├── RecursiveTraining.java │ ├── TestLesson.java │ ├── TestLesson2.java │ ├── filefilter │ │ └── Test2.java │ └── serial │ │ ├── DemoSerial.java │ │ └── SerialDemo.java ├── junit │ ├── Bank.java │ └── Client.java ├── labs │ ├── practice1 │ │ ├── ConvertStringIntegerRadix26.java │ │ ├── Demo.java │ │ ├── GreatestCommonDividers.java │ │ ├── HelloWorld.java │ │ ├── SumArguments.java │ │ └── SumDigitsInNumber.java │ ├── practice2 │ │ ├── Demo.java │ │ ├── ListIterable.java │ │ ├── ListIterator.java │ │ ├── MyList.java │ │ └── MyListImpl.java │ ├── practice3 │ │ ├── Demo.java │ │ ├── Part1.java │ │ ├── Part2.java │ │ ├── Part3.java │ │ ├── Part4.java │ │ └── Part5.java │ ├── practice4 │ │ ├── Demo.java │ │ ├── Part1.java │ │ ├── Part2.java │ │ ├── Part3.java │ │ ├── Part4.java │ │ └── Part5.java │ ├── practice5 │ │ ├── Part1.java │ │ ├── Part2.java │ │ ├── Part3.java │ │ ├── Part4.java │ │ ├── Part51.java │ │ ├── Part52.java │ │ ├── Part53.java │ │ ├── Part6.java │ │ ├── SearchEngine.java │ │ ├── Spam.java │ │ └── Writer.java │ └── practice6 │ │ ├── Demo.java │ │ ├── Parking.java │ │ ├── Part1.java │ │ ├── Part2.java │ │ ├── Part3.java │ │ ├── Part5.java │ │ ├── Part6.java │ │ ├── Part7.java │ │ ├── Range.java │ │ ├── Tree.java │ │ ├── Word.java │ │ └── WordContainer.java ├── lessons │ ├── allgroups │ │ ├── DemoLesson.java │ │ ├── GiftExample.java │ │ ├── HomeWork511.java │ │ ├── Lesson1.java │ │ ├── Lesson1_1.java │ │ ├── Lesson2.java │ │ ├── Lesson2Part2.java │ │ ├── Lesson3.java │ │ ├── Lesson3_3.java │ │ ├── Lesson4ArrayStream.java │ │ ├── Lesson4Methods.java │ │ ├── Lesson5.java │ │ ├── Lesson7.java │ │ ├── Lesson9.java │ │ ├── LessonIo.java │ │ ├── LessonStringBuilder.java │ │ ├── Questino.java │ │ └── TriangleSquare.java │ ├── group10 │ │ ├── HomeWork_2.java │ │ ├── LRUCaches.java │ │ ├── LRUDemo.java │ │ ├── Lesson10.java │ │ ├── Lesson11.java │ │ ├── Lesson12.java │ │ ├── Lesson12HwTask4.java │ │ ├── Lesson13.java │ │ ├── Lesson2.java │ │ ├── Lesson3.java │ │ ├── Lesson4.java │ │ ├── Lesson5.java │ │ ├── Lesson7.java │ │ ├── Lesson8.java │ │ ├── Lesson9.java │ │ ├── LessonOOP.java │ │ ├── LessonOOPChild.java │ │ ├── LessonOOPDemo.java │ │ └── Test.java │ ├── group11 │ │ ├── Address.java │ │ ├── DebugDemo.java │ │ ├── DemoOop.java │ │ ├── DemoOopHw.java │ │ ├── ExceptionsDemo.java │ │ ├── IoLesson.java │ │ ├── Lesson2.java │ │ ├── Lesson2Arrays.java │ │ ├── Lesson3.java │ │ ├── Lesson4.java │ │ ├── ListDemo.java │ │ ├── StreamDemo.java │ │ ├── StreamDemo2.java │ │ ├── Student.java │ │ ├── StudentService.java │ │ ├── TextAnalyzer.java │ │ ├── TextAnalyzerDemo.java │ │ ├── ThreadDemo.java │ │ └── presenthw │ │ │ ├── Candy.java │ │ │ ├── ChocolateCandy.java │ │ │ ├── Cookie.java │ │ │ ├── Demo.java │ │ │ ├── Gift.java │ │ │ ├── Lollipop.java │ │ │ ├── Ovsyanoe.java │ │ │ └── Sweet.java │ ├── group2 │ │ ├── Dron_Multithreading.java │ │ ├── FunctionalInterfaceTest.java │ │ ├── HW13_task4.java │ │ ├── Lesson10_2.java │ │ ├── Lesson11_2.java │ │ ├── Lesson12_2.java │ │ ├── Lesson13_2.java │ │ ├── Lesson14_2.java │ │ ├── Lesson15_2.java │ │ ├── Lesson17.java │ │ ├── Lesson20.java │ │ ├── Lesson2_2.java │ │ ├── Lesson6_2.java │ │ ├── Lesson7_2.java │ │ ├── Lesson8_2.java │ │ ├── Lesson9_2.java │ │ ├── Lessont4_2.java │ │ └── PseudoTests.java │ ├── group6 │ │ ├── Lesson1.java │ │ ├── Lesson2.java │ │ ├── Lesson3.java │ │ ├── Lesson7.java │ │ ├── LruCache.java │ │ ├── Test.java │ │ ├── Test2.java │ │ ├── Test3.java │ │ └── TestLruCache.java │ ├── group7 │ │ ├── CallableDemo.java │ │ ├── DeadLockExample.java │ │ ├── Lesson11.java │ │ ├── Lesson12.java │ │ ├── Lesson12_2.java │ │ ├── MultithreadingHw.java │ │ ├── MyCallable.java │ │ ├── PrimeNumberSearcher.java │ │ ├── PrimeService.java │ │ ├── ThreadLesson.java │ │ └── ThreadLesson2.java │ ├── group8 │ │ ├── Lesson10.java │ │ ├── Lesson11.java │ │ ├── Lesson12.java │ │ ├── Lesson13.java │ │ ├── Lesson14.java │ │ ├── Lesson3.java │ │ ├── Lesson4.java │ │ ├── Lesson5.java │ │ ├── Lesson9.java │ │ ├── PrimitiveTest.java │ │ ├── TestClass.java │ │ └── exampledao │ │ │ ├── Demo.java │ │ │ ├── dao │ │ │ ├── UserDao.java │ │ │ └── impl │ │ │ │ └── DefaultUserDao.java │ │ │ └── models │ │ │ └── UserData.java │ └── group9 │ │ ├── Lesson10.java │ │ ├── Lesson11.java │ │ ├── Lesson12.java │ │ ├── Lesson14.java │ │ ├── Lesson14_2.java │ │ ├── Lesson15.java │ │ ├── Lesson2.java │ │ ├── Lesson3.java │ │ ├── Lesson4.java │ │ ├── Lesson5.java │ │ ├── Lesson6.java │ │ ├── Lesson6_2.java │ │ ├── MTApp.java │ │ ├── NewFile.java │ │ ├── OpenLesson.java │ │ └── Test1.java ├── multithreading │ ├── Lesson.java │ ├── Sasha.java │ ├── StartThread.java │ ├── demo │ │ ├── CallableDemo.java │ │ ├── CompletableFutureDemo.java │ │ ├── CreditRatingService.java │ │ ├── FirstLessonMultithreading.java │ │ └── UserService.java │ ├── different │ │ ├── DemoTest2.java │ │ ├── Interruption.java │ │ ├── Semaphore2.java │ │ ├── Synchronized1.java │ │ ├── TestDemo.java │ │ └── VolatileExample.java │ ├── examples1 │ │ ├── Atomic1.java │ │ ├── CompletableFuture1.java │ │ ├── ConcurrentUtils.java │ │ ├── CreateThreads1.java │ │ ├── DeadLockExample.java │ │ ├── Executors2.java │ │ ├── Executors3.java │ │ ├── Lock1.java │ │ ├── Lock2.java │ │ ├── Lock3.java │ │ ├── Lock4.java │ │ ├── Lock5.java │ │ ├── Semaphore1.java │ │ ├── Semaphore2.java │ │ ├── Synchronized1.java │ │ ├── Synchronized2.java │ │ ├── VolatileDemo.java │ │ └── VolatileExample.java │ ├── examples2 │ │ ├── callableandfuture │ │ │ ├── App.java │ │ │ ├── App2.java │ │ │ └── CallableTester.java │ │ ├── countdownlatch │ │ │ └── App.java │ │ ├── deadlock_11 │ │ │ ├── Account.java │ │ │ ├── App.java │ │ │ ├── Runner.java │ │ │ └── SimpleDeadLock.java │ │ ├── interruptthreads_14 │ │ │ └── App.java │ │ ├── jointhreads │ │ │ └── Worker.java │ │ ├── lockobjects │ │ │ ├── App.java │ │ │ ├── Worker.java │ │ │ └── WorkerMethodsSynchronized.java │ │ ├── lowLevelProducerConsumer │ │ │ ├── App.java │ │ │ └── Processor.java │ │ ├── producerConcumer │ │ │ └── App.java │ │ ├── reentrantlock │ │ │ ├── App.java │ │ │ └── Runner.java │ │ ├── semaphores │ │ │ ├── App.java │ │ │ ├── Connection.java │ │ │ └── Connectionn.java │ │ ├── startingthreads │ │ │ ├── ApplicationAnonymous.java │ │ │ ├── ApplicationExtends.java │ │ │ └── ApplicationRunnable.java │ │ ├── threadpool │ │ │ ├── App.java │ │ │ └── WorkerThreadPool.java │ │ ├── volatileKeyWord │ │ │ └── App.java │ │ └── waitAndNotify │ │ │ ├── App.java │ │ │ ├── BlockingQueueApp.java │ │ │ └── Processor.java │ └── waitnotify │ │ ├── Message.java │ │ ├── Notifier.java │ │ ├── Part53.java │ │ ├── WaitNotifyTest.java │ │ └── Waiter.java ├── oop │ ├── Demo.java │ ├── Demo2.java │ ├── DemoYacht.java │ ├── InitOrder.java │ ├── Lesson7.java │ ├── Test.java │ ├── Yacht.java │ ├── cars │ │ ├── Cabrio.java │ │ ├── Car.java │ │ ├── Demo.java │ │ ├── DieselEngine.java │ │ ├── Engine.java │ │ ├── PetrolEngine.java │ │ └── Sedan.java │ ├── cloning │ │ ├── CloneDemo.java │ │ ├── CloningTest.java │ │ ├── Employee.java │ │ └── Test.java │ ├── diamandissue │ │ ├── I1.java │ │ ├── I2.java │ │ └── Impl.java │ └── protecteddemo │ │ └── DemoProtected.java ├── optional │ └── OptionalDemo.java ├── patterns │ ├── basicpatterns │ │ ├── adapter │ │ │ ├── Client.java │ │ │ ├── NumberSorter.java │ │ │ ├── SortListAdapter.java │ │ │ └── Sorter.java │ │ ├── command │ │ │ ├── Client.java │ │ │ ├── Command.java │ │ │ ├── Light.java │ │ │ ├── LightOffCommand.java │ │ │ ├── LightOnCommand.java │ │ │ └── RemoteControl.java │ │ ├── facade │ │ │ ├── Client.java │ │ │ ├── FacadeMain.java │ │ │ ├── Flight.java │ │ │ ├── FlightBooker.java │ │ │ ├── Hotel.java │ │ │ ├── HotelBooker.java │ │ │ ├── TravelFacade.java │ │ │ └── TravelRoute.java │ │ ├── strategy │ │ │ ├── Client.java │ │ │ ├── CompressionContext.java │ │ │ ├── CompressionStrategy.java │ │ │ ├── RarCompressionStrategy.java │ │ │ └── ZipCompressionStrategy.java │ │ └── templmethod │ │ │ ├── AndroidCompiler.java │ │ │ ├── Client.java │ │ │ ├── CrossCompiler.java │ │ │ └── IPhoneCompiler.java │ ├── bridge │ │ ├── AdvancedRemote.java │ │ ├── BasicRemote.java │ │ ├── Demo.java │ │ ├── Device.java │ │ ├── Radio.java │ │ ├── Remote.java │ │ └── Tv.java │ ├── chainpatterns │ │ ├── chain │ │ │ ├── ATMDispenseChain.java │ │ │ ├── ATMDispenseChain2.java │ │ │ ├── ConcreteDespenser.java │ │ │ ├── Currency.java │ │ │ ├── DispenseChain.java │ │ │ ├── Dollar10Dispenser.java │ │ │ ├── Dollar20Dispenser.java │ │ │ └── Dollar50Dispenser.java │ │ └── decorator │ │ │ ├── BasicCar.java │ │ │ ├── Car.java │ │ │ ├── CarDecorator.java │ │ │ ├── DecoratorPatternTest.java │ │ │ ├── LuxuryCar.java │ │ │ └── SportsCar.java │ ├── composite │ │ ├── BaseShape.java │ │ ├── Circle.java │ │ ├── CompoundShape.java │ │ ├── Demo.java │ │ ├── Dot.java │ │ ├── ImageEditor.java │ │ ├── Rectangle.java │ │ └── Shape.java │ ├── creationalpatterns │ │ ├── abstractfactory │ │ │ ├── computerfactory │ │ │ │ ├── Computer.java │ │ │ │ ├── ComputerAbstractFactory.java │ │ │ │ ├── ComputerFactory.java │ │ │ │ ├── PC.java │ │ │ │ ├── PCFactory.java │ │ │ │ ├── Server.java │ │ │ │ ├── ServerFactory.java │ │ │ │ └── TestDesignPatterns.java │ │ │ ├── squadbuilder │ │ │ │ ├── Archer.java │ │ │ │ ├── Client.java │ │ │ │ ├── ElfSquadronFactory.java │ │ │ │ ├── Mage.java │ │ │ │ ├── SquadronFactory.java │ │ │ │ ├── Warrior.java │ │ │ │ └── elfsquade │ │ │ │ │ ├── ElfArcher.java │ │ │ │ │ ├── ElfMage.java │ │ │ │ │ └── ElfWarrior.java │ │ │ └── windowfactory │ │ │ │ ├── AbstractWidgetFactory.java │ │ │ │ ├── GUIBuilder.java │ │ │ │ ├── MSWindow.java │ │ │ │ ├── MacOSXWidgetFactory.java │ │ │ │ ├── MacOSXWindow.java │ │ │ │ ├── Main.java │ │ │ │ ├── MsWindowsWidgetFactory.java │ │ │ │ └── Window.java │ │ ├── builder │ │ │ ├── BuilderExample.java │ │ │ ├── CheapComputerBuilder.java │ │ │ ├── Computer.java │ │ │ ├── ComputerDirector.java │ │ │ └── easybuilder │ │ │ │ ├── Account.java │ │ │ │ └── Demo.java │ │ └── factorymethod │ │ │ ├── FactoryMethodDemo.java │ │ │ ├── T34Tank.java │ │ │ ├── T35Tank.java │ │ │ ├── T38Tank.java │ │ │ ├── Tank.java │ │ │ ├── TankCreator.java │ │ │ └── USSRTankCreator.java │ └── singleton │ │ └── SingletonDemo.java ├── reflection │ ├── DemoReflection.java │ ├── Main.java │ ├── PracticeExampleCar.java │ ├── TestDemo.java │ └── example-config.xml ├── resources_en.properties ├── resources_ru.properties ├── scanner │ └── Demo.java ├── solid │ ├── d │ │ ├── problem │ │ │ ├── WeatherAggregator.java │ │ │ ├── WeatherApi1.java │ │ │ └── WeatherApi2.java │ │ └── solution │ │ │ ├── WeatherAggregator.java │ │ │ ├── WeatherApi2.java │ │ │ └── WeatherSource.java │ ├── l │ │ ├── Bird2.java │ │ └── BirdTest.java │ ├── o │ │ ├── ExtendLoanHandler.java │ │ ├── LoanApprovalHandler.java │ │ ├── LoanApprovalHandler2.java │ │ ├── PersonalLoanValidator2.java │ │ ├── PersonalValidator.java │ │ ├── Validator.java │ │ └── reportexample │ │ │ ├── BadReport.java │ │ │ ├── ConversionRatesReport.java │ │ │ ├── OrdersPerDayReport.java │ │ │ └── Report.java │ └── s │ │ ├── MailboxSettingService.java │ │ ├── MailboxSettingService2.java │ │ ├── SecurityService.java │ │ └── User.java ├── string │ ├── StringFormatting.java │ └── Test.java ├── syntax │ ├── Demo.java │ ├── Demo2.java │ └── Demo3.java ├── test │ ├── HW6Discussion.java │ ├── LettersStatistic.java │ ├── LocalizedTimeStamp.java │ ├── SashsMultithreadHw.java │ ├── Test.java │ ├── Test2.java │ └── TestFunctionalStatic.java └── tests │ └── A.java ├── task03_in.txt ├── test.txt ├── test ├── TestDemoIntegrationTest.java ├── junit │ └── BankTest.java ├── labs │ └── practice4 │ │ ├── AllTests.java │ │ ├── DemoTest.java │ │ ├── Part1Test.java │ │ ├── Part2Test.java │ │ ├── Part3Test.java │ │ ├── Part4Test.java │ │ └── Part5Test.java └── lessons │ └── group6 │ └── TestLesson7.java ├── test11.txt ├── test12.txt ├── test4.txt ├── testWrite.txt ├── testWrite2.txt ├── testWrite3.txt ├── text01_in.txt ├── text02.txt ├── text02_INPUT_Test.txt ├── text02_MUSTBE_Sorted.txt ├── text02_SORTED.txt ├── text02_Sorted_Test.txt ├── text02_Test.txt └── text04.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse 2 | .classpath 3 | .project 4 | .settings/ 5 | bin/ 6 | doc/ 7 | 8 | # Intellij 9 | .idea/ 10 | *.iml 11 | *.iws 12 | 13 | # Mac 14 | .DS_Store 15 | 16 | # Maven 17 | log/ 18 | target/ 19 | build/ 20 | -------------------------------------------------------------------------------- /a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/a -------------------------------------------------------------------------------- /asciireadDemo.txt: -------------------------------------------------------------------------------- 1 | приветпривет!привет!привет!привет!привет!привет!привет!привет! -------------------------------------------------------------------------------- /asd: -------------------------------------------------------------------------------- 1 | hello -------------------------------------------------------------------------------- /demoIO12: -------------------------------------------------------------------------------- 1 | asdasd12121212cccc 2 | scscscs 3 | acascac 4 | -------------------------------------------------------------------------------- /demoIO13: -------------------------------------------------------------------------------- 1 | asd 2 | sds sds sds 3 | -------------------------------------------------------------------------------- /demoIo.txt: -------------------------------------------------------------------------------- 1 | asdasdasda фывйыфвфывфы‚ 2 | asdasd 3 | asdasdas -------------------------------------------------------------------------------- /eagles-group-io-demo.txt: -------------------------------------------------------------------------------- 1 | some input textsome input textsome input textsome input textsome input textsome input textsome input text -------------------------------------------------------------------------------- /eagles-group-io-demo2.txt: -------------------------------------------------------------------------------- 1 | some input textsome input textsome input text -------------------------------------------------------------------------------- /esenin.txt: -------------------------------------------------------------------------------- 1 | Ты такая ж простая, как все, 2 | Как сто ты@сяч других в России. 3 | Знаешь ты одинокий рассвет, 4 | Знаешь холод осени синий. 5 | 6 | По-смешному я сердцем влип, 7 | Я по-глупому мы@сли занял. 8 | Твой иконный и строгий лик 9 | По часовням висел в рязанях. 10 | 11 | Я на эти иконы плевал, 12 | Чтил я грубость и крик в повесе, 13 | А теперь вд@руг растут слова 14 | Самых нежных и кротких песен. 15 | 16 | Не хочу я лететь в зенит, 17 | Слишком многое телу надо. 18 | Что ж так имя твое звенит, 19 | Словно августовская прохлада? 20 | 21 | Я не нищий, ни жалок, ни мал 22 | И умею расслы@шать за пылом: 23 | С детства нравиться я понимал 24 | Кобелям да степным кобылам. 25 | 26 | Потому и себя не сберег 27 | Для тебя, для нее и для этой. 28 | Неве@селого счастья залог - 29 | Сумасшедшее сердце поэта. 30 | 31 | Потому и грущу, осев, 32 | Словно в листья, в глаза косые... 33 | Ты такая ж про@стая, как все, 34 | Как сто тысяч других в России. -------------------------------------------------------------------------------- /git-usefull-commands.txt: -------------------------------------------------------------------------------- 1 | git config --global user.name "Jerry Mouse" 2 | git config --global user.email "jerry@tutorialspoint.com" 3 | 4 | git config --local user.name "Jerry Mouse" 5 | git config --local user.email "jerry@tutorialspoint.com" 6 | 7 | 8 | git config --global branch.autosetuprebase always 9 | 10 | git config --global core.editor "notepad" 11 | git config --global core.editor vim 12 | git config --global core.editor "vim" 13 | 14 | git config --list 15 | -------------------------------------------------------------------------------- /niotest.txt: -------------------------------------------------------------------------------- 1 | a 2 | s 3 | d 4 | -------------------------------------------------------------------------------- /niotest2.txt: -------------------------------------------------------------------------------- 1 | asdasdasdasd -------------------------------------------------------------------------------- /part6.txt: -------------------------------------------------------------------------------- 1 | 00000000000000000000 2 | 11111111111111111111 3 | 22222222222222222222 4 | 33333333333333333333 5 | 44444444444444444444 6 | 55555555555555555555 7 | 66666666666666666666 8 | 77777777777777777777 9 | 88888888888888888888 10 | 99999999999999999999 11 | -------------------------------------------------------------------------------- /result.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/result.csv -------------------------------------------------------------------------------- /serial: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/serial -------------------------------------------------------------------------------- /serialFile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/serialFile -------------------------------------------------------------------------------- /some/textEditor.txt: -------------------------------------------------------------------------------- 1 | asdasd 2 | qwdqwd 3 | -------------------------------------------------------------------------------- /someDir/file.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/someDir/file.txt -------------------------------------------------------------------------------- /someFile.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/someFile.txt -------------------------------------------------------------------------------- /src/MyClass.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | 3 | //import java.util.HashSet; 4 | //import java.util.Set; 5 | // 6 | //class Copier { 7 | // public T copy(T param) throws CloneNotSupportedException { 8 | // return (T) param.clone(); // 1 9 | // } 10 | //} 11 | // 12 | //class A implements Cloneable { 13 | // public int i = 10; 14 | // 15 | // @Override 16 | // public A clone() throws CloneNotSupportedException { 17 | // return (A) super.clone(); // 2 18 | // } 19 | //} 20 | // 21 | //class B extends A { 22 | // public int i = 20; 23 | //} 24 | // 25 | //public class MyClass { 26 | // public static void main(String[] args) throws CloneNotSupportedException { 27 | // B b = new B(); 28 | // Copier copier = new Copier<>(); // 3 29 | // A a = copier.copy(b); // 4 30 | // System.out.println(a.i); 31 | // } 32 | //} 33 | 34 | 35 | public class MyClass { 36 | 37 | 38 | public static void main(String[] args) { 39 | System.out.println(m()); 40 | } 41 | 42 | public static int m() { 43 | try { 44 | return 1; 45 | } finally { 46 | return 2; 47 | } 48 | } 49 | 50 | public static int t2() { 51 | try { 52 | int x = 0; 53 | int y = 5 / 2; 54 | } catch (Exception e) { 55 | 56 | } 57 | 58 | return 0; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/annotations/BusinessLogic.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Class demonstrates use of Todo annotation defined in Todo.java 3 | * 4 | * @author Yashwant Golecha (ygolecha@gmail.com) 5 | * @version 1.0 6 | * 7 | */ 8 | 9 | package annotations; 10 | 11 | public class BusinessLogic { 12 | 13 | // @Email(pattern = "") 14 | // String name; 15 | 16 | // @Override 17 | 18 | public BusinessLogic() { 19 | super(); 20 | } 21 | 22 | // public void test(@Valid User user, BindingResult br) { 23 | // 24 | // } 25 | 26 | public void compltedMethod() { 27 | System.out.println("This method is complete"); 28 | } 29 | 30 | @Todo(priority = Todo.Priority.HIGH) 31 | public void notYetStartedMethod() { 32 | // No Code Written yet 33 | } 34 | 35 | @Todo(priority = Todo.Priority.MEDIUM, author = "Some other", status = Todo.Status.STARTED) 36 | public void incompleteMethod1() { 37 | //Some business logic is written 38 | //But its not complete yet 39 | } 40 | 41 | @Todo(priority = Todo.Priority.LOW, status = Todo.Status.STARTED ) 42 | public void incompleteMethod2() { 43 | //Some business logic is written 44 | //But its not complete yet 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/annotations/DemoTest.java: -------------------------------------------------------------------------------- 1 | package annotations; 2 | 3 | @TestA(smth = "") 4 | public class DemoTest { 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/annotations/RequestForEnhancement.java: -------------------------------------------------------------------------------- 1 | package annotations; 2 | 3 | /** 4 | * Describes the Request-for-Enhancement (RFE) annotation type. 5 | */ 6 | public @interface RequestForEnhancement { 7 | int id(); 8 | String synopsis(); 9 | String engineer() default "[unassigned]"; 10 | String date() default "[unknown]"; 11 | } 12 | -------------------------------------------------------------------------------- /src/annotations/TestA.java: -------------------------------------------------------------------------------- 1 | package annotations; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | @Retention(RetentionPolicy.CLASS) 7 | public @interface TestA { 8 | String smth(); 9 | } 10 | -------------------------------------------------------------------------------- /src/annotations/Todo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This code demonstrates how to define an annotation. 3 | * 4 | * @author Yashwant Golecha (ygolecha@gmail.com) 5 | * @version 1.0 6 | * 7 | */ 8 | 9 | package annotations; 10 | 11 | import java.lang.annotation.ElementType; 12 | import java.lang.annotation.Retention; 13 | import java.lang.annotation.RetentionPolicy; 14 | import java.lang.annotation.Target; 15 | 16 | @Target(ElementType.METHOD) 17 | @Retention(RetentionPolicy.RUNTIME) 18 | @interface Todo { 19 | public enum Priority {LOW, MEDIUM, HIGH} 20 | public enum Status {STARTED, NOT_STARTED} 21 | 22 | String author() default "Test"; 23 | Priority priority() default Priority.LOW; 24 | Status status() default Status.NOT_STARTED; 25 | } 26 | -------------------------------------------------------------------------------- /src/annotations/TodoReport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Class demonstrates use of annotations using reflection. 3 | * 4 | * @author Yashwant Golecha (ygolecha@gmail.com) 5 | * @version 1.0 6 | * 7 | */ 8 | 9 | package annotations; 10 | 11 | import java.lang.reflect.Method; 12 | 13 | public class TodoReport { 14 | public TodoReport() { 15 | super(); 16 | } 17 | 18 | public static void main(String[] args) { 19 | getTodoReportForBusinessLogic(); 20 | } 21 | 22 | /** 23 | * This method iterates through all messages of BusinessLogic class and 24 | * fetches annotations defined on each of them. After that it displays the 25 | * information from annotation accordingly. 26 | */ 27 | private static void getTodoReportForBusinessLogic() { 28 | 29 | Class businessLogicClass = BusinessLogic.class; 30 | for (Method method : businessLogicClass.getMethods()) { 31 | Todo todoAnnotation = (Todo) method.getAnnotation(Todo.class); 32 | if (todoAnnotation != null) { 33 | System.out.println(" Method Name : " + method.getName()); 34 | System.out.println(" Author : " + todoAnnotation.author()); 35 | System.out.println(" Priority : " + todoAnnotation.priority()); 36 | System.out.println(" Status : " + todoAnnotation.status()); 37 | System.out.println(" --------------------------- "); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/collections/DemoSet.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class DemoSet { 7 | 8 | public static void main(String[] args) { 9 | Set set = new HashSet<>(); 10 | TestClass e = new TestClass(1); 11 | TestClass e2 = new TestClass(1); 12 | System.out.println(set.add(e)); 13 | System.out.println(set.add(e)); 14 | System.out.println(set.add(e2)); 15 | System.out.println(set.size()); 16 | } 17 | } 18 | 19 | 20 | class TestClass { 21 | 22 | private int i; 23 | 24 | public TestClass(int i) { 25 | this.i = i; 26 | } 27 | 28 | @Override 29 | public int hashCode() { 30 | final int prime = 31; 31 | int result = 1; 32 | result = prime * result + i; 33 | return result; 34 | } 35 | 36 | @Override 37 | public boolean equals(Object obj) { 38 | if (this == obj) 39 | return true; 40 | if (obj == null) 41 | return false; 42 | if (getClass() != obj.getClass()) 43 | return false; 44 | TestClass other = (TestClass) obj; 45 | if (i != other.i) 46 | return false; 47 | return true; 48 | } 49 | } -------------------------------------------------------------------------------- /src/collections/Lesson1.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | 8 | public class Lesson1 implements Iterable { 9 | 10 | public static void main(String[] args) { 11 | // Lesson1 l = new Lesson1(); 12 | // for (Lesson1 o : l) { 13 | // System.out.println(o); 14 | // 15 | // } 16 | // 17 | // List list = new ArrayList(); 18 | // Object[] array = list.toArray(); 19 | // String[] a = list.toArray(new String[0]); 20 | // 21 | 22 | List l = new ArrayList<>(Arrays.asList(1,3,4, 2, 2)); 23 | List l2 = new ArrayList<>(Arrays.asList(1,2)); 24 | 25 | l.retainAll(l2); 26 | System.out.println(l); 27 | 28 | l.removeAll(l2); 29 | System.out.println(l); 30 | 31 | 32 | 33 | } 34 | 35 | 36 | @Override 37 | public Iterator iterator() { 38 | return null; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/collections/Lesson11.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.Arrays; 4 | import java.util.Set; 5 | import java.util.TreeSet; 6 | 7 | public class Lesson11 { 8 | 9 | private int list; 10 | 11 | 12 | public static void main(String[] args) { 13 | String s = "asda, asdas; asda."; 14 | String[] split = s.split("\\p{P}"); 15 | System.out.println(Arrays.toString(split)); 16 | System.out.println(split.length); 17 | 18 | Set set = new TreeSet<>(); 19 | } 20 | 21 | private class A { 22 | 23 | private int list; 24 | public void doSmth() { 25 | Lesson11.this.list = 10; 26 | 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/collections/LessonTest.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class LessonTest { 7 | 8 | public static void main(String[] args) { 9 | List l = new ArrayList<>(); 10 | Object[] array = l.toArray(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/collections/QueueDemo.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.PriorityQueue; 4 | import java.util.Queue; 5 | 6 | public class QueueDemo { 7 | 8 | public static void main(String[] args) { 9 | 10 | Queue queue = new PriorityQueue<>((s1, s2) -> s1.compareToIgnoreCase(s2)); 11 | 12 | queue.offer("abc"); 13 | queue.offer("zex"); 14 | queue.offer("bcd"); 15 | queue.offer("Abc"); 16 | queue.offer("Bcd"); 17 | 18 | System.out.println(queue.poll()); 19 | System.out.println(queue.poll()); 20 | System.out.println(queue.poll()); 21 | System.out.println(queue.poll()); 22 | System.out.println(queue.poll()); 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/exceptions/CustomCheckedException.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | 3 | public class CustomCheckedException extends Exception { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/exceptions/CustomException.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | 3 | public class CustomException extends RuntimeException { 4 | 5 | public CustomException() { 6 | super(); 7 | } 8 | 9 | public CustomException(String message) { 10 | super(message); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/generic/GenericDemo1.java: -------------------------------------------------------------------------------- 1 | package generic; 2 | 3 | import java.util.Formatter; 4 | 5 | public class GenericDemo1 { 6 | 7 | // generic method printArray 8 | public static E printArray(E[] inputArray) { 9 | // Display array elements 10 | for (E element : inputArray) { 11 | System.out.printf("%s ", element); 12 | } 13 | System.out.println(); 14 | return inputArray[0]; 15 | } 16 | 17 | 18 | 19 | public static void main(String args[]) { 20 | // Create arrays of Integer, Double and Character 21 | Integer[] intArray = { 1, 2, 3, 4, 5 }; 22 | Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; 23 | Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; 24 | 25 | System.out.println("Array integerArray contains:"); 26 | Integer printArray = printArray(intArray); // pass an Integer array 27 | 28 | System.out.println("\nArray doubleArray contains:"); 29 | Double printArray2 = printArray(doubleArray); // pass a Double array 30 | 31 | System.out.println("\nArray characterArray contains:"); 32 | Character printArray3 = printArray(charArray); // pass a Character array 33 | } 34 | 35 | } 36 | 37 | class SomeClass15 { 38 | 39 | public void doSmth() { 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/generic/GenericDemo2.java: -------------------------------------------------------------------------------- 1 | package generic; 2 | 3 | public class GenericDemo2 { 4 | // determines the largest of three Comparable objects 5 | 6 | public static > T maximum(T x, T y, T z) { 7 | T max = x; // assume x is initially the largest 8 | 9 | if (y.compareTo(max) > 0) { 10 | max = y; // y is the largest so far 11 | } 12 | 13 | if (z.compareTo(max) > 0) { 14 | max = z; // z is the largest now 15 | } 16 | return max; // returns the largest object 17 | } 18 | 19 | public static void main(String args[]) { 20 | System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5)); 21 | 22 | System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7)); 23 | 24 | System.out.printf("Max of %s, %s and %s is %s\n", "pear", "apple", "orange", 25 | maximum("pear", "apple", "orange")); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/generic/InterestingTest.java: -------------------------------------------------------------------------------- 1 | //package generic; 2 | // 3 | //import java.util.ArrayList; 4 | //import java.util.List; 5 | // 6 | //public class InterestingTest { 7 | // 8 | // private List list = new ArrayList<>(); 9 | // 10 | // public void add() { 11 | //// List list = this.list; 12 | // list.add(new Object()); 13 | // } 14 | //} 15 | -------------------------------------------------------------------------------- /src/generic/Main.java: -------------------------------------------------------------------------------- 1 | package generic; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.util.Scanner; 6 | 7 | public class Main { 8 | 9 | public static final String CONSTANT_SOME = "Constanct"; 10 | 11 | public static void main(String[] args) throws IOException { 12 | final int a = 10; 13 | 14 | } 15 | 16 | void test(final String s) { 17 | if (s == null) 18 | return; 19 | 20 | } 21 | 22 | private void testMethod(String str) { 23 | System.out.println(str); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/io/DemoFile.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class DemoFile { 7 | 8 | public static void main(String[] args) throws IOException { 9 | File file = new File("fold2" + File.separator + "test"); 10 | 11 | System.out.println(file.getAbsolutePath()); 12 | System.out.println(file.getPath()); 13 | System.out.println(file.getCanonicalPath()); 14 | file.mkdirs(); 15 | 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/io/DemoIo.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.BufferedReader; 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileNotFoundException; 8 | import java.io.FileReader; 9 | import java.io.IOException; 10 | import java.util.Scanner; 11 | 12 | public class DemoIo { 13 | 14 | public static void main(String[] args) throws IOException { 15 | test(); 16 | String pathToFile = "some3" + File.pathSeparator + "some2"; 17 | File file = new File("../"); 18 | 19 | File file2 = file; 20 | 21 | FileReader fr = new FileReader("test"); 22 | BufferedReader br = new BufferedReader(fr); 23 | br.readLine(); 24 | 25 | try (FileInputStream fis = new FileInputStream("test"); 26 | BufferedInputStream bis = new BufferedInputStream(fis);) { 27 | 28 | } 29 | } 30 | 31 | public static void test() { 32 | test(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/io/FileAttributes.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | import java.nio.file.attribute.DosFileAttributeView; 7 | import java.nio.file.attribute.FileAttribute; 8 | import java.nio.file.attribute.PosixFilePermission; 9 | import java.nio.file.attribute.PosixFilePermissions; 10 | import java.util.Set; 11 | 12 | public class FileAttributes { 13 | 14 | public static void main(String[] args) throws IOException { 15 | // DosFileAttributeView dosView = Files.getFileAttributeView("",DosFileAttributeView.class); 16 | // dosView.setHidden(true); 17 | // dosView.setReadOnly(true); 18 | // dosView.setSystem(true); 19 | // dosView.setArchive(true); 20 | 21 | Set permissions = PosixFilePermissions.fromString("rwxrwxrwx"); 22 | FileAttribute> fileAttributes = PosixFilePermissions 23 | .asFileAttribute(permissions); 24 | Files.createDirectory(Paths.get("test10"), fileAttributes); 25 | Files.createFile(Paths.get("someFile.txt")); 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/io/ReadingFiles.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileReader; 7 | import java.io.IOException; 8 | import java.nio.file.Files; 9 | import java.nio.file.Paths; 10 | import java.util.List; 11 | import java.util.stream.Stream; 12 | 13 | public class ReadingFiles { 14 | 15 | public static void main(String[] args) throws IOException { 16 | printFileToConsole("test"); 17 | 18 | } 19 | 20 | 21 | public static void printFileToConsole(String path) throws IOException { 22 | try (Stream fStream = Files.lines(Paths.get(path))) { 23 | fStream.forEach(System.out::println); 24 | } 25 | } 26 | 27 | public static void printFileToConsole2(String path) throws FileNotFoundException, IOException { 28 | try (BufferedReader br = new BufferedReader(new FileReader(path))) { 29 | String line; 30 | while ( (line = br.readLine()) != null) { 31 | System.out.println(line); 32 | } 33 | } 34 | } 35 | 36 | public void e(List list) { 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/io/RecursiveTraining.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.File; 4 | 5 | public class RecursiveTraining { 6 | 7 | private static int i = 0; 8 | 9 | private static int fileCount; 10 | 11 | public static void main(String[] args) { 12 | // recursiveMethod(); 13 | int counter = 0; 14 | File file = new File("./"); 15 | System.out.println(file.getAbsolutePath()); 16 | System.out.println(file.isDirectory()); 17 | searchRecursively(file); 18 | System.out.println(fileCount); 19 | } 20 | 21 | 22 | private static void searchRecursively(File file) { 23 | File[] listFiles = file.listFiles(); 24 | if (listFiles != null) { 25 | for (File file2 : listFiles) { 26 | if (file2.isDirectory()) { 27 | searchRecursively(file2); 28 | } else { 29 | if (file2.getName().endsWith(".java")) { 30 | fileCount++; 31 | } 32 | } 33 | } 34 | } 35 | 36 | } 37 | 38 | private static void recursiveMethod() { 39 | System.out.println(i++); 40 | 41 | if (i < 1000) { 42 | recursiveMethod(); 43 | } else { 44 | return; 45 | } 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/io/TestLesson.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.nio.charset.Charset; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.nio.file.Paths; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * asdasd 16 | * 17 | * @author Andrii_Piatakha 18 | * 19 | */ 20 | 21 | public final class TestLesson { 22 | 23 | private TestLesson() { 24 | 25 | } 26 | 27 | public static void main(String[] args) throws IOException { 28 | Path p = Paths.get("folder1", "folder2", "text.txt"); 29 | Charset charset = Charset.forName("UTF-8"); 30 | List lines = new ArrayList<>(); 31 | Files.write(p, lines, charset); 32 | 33 | } 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/io/TestLesson2.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | import java.nio.file.Path; 7 | import java.nio.file.Paths; 8 | 9 | 10 | public class TestLesson2 { 11 | 12 | public static void main(String[] args) throws IOException { 13 | File f = new File("someDir"); 14 | f.mkdir(); 15 | 16 | File f2 = new File("someDir" + File.separator + "file.txt"); 17 | f2.createNewFile(); 18 | 19 | Path p = Paths.get("someDir2"); 20 | Files.createDirectory(p); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/io/filefilter/Test2.java: -------------------------------------------------------------------------------- 1 | package io.filefilter; 2 | 3 | import java.io.File; 4 | import java.io.FileFilter; 5 | 6 | public class Test2 { 7 | private void test() { 8 | FileFilter ff = pathname -> pathname.isHidden(); 9 | } 10 | 11 | public static void main(String[] args) { 12 | File file = new File("./src/com"); 13 | File[] listFiles = file.listFiles(); 14 | File[] listFiles2 = file.listFiles(pathname -> pathname.isHidden()); 15 | 16 | System.out.println(file.getParent()); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/junit/Bank.java: -------------------------------------------------------------------------------- 1 | package junit; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Bank { 7 | 8 | private List clients; 9 | 10 | public Bank() { 11 | clients = new ArrayList<>(); 12 | } 13 | 14 | public void addClient(Client client) { 15 | this.clients.add(client); 16 | } 17 | 18 | public List getClients() { 19 | return this.clients; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/junit/Client.java: -------------------------------------------------------------------------------- 1 | package junit; 2 | 3 | public class Client { 4 | 5 | public int salary; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/labs/practice1/Demo.java: -------------------------------------------------------------------------------- 1 | package labs.practice1; 2 | 3 | /** 4 | * Application Demo demonstrates all applications from task01. 5 | * Class Demo consists of one static main method which provides 6 | * access to static main methods of each class in package ua.khpi.pyatakha.task01 7 | * 8 | * @author Andrey Pyatakha 9 | * 10 | */ 11 | 12 | public class Demo { 13 | 14 | /** 15 | * Enter point to the Demo application. 16 | * 17 | * Invokes main methods of each class in package ua.khpi.pyatakha.task01 18 | * 19 | * @param args 20 | */ 21 | 22 | public static void main(String[] args) { 23 | HelloWorld.main(new String[] {}); 24 | SumArguments.main(new String[] {"81", "36"}); 25 | GreatestCommonDividers.main(new String[] {"12", "30"}); 26 | SumDigitsInNumber.main(new String[] {"1123"}); 27 | ConvertStringIntegerRadix26.main(new String[] {"ABZ", "754", "ABZ"}); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/labs/practice1/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package labs.practice1; 2 | 3 | /** 4 | * This application shows welcome message in console. 5 | * 6 | * @author Andrey Pyatakha 7 | * 8 | */ 9 | 10 | public class HelloWorld { 11 | 12 | /** 13 | * Enter point to the HelloWorld application. 14 | * 15 | * @param args 16 | */ 17 | 18 | public static void main(String[] args) { 19 | System.out.println("Hello, World"); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/labs/practice1/SumArguments.java: -------------------------------------------------------------------------------- 1 | package labs.practice1; 2 | 3 | /** 4 | * This class summarize only first and second arguments. 5 | * 6 | * @author Andrey Pyatakha 7 | * 8 | */ 9 | 10 | public class SumArguments { 11 | 12 | /** 13 | * Enter point. 14 | * 15 | * If entered arguments are not numbers throws NumberFormatException 16 | * If there are less than two arguments throws IndexOutOfBoundsException 17 | * 18 | * @param args; 19 | */ 20 | 21 | 22 | public static void main(String[] args) { 23 | // check if input numbers double or integer 24 | if (args[0].contains(".") || args[1].contains(".")) { 25 | double paramDouble1 = Double.parseDouble(args[0]); 26 | double paramDouble2 = Double.parseDouble(args[1]); 27 | System.out.println(paramDouble1 + " + " + paramDouble2 28 | + " = " + (paramDouble1 + paramDouble2)); 29 | } else { 30 | int paramInt1 = Integer.parseInt(args[0]); 31 | int paramInt2 = Integer.parseInt(args[1]); 32 | System.out.println(paramInt1 + " + " + paramInt2 33 | + " = " + (paramInt1 + paramInt2)); 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/labs/practice2/ListIterable.java: -------------------------------------------------------------------------------- 1 | package labs.practice2; 2 | 3 | /** 4 | * Implementing this interface allows an object to returns 5 | * object of ListIterator. 6 | * 7 | * @author Andrey Pyatakha 8 | * 9 | */ 10 | 11 | public interface ListIterable { 12 | 13 | /** 14 | * Returns object of ListIterator. 15 | * 16 | * @return object of ListIterator 17 | */ 18 | ListIterator listIterator(); 19 | } 20 | -------------------------------------------------------------------------------- /src/labs/practice3/Part3.java: -------------------------------------------------------------------------------- 1 | package labs.practice3; 2 | 3 | /** 4 | * Turns every first letter in each word to capital. 5 | * 6 | * Contains only one static method which provide main functionality. 7 | * 8 | * @author Andrey Pyatakha 9 | * 10 | */ 11 | 12 | public class Part3 { 13 | 14 | 15 | /** 16 | * Turns first letter in each word to capital. 17 | * 18 | * At first method turns input text to chat array. 19 | * After it runs through it and when it faces to the first letter 20 | * it turns is to capital. 21 | * 22 | * @param string with text. 23 | * @return string of formated text. 24 | */ 25 | public static String firstCharToTitleCase(String string) { 26 | char[] chars = string.toLowerCase().toCharArray(); 27 | boolean found = false; 28 | for (int i = 0; i < chars.length; i++) { 29 | if (!found && Character.isLetter(chars[i])) { 30 | chars[i] = Character.toUpperCase(chars[i]); 31 | found = true; 32 | } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // Possible to add other chars here 33 | found = false; 34 | } 35 | } 36 | return String.valueOf(chars); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/labs/practice3/Part4.java: -------------------------------------------------------------------------------- 1 | package labs.practice3; 2 | import java.security.MessageDigest; 3 | import java.security.NoSuchAlgorithmException; 4 | 5 | /** 6 | * Cashing string values with encodings from package java.security. 7 | * 8 | * Provides possibility to get hex representation of hash of the string. 9 | * 10 | * @author Andrey Pyatakha 11 | * 12 | */ 13 | 14 | public class Part4 { 15 | 16 | /** 17 | * Returns string of hex representation of byte array of hash algorithm. 18 | * 19 | * Uses string format to formatting each byte to hex representation. 20 | * 21 | * @param input text to receive hash. 22 | * @param algorithm for hashing 23 | * @return string with hex representation of hashing in specified algorithm. 24 | * @throws NoSuchAlgorithmException 25 | */ 26 | 27 | public static String hash(String input, String algorithm) throws NoSuchAlgorithmException { 28 | 29 | MessageDigest digest = MessageDigest.getInstance(algorithm); 30 | digest.update(input.getBytes()); 31 | byte[] hash = digest.digest(); 32 | StringBuilder sb = new StringBuilder(); 33 | for (byte b : hash) { 34 | sb.append(String.format("%02X, ", b)); 35 | } 36 | 37 | return sb.toString(); 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/labs/practice5/Part2.java: -------------------------------------------------------------------------------- 1 | package labs.practice5; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * Demonstrates work of Spam class. 10 | * 11 | * Create stream and reset System.in to another one stream. 12 | * 13 | * @author Andrey Pyatakha 14 | * 15 | */ 16 | 17 | public class Part2 { 18 | 19 | 20 | 21 | /** 22 | * Enter point to the Part2. 23 | * 24 | * Create stream and reset System.in to another one stream. 25 | * Run the main method of Spam2 class. 26 | * 27 | * After 5 seconds had passed change input stream and simulates pressing 28 | * of enter key. 29 | * 30 | * @param args input parameters 31 | * @throws IOException in case of Exception in main class 32 | * @throws InterruptedException in case of interruption of main thread 33 | */ 34 | public static void main(String[] args) throws IOException, InterruptedException { 35 | ByteArrayInputStream bais = new ByteArrayInputStream(new byte[]{'\n'}); 36 | Spam.main(new String[]{}); 37 | TimeUnit.SECONDS.sleep(5); 38 | System.setIn(bais); 39 | 40 | } 41 | 42 | } 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/labs/practice5/Part4.java: -------------------------------------------------------------------------------- 1 | package labs.practice5; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | import java.util.concurrent.Future; 5 | 6 | public class Part4 { 7 | 8 | private static final int COLUMNS = 100; 9 | private static final int ROWS = 4; 10 | 11 | public static void main(String[] args) throws InterruptedException, ExecutionException { 12 | int[][] matrix = SearchEngine.createRandomMatrix(ROWS, COLUMNS); 13 | 14 | SearchEngine se = new SearchEngine(matrix); 15 | 16 | System.out.println("======= Demo of MultiThreading Search ========"); 17 | System.out.println("Max element in matrix: " + se.getMaxElementInMatrixMultiThreading()); 18 | System.out.println("Time of multithreading search: " + se.getTimeOfMultiThreadingSearch()); 19 | 20 | System.out.println(); 21 | System.out.println("======= Demo of SingleThreading Search ========"); 22 | System.out.println("Max element in matrix: " + se.getMaxElementInMatrixSingleThreading()); 23 | System.out.println("Time of singlethreading search: " + se.getTimeOfSingleThreadingSearch()); 24 | 25 | System.out.println("\nPrinting the futureList: "); 26 | for (Future future : se.getFutureList()) { 27 | System.out.println(future.get()); 28 | } 29 | } 30 | 31 | 32 | 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/labs/practice6/Demo.java: -------------------------------------------------------------------------------- 1 | package labs.practice6; 2 | 3 | 4 | /** 5 | * Demonstrates work of all Parts from Practice6. 6 | * 7 | * @author Andrey Pyatakha 8 | * 9 | */ 10 | public class Demo { 11 | 12 | /** 13 | * Enter point to the Demo. 14 | * 15 | * Calls main methods of each Part from Practice6. 16 | * 17 | * @param args input parameters. 18 | * @throws Exception in case of exceptions in main methods of tasks. 19 | */ 20 | public static void main(String[] args) throws Exception { 21 | System.out.println("~~~~~~~~~~~~Part1"); 22 | Part1.main(args); 23 | 24 | System.out.println("~~~~~~~~~~~~Part2"); 25 | Part2.main(args); 26 | 27 | System.out.println("~~~~~~~~~~~~Part3"); 28 | Part3.main(args); 29 | // 30 | // System.out.println("~~~~~~~~~~~~Part4"); 31 | // Part4.main(args); 32 | // 33 | System.out.println("~~~~~~~~~~~~Part5"); 34 | Part5.main(args); 35 | 36 | System.out.println("~~~~~~~~~~~~Part6"); 37 | Part6.main(new String[]{"-i", "test.txt", "-t", "duplicates"}); 38 | 39 | System.out.println("~~~~~~~~~~~~Part7"); 40 | Part7.main(args); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/labs/practice6/Part3.java: -------------------------------------------------------------------------------- 1 | package labs.practice6; 2 | 3 | import labs.practice6.Parking.Car; 4 | 5 | /** 6 | * Demo class of Part3. 7 | * 8 | * @author Andrey Pyatakha 9 | * 10 | */ 11 | public class Part3 { 12 | 13 | /** 14 | * Enter point to the Part3. 15 | * 16 | * Creates parking. 17 | * 18 | * Then parks autos to the spots and takes them away. 19 | * Periodically prints the state of the parking 20 | * to the console. 21 | * 22 | * @param args input parameters. 23 | */ 24 | public static void main(String[] args) { 25 | Parking parking = new Parking(10); 26 | 27 | parking.parkAuto(new Car(), 2); 28 | System.out.println(parking); 29 | 30 | parking.parkAuto(new Car(), 2); 31 | parking.parkAuto(new Car(), 2); 32 | parking.parkAuto(new Car(), 2); 33 | 34 | System.out.println(parking); 35 | 36 | parking.deparkAuto(3); 37 | parking.deparkAuto(4); 38 | 39 | System.out.println(parking); 40 | 41 | parking.parkAuto(new Car(), 3); 42 | parking.parkAuto(new Car(), 3); 43 | parking.parkAuto(new Car(), 3); 44 | parking.parkAuto(new Car(), 3); 45 | parking.parkAuto(new Car(), 3); 46 | parking.parkAuto(new Car(), 3); 47 | parking.parkAuto(new Car(), 3); 48 | 49 | System.out.println(parking); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/labs/practice6/Part5.java: -------------------------------------------------------------------------------- 1 | package labs.practice6; 2 | 3 | /** 4 | * Demo class of Part5. 5 | * 6 | * Demonstrates how binary tree works. 7 | * 8 | * @author Andrey Pyatakha 9 | * 10 | */ 11 | public class Part5 { 12 | 13 | /** 14 | * Enter point to the Part5. 15 | * 16 | * Creates tree and fills it with the elements. 17 | * Printing the tree to console. 18 | * 19 | * Then, removes elements from the tree. 20 | * And again prints tree to console. 21 | * 22 | * @param args input parameters. 23 | */ 24 | public static void main(String[] args) { 25 | Tree tree = new Tree<>(); 26 | System.out.println(tree.add(3)); 27 | System.out.println(tree.add(3)); 28 | System.out.println("~~~~~~~"); 29 | tree.add(new Integer[] { 1, 2, 5, 4, 6, 0 }); 30 | tree.print(); 31 | System.out.println("~~~~~~~"); 32 | System.out.println(tree.remove(5)); 33 | System.out.println(tree.remove(5)); 34 | System.out.println("~~~~~~~"); 35 | tree.print(); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/labs/practice6/Part7.java: -------------------------------------------------------------------------------- 1 | package labs.practice6; 2 | 3 | import java.util.Iterator; 4 | 5 | /** 6 | * Demo of Part7. 7 | * 8 | * @author Andrey Pyatakha 9 | * 10 | */ 11 | 12 | public class Part7 { 13 | 14 | /** 15 | * Enter point to the Part7. 16 | * 17 | * Demonstrates the work of to types of iterators: in ascending 18 | * and descending order. 19 | * 20 | * Creates to objects of Part7 type. 21 | * 22 | * @param args input parameters. 23 | */ 24 | public static void main(String[] args) { 25 | Range obj = new Range(3, 10, true); 26 | 27 | Iterator iter = obj.iterator(); 28 | while (iter.hasNext()) { 29 | System.out.print(iter.next() + " "); 30 | } 31 | System.out.println(); 32 | 33 | Range obj2 = new Range(3, 10, false); 34 | 35 | Iterator iter2 = obj2.iterator(); 36 | while (iter2.hasNext()) { 37 | System.out.print(iter2.next() + " "); 38 | } 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/lessons/allgroups/DemoLesson.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | public class DemoLesson { 4 | 5 | private static String str; 6 | 7 | public static void main(String[] args) { 8 | System.out.println("Hello world"); 9 | 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/lessons/allgroups/GiftExample.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | public class GiftExample { 4 | String someProperty; 5 | 6 | protected String getter() { 7 | return ""; 8 | } 9 | 10 | GiftExample() { 11 | 12 | } 13 | 14 | public static void main(String[] args) { 15 | 16 | GiftExample ge = new ExampleChild(); 17 | ge.getter(); 18 | } 19 | 20 | } 21 | 22 | class ExampleChild extends GiftExample { 23 | 24 | @Override 25 | public String getter() { 26 | return ""; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/lessons/allgroups/Lesson2Part2.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Lesson2Part2 { 6 | 7 | public static void main(String[] args) { 8 | // int _1 = 1; 9 | // int String = 1; 10 | 11 | // try (Scanner sc = new Scanner(System.in);) { 12 | // int nextInt = sc.nextInt(); 13 | // System.out.println(nextInt); 14 | // } 15 | 16 | // for (String string : args) { 17 | // int i = 10; 18 | // System.out.println(string); 19 | // } 20 | 21 | System.out.println(4 << 3); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/lessons/allgroups/Lesson4ArrayStream.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.Stream; 5 | 6 | public class Lesson4ArrayStream { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] arr = {10215454, 254, 3}; 11 | Integer[] array = Arrays.stream(arr) 12 | .mapToObj(Integer::toString) 13 | .filter( str -> str.length() < 2) 14 | .map(Integer::valueOf) 15 | .toArray(Integer[]::new); 16 | System.out.println(Arrays.toString(array)); 17 | 18 | int sum = Arrays.stream(arr).sum(); 19 | System.out.println(sum); 20 | 21 | Integer[][] matrix = { 22 | {1, 2}, 23 | {3, 4} 24 | }; 25 | 26 | Integer[] array2 = Arrays.stream(matrix) 27 | .flatMap(x -> Arrays.stream(x)) 28 | .toArray(Integer[]::new); 29 | 30 | System.out.println(Arrays.toString(array2)); 31 | 32 | // .map(Integer::toString) 33 | // . 34 | 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/lessons/allgroups/Lesson4Methods.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | public class Lesson4Methods { 4 | 5 | public static void main(String... args) { 6 | int i = 1; 7 | doSmth(i); 8 | System.out.println(i); 9 | 10 | int[] arr = {1, 2, 3}; 11 | doSmth(arr); 12 | System.out.println(arr[1]); 13 | 14 | doSmth2(arr); 15 | System.out.println(arr); 16 | } 17 | 18 | private static void doSmth(int i) { 19 | i++; 20 | System.out.println("in method: " + i); 21 | } 22 | 23 | private static void doSmth(final int... arr) { 24 | arr[1] = 100; 25 | } 26 | 27 | private static void doSmth2(int... arr) { 28 | // do smth with arr final 29 | arr = null; 30 | 31 | // do smth more with the same arr 32 | System.out.println(arr); 33 | } 34 | 35 | private static int returnSmth() { 36 | return 1; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/lessons/allgroups/Lesson5.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Lesson5 { 6 | 7 | public static void main(String[] args) { 8 | Integer max = Arrays.stream(new int[2]) // Создание стрима 9 | .boxed() // Упаковка 10 | .max(Integer::compareTo) // Сравнение 11 | .get(); 12 | 13 | String s = "asdasd qadsad asdas !1:; =+=== qqwdqwd"; 14 | String[] split = s.split("\\s"); 15 | 16 | for (String string : split) { 17 | if(string.matches("[a-zA-Z]*")) { 18 | System.out.println(string); 19 | } 20 | } 21 | System.out.println(split.length); 22 | 23 | Arrays.stream(new int[1]).max().getAsInt(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/lessons/allgroups/Lesson9.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | public class Lesson9 { 4 | private int i; 5 | 6 | public void test() { 7 | int b = 0; 8 | i++; 9 | b++; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/lessons/allgroups/LessonIo.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | import java.io.File; 4 | import java.io.FileWriter; 5 | import java.io.FilenameFilter; 6 | import java.io.IOException; 7 | 8 | 9 | public class LessonIo { 10 | 11 | public static void main(String[] args) throws IOException { 12 | File dir = null; 13 | File[] fileList = dir.listFiles(new FilenameFilter() { 14 | public boolean accept(File dir, String name) { 15 | return name.endsWith(""); 16 | } 17 | }); 18 | 19 | File[] fileList2 = dir.listFiles((dir2, fileName) -> fileName.endsWith("")); 20 | 21 | try (FileWriter fw = new FileWriter(new File("")); 22 | FileWriter fw2 = new FileWriter(new File(""))) { 23 | 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/lessons/allgroups/LessonStringBuilder.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | public class LessonStringBuilder { 4 | 5 | public static void main(String[] args) { 6 | String[] strings = {}; 7 | 8 | StringBuilder sb = new StringBuilder(); 9 | for (String string : strings) { 10 | if (string.length() < 3) { 11 | sb.append(string); 12 | } 13 | } 14 | 15 | String str = sb.toString(); 16 | 17 | String result = ""; 18 | for (String string : strings) { 19 | if (string.length() < 3) { 20 | result += string; 21 | } 22 | } 23 | 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/lessons/allgroups/Questino.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | import java.util.Scanner; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class Questino { 7 | 8 | public static void main(String[] args) throws InterruptedException { 9 | // String result = scan(); 10 | 11 | long currentTimeMillis = System.nanoTime(); 12 | TimeUnit.MILLISECONDS.sleep(1); 13 | System.out.println("Time: " + (System.nanoTime() - currentTimeMillis)); 14 | } 15 | 16 | private static String scan() { 17 | Scanner scanner = new Scanner(System.in); 18 | System.out.print("Ввидите свой текст: \n"); 19 | StringBuffer textResult = new StringBuffer(); 20 | 21 | while (true) { 22 | String nextLine = scanner.nextLine(); 23 | if (nextLine.equals("exit")) 24 | break; 25 | textResult.append(nextLine).append(System.lineSeparator()); 26 | } 27 | 28 | return textResult.toString(); 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/lessons/allgroups/TriangleSquare.java: -------------------------------------------------------------------------------- 1 | package lessons.allgroups; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TriangleSquare { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | //Scanner in = new Scanner(System.in); 10 | int choise=1; 11 | double square, p; 12 | String temp; 13 | Scanner in = new Scanner(System.in); 14 | do { 15 | temp = ""; 16 | System.out.println("Введите через пробел высоту и сторону или три стороны треугольника:"); 17 | temp += in.nextLine(); 18 | String[] split = temp.split(" "); 19 | if(split.length==2) { 20 | square = 0.5 * Integer.parseInt(split[0])*Integer.parseInt(split[1]); 21 | System.out.println("Площадь треугольника равна 1//2 * a * h = " + square); 22 | } 23 | else { 24 | p = (Integer.parseInt(split[0])+Integer.parseInt(split[1])+Integer.parseInt(split[2]))/2; 25 | square = Math.sqrt(p*(p-Integer.parseInt(split[0]))*(p-Integer.parseInt(split[1]))*(p-Integer.parseInt(split[2]))); 26 | System.out.println("Площадь треугольника равна корню квадратному из (p*(p-a)*(p-b)*(p-c)) = " + square); 27 | } 28 | 29 | System.out.println("Input 0 to exit, to continue input any other digit:"); 30 | choise = in.nextInt(); 31 | 32 | }while(choise!=0); 33 | in.close(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/lessons/group10/LRUCaches.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | public class LRUCaches extends LinkedHashMap { 7 | 8 | private final int capacity; 9 | 10 | public LRUCaches(int capacity) { 11 | super(capacity, 1.1f, true); 12 | this.capacity = capacity; 13 | } 14 | 15 | public int get(int key) { 16 | return super.getOrDefault(key, -1); 17 | } 18 | 19 | public void put(int key, int value) { 20 | super.put(key, value); 21 | } 22 | 23 | @Override 24 | protected boolean removeEldestEntry(Map.Entry eldest) { 25 | return size() > capacity; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/lessons/group10/LRUDemo.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | public class LRUDemo { 4 | 5 | public static void main(String[] args) { 6 | 7 | LRUCaches cache = new LRUCaches(2); 8 | 9 | cache.put(1, 1); 10 | cache.put(2, 2); 11 | System.out.println(cache.get(1)); 12 | cache.put(3, 3); 13 | System.out.println(cache.get(2)); 14 | System.out.println(); 15 | cache.put(4, 4); 16 | System.out.println(cache.get(1)); 17 | System.out.println(cache.get(3)); 18 | System.out.println(cache.get(4)); 19 | 20 | cache.put(5, 5); 21 | System.out.println(cache.get(3)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/lessons/group10/Lesson13.java: -------------------------------------------------------------------------------- 1 | //package lessons.group10; 2 | // 3 | ////import org.apache.commons.lang3.SerializationUtils; 4 | // 5 | //public class Lesson13 { 6 | // 7 | // public static void main(String[] args) { 8 | // User pm = new User(); 9 | //// User deepCopy = (User) SerializationUtils.clone(pm); 10 | // 11 | // 12 | // } 13 | // 14 | //} 15 | -------------------------------------------------------------------------------- /src/lessons/group10/Lesson4.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Lesson4 { 6 | 7 | public static void main(String[] args) { 8 | String[] filteredStrings = filterStringsByCharacter(3, "String", "abs", "c", "da"); 9 | 10 | String[] arr = {}; 11 | Arrays.sort(arr, (str1, str2) -> { 12 | int result = str2.length() - str1.length(); 13 | if (result == 0) { 14 | return str1.compareToIgnoreCase(str2); 15 | } else { 16 | return result; 17 | } 18 | }); 19 | } 20 | 21 | private static String[] filterStringsByCharacter(int amountOfChars, 22 | String... arr) { 23 | return Arrays.stream(arr) 24 | .filter((s) -> s.length() > 3) 25 | .toArray(String[]::new); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/lessons/group10/Lesson9.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | public class Lesson9 { 4 | 5 | public static void main(String[] args) { 6 | 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/lessons/group10/LessonOOPChild.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | public class LessonOOPChild extends LessonOOP { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group10/LessonOOPDemo.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | public class LessonOOPDemo { 4 | 5 | public static void main(String[] args) { 6 | 7 | LessonOOP obj = new LessonOOP(15, "1"); 8 | LessonOOP obj2 = new LessonOOP(20, "10"); 9 | System.out.println(obj.getAge()); 10 | 11 | LessonOOP.doSmth(); 12 | obj.doSmth(); 13 | 14 | LessonOOP.NestedClass nestedObj = new LessonOOP.NestedClass(); 15 | System.out.println(); 16 | 17 | LessonOOP.InnerClass inner = new LessonOOP().new InnerClass(); 18 | 19 | LessonOOPChild child = new LessonOOPChild(); 20 | child.getAge(); 21 | 22 | SpaceRocket[] rockets = {new UserOop()}; 23 | for (SpaceRocket spaceRocket : rockets) { 24 | spaceRocket.flyAsRocket(); 25 | } 26 | 27 | 28 | LessonOOPI[] interfaces = {new UserOop()}; 29 | for (LessonOOPI lessonOOPI : interfaces) { 30 | lessonOOPI.doSmth(); 31 | } 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/lessons/group10/Test.java: -------------------------------------------------------------------------------- 1 | package lessons.group10; 2 | 3 | public class Test { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(0 / 0.0); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/lessons/group11/Address.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | public class Address { 4 | 5 | private String country; 6 | private String city; 7 | private String street; 8 | private String building; 9 | 10 | public Address() { 11 | } 12 | public Address(String country) { 13 | this.country = country; 14 | } 15 | public String getCountry() { 16 | return country; 17 | } 18 | public void setCountry(String country) { 19 | this.country = country; 20 | } 21 | public String getCity() { 22 | return city; 23 | } 24 | public void setCity(String city) { 25 | this.city = city; 26 | } 27 | public String getStreet() { 28 | return street; 29 | } 30 | public void setStreet(String street) { 31 | this.street = street; 32 | } 33 | public String getBuilding() { 34 | return building; 35 | } 36 | public void setBuilding(String building) { 37 | this.building = building; 38 | } 39 | @Override 40 | public String toString() { 41 | return "Address [country=" + country + ", city=" + city + ", street=" + street + ", building=" + building + "]"; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/lessons/group11/DebugDemo.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | public class DebugDemo { 4 | 5 | public static void main(String[] args) { 6 | 7 | String str = "Hello"; 8 | for (char c : str.toCharArray()) { 9 | System.out.println(c); 10 | int i = c - 10; 11 | doSomething(); 12 | } 13 | 14 | 15 | } 16 | 17 | private static void doSomething() { 18 | int i = 10; 19 | System.out.println(i); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/lessons/group11/DemoOop.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | public abstract class DemoOop { 4 | 5 | public abstract void doSmth(); 6 | 7 | public static void main(String[] args) { 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/lessons/group11/DemoOopHw.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.util.Arrays; 4 | 5 | public class DemoOopHw { 6 | 7 | public static void main(String[] args) { 8 | StudentService ss = new StudentService(); 9 | 10 | Student[] students = ss.generateRandomStudents(5); 11 | Address address = new Address("Ukraine"); 12 | 13 | students[0].setAddress(address); 14 | students[1].setAddress(address); 15 | 16 | Student[] filteredStudentsByCountry = ss.filterStudentsByCountry("ukraine", students); 17 | System.out.println(Arrays.toString(filteredStudentsByCountry)); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/lessons/group11/IoLesson.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.io.IOException; 4 | import java.nio.charset.StandardCharsets; 5 | import java.nio.file.Files; 6 | import java.nio.file.Paths; 7 | import java.nio.file.StandardOpenOption; 8 | import java.util.stream.Stream; 9 | 10 | public class IoLesson { 11 | 12 | public static void main(String[] args) throws IOException { 13 | 14 | // try (Stream lines 15 | // = Files.lines(Paths 16 | // .get("asciireadDemo.txt"), 17 | // StandardCharsets.UTF_8)) { 18 | // lines.forEach((string) -> System.out.println(string)); 19 | // } 20 | // 21 | // Files.write(Paths 22 | // .get("asciireadDemo.txt"), 23 | // "привет!".getBytes(), 24 | // StandardOpenOption.APPEND); 25 | 26 | StringBuilder sb = new StringBuilder(); 27 | String result = ""; 28 | for (String string : new String[]{"apple", "orange", "banana"}) { 29 | sb.append(string); 30 | } 31 | 32 | System.out.println(result); 33 | System.out.println(sb.toString()); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/lessons/group11/Lesson2Arrays.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | public class Lesson2Arrays { 7 | 8 | public static void main(String[] args) { 9 | String[] productNames = { "Banana", "Apple", "Tesla" }; 10 | String[] productNames2 = new String[10]; 11 | 12 | System.out.println(productNames[1]); 13 | System.out.println(productNames2[1]); 14 | 15 | productNames2[1] = "Apple 2"; 16 | System.out.println(productNames2[1]); 17 | 18 | int[] integers = new int[10]; 19 | System.out.println(integers[1]); 20 | 21 | int[][][] matrix = { { { 1, 2, 3 }, { 4, 5, 6 } }, 22 | 23 | { { 1, 2, 3 }, { 4, 5, 6 } } }; 24 | 25 | System.out.println(matrix[0][0][1]); 26 | System.out.println(productNames[2]); 27 | 28 | // ========================= 29 | 30 | Integer[] ints = { 101, 20001, 1, 5, -2, 5000 }; 31 | System.out.println(Arrays.toString(ints)); 32 | Arrays.sort(ints); 33 | System.out.println(Arrays.toString(ints)); 34 | Arrays.sort(ints, (i1, i2) -> i2 - i1); 35 | System.out.println(Arrays.toString(ints)); 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/lessons/group11/Lesson3.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Lesson3 { 6 | 7 | public static void main(String[] args) { 8 | BigDecimal bd = null; 9 | String[] arr = new String[10]; 10 | System.out.println(arr[2]); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/lessons/group11/Lesson4.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | public class Lesson4 { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group11/StreamDemo.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class StreamDemo { 8 | 9 | public static void main(String[] args) { 10 | List strings = 11 | new ArrayList<>(Arrays.asList("apple", "orange", "banana", "apple")); 12 | 13 | int sum = strings.stream() 14 | .distinct() 15 | .mapToInt(str -> str.length()) 16 | .sum(); 17 | 18 | System.out.println(sum); 19 | 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/lessons/group11/StreamDemo2.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | import java.util.stream.Stream; 10 | 11 | public class StreamDemo2 { 12 | 13 | 14 | public static void main(String[] args) throws IOException { 15 | List atWords = Files.lines(Paths.get("esenin.txt")) 16 | .map(line -> line.split("\\s")) 17 | .flatMap(stringArray -> Arrays.stream(stringArray)) 18 | .filter(word -> word.contains("@")) 19 | .collect(Collectors.toList()); 20 | 21 | String[] stream = Files.lines(Paths.get("esenin.txt")) 22 | .map(line -> line.split("\\s")) 23 | .toArray(String[]::new); 24 | 25 | Stream map = Files.lines(Paths.get("esenin.txt")) 26 | .map(line -> line.split("\\s")); 27 | 28 | Stream flatMap = Files.lines(Paths.get("esenin.txt")) 29 | .map(line -> line.split("\\s")) 30 | .flatMap(stringArray -> Arrays.stream(stringArray)); 31 | 32 | 33 | System.out.println(atWords); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/lessons/group11/Student.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | public class Student { 4 | 5 | private int id; 6 | private String lastName; 7 | private String firstName; 8 | private Address address; 9 | 10 | public Student() { 11 | } 12 | 13 | public Student(int id, String lastName, String firstName) { 14 | this.id = id; 15 | this.lastName = lastName; 16 | this.firstName = firstName; 17 | } 18 | 19 | public int getId() { 20 | return id; 21 | } 22 | 23 | public void setId(int id) { 24 | this.id = id; 25 | } 26 | 27 | public String getLastName() { 28 | return lastName; 29 | } 30 | 31 | public void setLastName(String lastName) { 32 | this.lastName = lastName; 33 | } 34 | 35 | public String getFirstName() { 36 | return firstName; 37 | } 38 | 39 | public void setFirstName(String firstName) { 40 | this.firstName = firstName; 41 | } 42 | 43 | public Address getAddress() { 44 | return address; 45 | } 46 | 47 | public void setAddress(Address address) { 48 | this.address = address; 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return "Student [id=" + id + ", lastName=" + lastName + ", firstName=" + firstName + ", address=" + address 54 | + "]"; 55 | } 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/lessons/group11/StudentService.java: -------------------------------------------------------------------------------- 1 | package lessons.group11; 2 | 3 | import java.util.Arrays; 4 | 5 | public class StudentService { 6 | 7 | public Student[] generateRandomStudents(int studentsAmount) { 8 | Student[] students = new Student[studentsAmount]; 9 | for (int i = 0; i < studentsAmount; i++) { 10 | students[i] = new Student(i, "LastName" + i, "FirstName" + i); 11 | } 12 | return students; 13 | } 14 | 15 | public Student[] filterStudentsByCountry(String country, Student[] students) { 16 | return Arrays.stream(students) 17 | .filter((student) 18 | -> { 19 | if (student.getAddress() != null && student.getAddress().getCountry() != null) { 20 | return student.getAddress().getCountry().equalsIgnoreCase(country); 21 | } else { 22 | return false; 23 | } 24 | }) 25 | .toArray(Student[]::new); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/lessons/group11/TextAnalyzer.java: -------------------------------------------------------------------------------- 1 | //package lessons.group11; 2 | // 3 | //import java.io.IOException; 4 | //import java.nio.file.Files; 5 | //import java.nio.file.Paths; 6 | //import java.util.ArrayList; 7 | //import java.util.Arrays; 8 | //import java.util.List; 9 | // 10 | //public class TextAnalyzer { 11 | // 12 | // private static List vowels; 13 | // 14 | // static { 15 | // vowels = new ArrayList<>(Arrays.asList('а','у', 'е', 'э', 16 | // 'о', 'ы', 'я', 'и', 'ю')); 17 | // } 18 | // 19 | // 20 | // public int findLineWithMostVowels(String fileName) throws IOException { 21 | // int lineIndex = 0; 22 | // long maxVowels = 0; 23 | // 24 | // List lines = Files.readAllLines(Paths.get(fileName)); 25 | // 26 | // for (int i = 0; i < lines.size(); i++) { 27 | // long vowelsInLine = calculateVowelsInLine(lines.get(i)); 28 | // if (maxVowels < vowelsInLine) { 29 | // maxVowels = vowelsInLine; 30 | // lineIndex = i; 31 | // } 32 | // } 33 | // 34 | // return lineIndex + 1; 35 | // } 36 | // 37 | // private long calculateVowelsInLine(String line) { 38 | // Character[] chars = 39 | // line.toLowerCase() 40 | // .chars() 41 | // .mapToObj(c -> (char)c).toArray(Character[]::new); 42 | // 43 | // return Arrays.stream(chars) 44 | // .filter(c -> vowels.contains(c)) 45 | // .count(); 46 | // } 47 | // 48 | //} 49 | -------------------------------------------------------------------------------- /src/lessons/group11/TextAnalyzerDemo.java: -------------------------------------------------------------------------------- 1 | //package lessons.group11; 2 | // 3 | //import java.io.IOException; 4 | // 5 | //public class TextAnalyzerDemo { 6 | // 7 | // public static void main(String[] args) throws IOException { 8 | // TextAnalyzer textAnalyzer = new TextAnalyzer(); 9 | // int lineWithMaxVowels = textAnalyzer.findLineWithMostVowels("esenin.txt"); 10 | // System.out.println(lineWithMaxVowels); 11 | // } 12 | // 13 | //} 14 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/Candy.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | public abstract class Candy extends Sweet { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/ChocolateCandy.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | public class ChocolateCandy extends Candy { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/Cookie.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | public abstract class Cookie extends Sweet { 4 | 5 | private double doughWeight; 6 | 7 | public double getDoughWeight() { 8 | return doughWeight; 9 | } 10 | 11 | public void setDoughWeight(double doughWeight) { 12 | this.doughWeight = doughWeight; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/Demo.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Demo { 6 | 7 | 8 | public static void main(String[] args) { 9 | Sweet candy = new ChocolateCandy(); 10 | candy.setName("Krasnyi Mak"); 11 | candy.setSugarWeight(0.53); 12 | candy.setWeight(0.05); 13 | 14 | Cookie cookie = new Ovsyanoe(); 15 | cookie.setName("Ovsyonaoy"); 16 | cookie.setSugarWeight(0.1); 17 | cookie.setDoughWeight(0.3); 18 | cookie.setWeight(0.2); 19 | 20 | Sweet lollipop = new Lollipop(); 21 | lollipop.setWeight(0.5); 22 | lollipop.setName("Lollipop"); 23 | lollipop.setSugarWeight(0.2); 24 | 25 | Gift gift = new Gift(); 26 | gift.addSweet(candy); 27 | gift.addSweet(cookie); 28 | gift.addSweet(lollipop); 29 | 30 | Sweet[] filteredSweets = gift.filterSweetsBySugar(0, 0.20); 31 | System.out.println(Arrays.toString(filteredSweets)); 32 | 33 | System.out.println("Total gift weight: " + gift.calculateWeight()); 34 | System.out.println("Dough weight: " + gift.calculateDoughWeight()); 35 | 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/Lollipop.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | public class Lollipop extends Candy { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/Ovsyanoe.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | public class Ovsyanoe extends Cookie { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group11/presenthw/Sweet.java: -------------------------------------------------------------------------------- 1 | package lessons.group11.presenthw; 2 | 3 | public abstract class Sweet { 4 | 5 | private String name; 6 | private double weight; // kg 7 | private double sugarWeight; // kg 8 | 9 | 10 | 11 | public double getWeight() { 12 | return weight; 13 | } 14 | public void setWeight(double weight) { 15 | this.weight = weight; 16 | } 17 | public double getSugarWeight() { 18 | return sugarWeight; 19 | } 20 | public void setSugarWeight(double sugarWeight) { 21 | this.sugarWeight = sugarWeight; 22 | } 23 | public String getName() { 24 | return name; 25 | } 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | @Override 30 | public String toString() { 31 | return "Sweet [name=" + name + ", weight=" + weight + ", sugarWeight=" + sugarWeight + "]"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/lessons/group2/FunctionalInterfaceTest.java: -------------------------------------------------------------------------------- 1 | package lessons.group2; 2 | 3 | @FunctionalInterface 4 | public interface FunctionalInterfaceTest { 5 | 6 | void doSmth(); 7 | 8 | default void doSmth2() { 9 | 10 | } 11 | 12 | static void doSmth3() { 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/lessons/group2/Lesson13_2.java: -------------------------------------------------------------------------------- 1 | package lessons.group2; 2 | 3 | import java.time.Instant; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | //import org.apache.commons.collections4.queue.CircularFifoQueue; 10 | 11 | public class Lesson13_2 { 12 | 13 | public static void main(String[] args) { 14 | // CircularFifoQueue str = new CircularFifoQueue<>(); 15 | 16 | Collection c = new ArrayList(); 17 | // c.add(new Object()); // Compile time error 18 | c.add(null); 19 | 20 | List emptyList = Collections.EMPTY_LIST; 21 | System.out.println(Instant.EPOCH); 22 | long start = System.currentTimeMillis(); 23 | // some function; 24 | long delta = System.currentTimeMillis() - start; 25 | 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/lessons/group2/Lesson17.java: -------------------------------------------------------------------------------- 1 | package lessons.group2; 2 | 3 | public class Lesson17 { 4 | 5 | public static void main(String[] args) { 6 | } 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/lessons/group2/Lesson20.java: -------------------------------------------------------------------------------- 1 | package lessons.group2; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.SQLException; 6 | 7 | public class Lesson20 { 8 | 9 | public static void main(String[] args) throws SQLException { 10 | // Lesson20.class.getResourceAsStream(""); 11 | // Lesson20.class.getClassLoader().getResourceAsStream(""); 12 | // 13 | // try (Connection conn = null; 14 | // PreparedStatement ps = conn.prepareStatement("")) { 15 | // 16 | // } 17 | 18 | System.out.println(new Impl().getThisClass()); 19 | } 20 | 21 | } 22 | 23 | abstract class Abstr1 { 24 | 25 | public Class getThisClass() { 26 | return this.getClass(); 27 | } 28 | 29 | } 30 | 31 | class Impl extends Abstr1 { 32 | 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/lessons/group2/Lesson2_2.java: -------------------------------------------------------------------------------- 1 | package lessons.group2; 2 | 3 | import java.util.Comparator; 4 | 5 | public class Lesson2_2 implements Comparator { 6 | 7 | @Override 8 | public int compare(String o1, String o2) { 9 | // TODO Auto-generated method stub 10 | return 0; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/lessons/group2/Lessont4_2.java: -------------------------------------------------------------------------------- 1 | package lessons.group2; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Lessont4_2 { 6 | 7 | public static void main(String[] args) { 8 | String[] arr = { "1", "asda", "as", "asd"}; 9 | String[] arr2 = new String[10]; 10 | Arrays.sort(arr); 11 | 12 | 13 | int sum = Arrays.stream(arr) 14 | // .forEach(System.out::println); 15 | .map( string -> string.length()) 16 | .mapToInt(Integer::valueOf) 17 | .sum(); 18 | 19 | String[] array = Arrays.stream(arr) 20 | .filter( string -> string.length() > 2) 21 | .toArray(String[]::new); 22 | 23 | System.out.println(Arrays.toString(arr)); 24 | System.out.println(Arrays.toString(array)); 25 | 26 | System.out.println(sum); 27 | 28 | } 29 | 30 | public int doSmth(int... arr) { 31 | int i = arr[0]; 32 | return 1; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/lessons/group2/PseudoTests.java: -------------------------------------------------------------------------------- 1 | //package lessons.group2; 2 | // 3 | //import org.junit.Before; 4 | //import org.junit.Test; 5 | // 6 | //import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException; 7 | // 8 | //public class PseudoTests { 9 | // 10 | // private Parser testInstance; 11 | // 12 | // @Before 13 | // public void setUp() { 14 | // testInstance = new Parser(); 15 | // } 16 | // 17 | // @Test 18 | // public void shouldParseValidFile() { 19 | // String filePathToValidFile = "validFile.xml"; 20 | // 21 | // Container actualContainer = testInstance.parse(filePathToValidFile); 22 | // 23 | // Container expectedContainer = getExpectedContainer(); 24 | // assertEquals(actualContainer, expectedContainer); 25 | // } 26 | // 27 | // @Test(expected = ParseException.class) 28 | // public void shouldThrowExceptionIfFileIsInvalid() { 29 | // String filePathToInvalidFile = "invalidFile.xml"; 30 | // 31 | // Container actualContainer = testInstance.parse(filePathToValidFile); 32 | // } 33 | // 34 | // private Container getExpectedContainer() { 35 | // // TODO returns valid Container 36 | // return null; 37 | // } 38 | // 39 | //} 40 | -------------------------------------------------------------------------------- /src/lessons/group6/Lesson2.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | import java.io.IOException; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | 7 | public class Lesson2 { 8 | 9 | public static void main(String[] args) { 10 | 11 | Thread t = new Thread(() -> { 12 | System.out.println(Thread.currentThread()); 13 | 14 | throw new RuntimeException(new IOException()); 15 | }); 16 | 17 | t.start(); 18 | System.out.println(Thread.currentThread().getName()); 19 | 20 | ExecutorService es = Executors.newFixedThreadPool(2); 21 | es.execute(() -> System.out.println(Thread.currentThread())); 22 | // es.submit(task) 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/lessons/group6/Lesson3.java: -------------------------------------------------------------------------------- 1 | //package lessons.group6; 2 | // 3 | //import static org.junit.Assert.assertEquals; 4 | // 5 | //import java.io.ByteArrayInputStream; 6 | //import java.io.File; 7 | //import java.io.FileNotFoundException; 8 | //import java.io.PrintStream; 9 | // 10 | //public class Lesson3 { 11 | // 12 | // private Object o; 13 | // 14 | // public Lesson3() { 15 | // this.o = new Object(); 16 | // } 17 | // 18 | // public void testDirections() throws FileNotFoundException { 19 | //// askDirection(); 20 | // 21 | // System.setIn(new ByteArrayInputStream("n".getBytes())); 22 | // 23 | // PrintStream ps = new PrintStream(new File("someFile")); 24 | // System.setOut(ps); 25 | // String fileContent = ""; 26 | // 27 | // assertEquals("north", fileContent); 28 | // } 29 | // 30 | //} 31 | -------------------------------------------------------------------------------- /src/lessons/group6/Lesson7.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Lesson7 { 6 | 7 | public static void main(String[] args) { 8 | String regex = ",|\n"; 9 | String s = "1,2*3*3\n"; 10 | String[] split = s.split("\\D"); 11 | System.out.println(Arrays.toString(split)); 12 | } 13 | 14 | public int sum(Integer a, Integer b) { 15 | if (a == null || b == null) { 16 | throw new RuntimeException(new IllegalArgumentException("Some expected meessage")); 17 | } 18 | return a + b; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/lessons/group6/LruCache.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | public class LruCache extends LinkedHashMap { 7 | private final int capacity; 8 | 9 | public LruCache(int capacity) { 10 | super(capacity, 1.1f, true); 11 | this.capacity = capacity; 12 | 13 | } 14 | 15 | public int get(int key) { 16 | return super.getOrDefault(key,-1); 17 | } 18 | 19 | public void put(int key, int value) { 20 | super.put(key, value); 21 | } 22 | @Override 23 | protected boolean removeEldestEntry(Map.Entry eldest) { 24 | return size() > capacity; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/lessons/group6/Test.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CopyOnWriteArrayList; 6 | 7 | public class Test { 8 | 9 | public static void main(String[] args) { 10 | // float f = Math.round(float(1123 % 1000 ) * 100); 11 | // System.out.println(f); 12 | 13 | // System.out.println(900 % 1000); 14 | // System.out.println( (float)123 / 1000); 15 | 16 | // A121 a = new B121(); 17 | // a.doSmthChild(); 18 | 19 | B121 b = new A121(); 20 | 21 | dosmthWithList(new CopyOnWriteArrayList<>()); 22 | b.doSmthParent(); 23 | } 24 | 25 | public static void dosmthWithList(List list) { 26 | 27 | } 28 | 29 | } 30 | 31 | 32 | class A121 extends B121 { 33 | 34 | public void doSmthChild() { 35 | 36 | } 37 | 38 | public void doSmthParent(){ 39 | 40 | } 41 | 42 | } 43 | 44 | class B121 extends C121 { 45 | 46 | public void doSmthParent(){ 47 | 48 | } 49 | } 50 | 51 | class C121 { 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/lessons/group6/Test2.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | public class Test2 { 4 | 5 | public static void main(String[] args) { 6 | int i = (int) Math.ceil(910 * 0.1); 7 | System.out.println(i); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/lessons/group6/Test3.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | import java.text.DecimalFormat; 4 | import java.text.NumberFormat; 5 | 6 | public class Test3 { 7 | 8 | public static void main(String[] args) { 9 | double d = 1; 10 | NumberFormat formatter = new DecimalFormat("##.00"); 11 | System.out.print(formatter.format(d)); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/lessons/group6/TestLruCache.java: -------------------------------------------------------------------------------- 1 | package lessons.group6; 2 | 3 | public class TestLruCache { 4 | 5 | public static void main(String[] args) { 6 | 7 | LruCache obj = new LruCache(2); 8 | obj.put(1, 1); 9 | obj.put(2, 2); 10 | System.out.println(obj.get(1)); 11 | 12 | obj.put(3,3); 13 | System.out.println(obj.get(2)); 14 | obj.put(4,4); 15 | System.out.println(); 16 | System.out.println(obj.get(1)); 17 | System.out.println(obj.get(3)); 18 | System.out.println(obj.get(4)); 19 | } 20 | } -------------------------------------------------------------------------------- /src/lessons/group7/CallableDemo.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.Future; 7 | 8 | public class CallableDemo { 9 | 10 | public static void main(String[] args) throws InterruptedException, ExecutionException { 11 | 12 | ExecutorService es = Executors.newFixedThreadPool(2); 13 | Future future = es.submit(CallableDemo::doSmth); 14 | Future future2 = es.submit(() -> 1); 15 | // TreeMap tM = new TreeMap((obj1, obj2) -> 1); 16 | 17 | System.out.println(future.get()); 18 | 19 | es.shutdown(); 20 | 21 | // es.shutdownNow(); 22 | while (true) { 23 | 24 | if (es.isTerminated()) { 25 | break; 26 | } 27 | } 28 | System.out.println(); 29 | 30 | } 31 | 32 | public static Integer doSmth() { 33 | return 1; 34 | } 35 | 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/lessons/group7/DeadLockExample.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class DeadLockExample { 6 | 7 | private static Object a = new Object(); 8 | private static Object b = new Object(); 9 | 10 | public static void main(String[] args) { 11 | Thread t = new Thread(DeadLockExample::runThread1); 12 | Thread t2 = new Thread(DeadLockExample::runThread2); 13 | 14 | t.start(); 15 | t2.start(); 16 | 17 | 18 | 19 | } 20 | 21 | public static void runThread1() { 22 | synchronized (a) { 23 | System.out.println("A CAPTURED"); 24 | try { 25 | TimeUnit.MILLISECONDS.sleep(100); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | synchronized (b) { 30 | System.out.println("B CAPTURED"); 31 | } 32 | 33 | } 34 | } 35 | 36 | public static void runThread2() { 37 | synchronized (b) { 38 | System.out.println("ahahah - B captured"); 39 | synchronized (a) { 40 | System.out.println("You will never get here"); 41 | 42 | } 43 | } 44 | } 45 | 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/lessons/group7/MultithreadingHw.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.IntStream; 7 | 8 | public class MultithreadingHw { 9 | 10 | 11 | public static void main(String[] args) { 12 | int start = 1; 13 | int finish = 1000; 14 | int threads = 3; 15 | 16 | List primeNumbers = new ArrayList<>(); 17 | List list = IntStream 18 | .range(1, 1000) 19 | .boxed() 20 | .collect(Collectors.toList()); 21 | 22 | // for(int i = start; i <= 1000; i++) { 23 | // list.add(i); 24 | // } 25 | 26 | // System.out.println(list); 27 | 28 | 29 | int step = list.size() / threads; 30 | int i2 = 0; 31 | 32 | 33 | for (int i = 0; i < threads; i++) { 34 | List numbersToProceed1 = list.subList(i2, i2 + step); 35 | i2 += step; 36 | Thread t = new Thread(new PrimeNumberSearcher(numbersToProceed1, primeNumbers)); 37 | t.start(); 38 | } 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/lessons/group7/MyCallable.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Callable; 5 | 6 | public class MyCallable implements Callable{ 7 | 8 | private List numbersToFind; 9 | 10 | public MyCallable(List numbers) { 11 | this.numbersToFind = numbers; 12 | } 13 | 14 | @Override 15 | public Integer call() throws Exception { 16 | return numbersToFind.stream().mapToInt((i) -> i).max().getAsInt(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/lessons/group7/PrimeNumberSearcher.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.List; 4 | 5 | public class PrimeNumberSearcher implements Runnable { 6 | 7 | private List numbersToProceed; 8 | private List primeNumbers; 9 | private PrimeService primeService; 10 | 11 | public PrimeNumberSearcher(List numbersToProceed, List primeNumbers) { 12 | this.numbersToProceed = numbersToProceed; 13 | this.primeNumbers = primeNumbers; 14 | this.primeService = new PrimeService(); 15 | } 16 | 17 | @Override 18 | public void run() { 19 | for (Integer integer : numbersToProceed) { 20 | if (primeService.isPrime(integer)) { 21 | primeNumbers.add(integer); 22 | } 23 | } 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/lessons/group7/PrimeService.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | public class PrimeService { 4 | 5 | public boolean isPrime(Integer integer) { 6 | return true; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/lessons/group7/ThreadLesson.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class ThreadLesson { 6 | 7 | public static void main(String[] args) throws InterruptedException { 8 | Thread t = new Thread(new ThreadExample()); 9 | t.setDaemon(true); 10 | t.start(); 11 | 12 | TimeUnit.SECONDS.sleep(1); 13 | 14 | System.out.println("Good bye"); 15 | } 16 | 17 | } 18 | 19 | 20 | class ThreadExample implements Runnable { 21 | 22 | @Override 23 | public void run() { 24 | while(true) { 25 | System.out.println("Hello"); 26 | } 27 | } 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/lessons/group7/ThreadLesson2.java: -------------------------------------------------------------------------------- 1 | package lessons.group7; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class ThreadLesson2 { 6 | 7 | private static void printToConsole() { 8 | while (true) { 9 | System.out.println(Thread.currentThread().getName()); 10 | } 11 | } 12 | 13 | public static void main(String[] args) throws InterruptedException { 14 | Thread t = new Thread(ThreadLesson2::printToConsole); 15 | Thread t2 = new Thread(ThreadLesson2::printToConsole); 16 | 17 | t.setDaemon(true); 18 | t2.setDaemon(true); 19 | 20 | t.start(); 21 | t2.start(); 22 | 23 | TimeUnit.SECONDS.sleep(1); 24 | Thread.sleep(1000); 25 | TimeUnit.MILLISECONDS.sleep(1000); 26 | TimeUnit.DAYS.sleep(1); 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/lessons/group8/Lesson10.java: -------------------------------------------------------------------------------- 1 | package lessons.group8; 2 | 3 | public class Lesson10 extends Lesson9 { 4 | 5 | public void doSmth1() { 6 | 7 | } 8 | 9 | public static void main(String[] args) throws CloneNotSupportedException { 10 | Lesson9 l = new Lesson9(); 11 | Lesson9 clone = (Lesson9) l.clone(); 12 | System.out.println(l.b == clone.b); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/lessons/group8/Lesson11.java: -------------------------------------------------------------------------------- 1 | package lessons.group8; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | import java.util.Queue; 7 | 8 | public class Lesson11 { 9 | 10 | private List someList; 11 | 12 | public static void main(String[] args) { 13 | 14 | List list = new ArrayList<>(); 15 | list.add("a"); 16 | 17 | // String string = list.get(0); 18 | // System.out.println(list.size()); 19 | // 20 | // for (Object object : list) { 21 | // System.out.println(object); 22 | // } 23 | 24 | 25 | Iterator iterator = list.iterator(); 26 | System.out.println(iterator.next()); 27 | 28 | iterator = list.iterator(); 29 | while (iterator.hasNext()) { 30 | System.out.println(iterator.next()); 31 | } 32 | 33 | } 34 | 35 | public void doSmth(List list) { 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/lessons/group8/Lesson14.java: -------------------------------------------------------------------------------- 1 | package lessons.group8; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.util.Arrays; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.Future; 9 | 10 | public class Lesson14 { 11 | 12 | public static void main(String[] args) throws InterruptedException, ExecutionException { 13 | // Integer[] arr = {1, 2, 3}; 14 | // Integer[] array = Arrays.stream(arr).filter(i -> i % 2 == 0).toArray(Integer[]::new); 15 | // System.out.println(Arrays.toString(array)); 16 | 17 | // Thread t = new Thread(() -> { 18 | // System.out.println(Thread.currentThread().getName()); 19 | // throw new RuntimeException(new FileNotFoundException()); 20 | // }, "NEW THREAD"); 21 | // t.start(); 22 | // System.out.println(Thread.currentThread().getName()); 23 | 24 | ExecutorService es = Executors.newFixedThreadPool(2); 25 | Future future = es.submit(() -> { 26 | return 1 + 2; 27 | }); 28 | 29 | System.out.println(future.get()); 30 | 31 | 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/lessons/group8/Lesson5.java: -------------------------------------------------------------------------------- 1 | package lessons.group8; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.Collectors; 5 | 6 | public class Lesson5 { 7 | 8 | public static void main(String[] args) { 9 | String[] array = { "I ", "could ", "not ", "do", "it", "without", "list" }; 10 | String[] filteredArray = Arrays.stream(array) 11 | .filter(x -> x.length() > 3) 12 | // .collect(Collectors.toList()); 13 | .toArray(String[]::new); 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/lessons/group8/Lesson9.java: -------------------------------------------------------------------------------- 1 | package lessons.group8; 2 | 3 | public class Lesson9 implements Cloneable { 4 | 5 | public B123 b; 6 | public int i; 7 | 8 | public Lesson9() { 9 | // this.b = b; 10 | this.b = new B123(); 11 | } 12 | 13 | public void doSmth() { 14 | b.doSmthSpecific(); 15 | } 16 | 17 | @Override 18 | public Object clone() throws CloneNotSupportedException { 19 | // Lesson9 l = new Lesson9(); 20 | 21 | return super.clone(); 22 | } 23 | 24 | // public static void main(String[] args) { 25 | // B123 b = new B123(); 26 | //// Lesson9 l = new Lesson9(b); 27 | // Lesson9 l = new Lesson9(); 28 | //// l.doSmthSpecific(); 29 | // l = null; 30 | // 31 | // } 32 | 33 | } 34 | 35 | class B123 { 36 | 37 | public void doSmthSpecific() { 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/lessons/group8/TestClass.java: -------------------------------------------------------------------------------- 1 | package lessons.group8; 2 | 3 | public class TestClass { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("hello"); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/lessons/group8/exampledao/Demo.java: -------------------------------------------------------------------------------- 1 | package lessons.group8.exampledao; 2 | 3 | import lessons.group8.exampledao.dao.UserDao; 4 | import lessons.group8.exampledao.dao.impl.DefaultUserDao; 5 | 6 | public class Demo { 7 | 8 | public static void main(String[] args) { 9 | 10 | UserDao userDao = new DefaultUserDao(); 11 | userDao.getUserById(); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/lessons/group8/exampledao/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package lessons.group8.exampledao.dao; 2 | 3 | import lessons.group8.exampledao.models.UserData; 4 | 5 | public interface UserDao { 6 | 7 | UserData getUserById(); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/lessons/group8/exampledao/models/UserData.java: -------------------------------------------------------------------------------- 1 | package lessons.group8.exampledao.models; 2 | 3 | public class UserData { 4 | 5 | private int id; 6 | private String name; 7 | 8 | public int getId() { 9 | return id; 10 | } 11 | public void setId(int id) { 12 | this.id = id; 13 | } 14 | public String getName() { 15 | return name; 16 | } 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/lessons/group9/Lesson14_2.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class Lesson14_2 { 6 | 7 | private static Object a = new Object(); 8 | private static Object b = new Object(); 9 | 10 | public static void main(String[] args) { 11 | Thread t1 = new Thread(Lesson14_2::thread1); 12 | Thread t2 = new Thread(Lesson14_2::thread2); 13 | t1.start(); 14 | t2.start(); 15 | } 16 | 17 | public static void thread1() { 18 | try { 19 | synchronized (a) { 20 | TimeUnit.MILLISECONDS.sleep(100); 21 | System.out.println("Waiting till B is released..."); 22 | synchronized (b) { 23 | System.out.println("You will never get here"); 24 | } 25 | } 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | 30 | } 31 | 32 | public static void thread2() { 33 | try { 34 | synchronized (b) { 35 | TimeUnit.MILLISECONDS.sleep(100); 36 | System.out.println("Waiting till A is released..."); 37 | synchronized (a) { 38 | System.out.println("You will never get here"); 39 | } 40 | } 41 | 42 | } catch (InterruptedException e) { 43 | e.printStackTrace(); 44 | } 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/lessons/group9/Lesson15.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | import java.io.IOException; 4 | 5 | class A20{ 6 | public A20 method() throws Throwable{ // 1 7 | return new Single(); 8 | } 9 | } 10 | class Single extends A20{ 11 | public Single method(String str) throws RuntimeException{ // 2 12 | return new Single(); 13 | } 14 | public Single method() throws Exception{ //3 15 | return new Double(); 16 | } 17 | } 18 | class Double extends Single{ 19 | public void method(Integer digit) throws ClassCastException{ 20 | } 21 | public Double method() throws IOException{ 22 | return new Double(); 23 | } 24 | } -------------------------------------------------------------------------------- /src/lessons/group9/Lesson3.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Lesson3 { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[][] matrix = { 10 | {1, 2, 3}, 11 | {4, 5} 12 | 13 | }; 14 | 15 | System.out.println(Arrays.deepToString(matrix)); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/lessons/group9/Lesson4.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | public class Lesson4 { 4 | 5 | public static void main(String[] args) { 6 | Class clazz = User.class; 7 | 8 | Parent p = new Parent(); 9 | User u = new User(); 10 | 11 | if (p instanceof User) { 12 | u = (User)p; 13 | } 14 | 15 | 16 | 17 | } 18 | 19 | } 20 | 21 | 22 | class Calculator extends Parent { 23 | 24 | public void sum() { 25 | 26 | } 27 | } 28 | 29 | class Parent { 30 | public Parent() {} 31 | public Parent(int someParentField) { 32 | } 33 | } 34 | 35 | class User extends Parent { 36 | 37 | private Calculator calculator; 38 | 39 | static { 40 | 41 | } 42 | 43 | public User() { 44 | } 45 | 46 | public User(int i) { 47 | 48 | } 49 | 50 | class Account { 51 | 52 | } 53 | 54 | static class Account2 { 55 | 56 | } 57 | 58 | public void sum() { 59 | calculator.sum(); 60 | } 61 | 62 | @Override 63 | public String toString() { 64 | return "User [calculator=" + calculator + "]"; 65 | } 66 | 67 | } 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/lessons/group9/Lesson6_2.java: -------------------------------------------------------------------------------- 1 | //package lessons.group9; 2 | // 3 | //interface Poet { 4 | // default void write() { 5 | // System.out.println("Poet's default method"); 6 | // } 7 | //} 8 | // 9 | //interface Writer { 10 | // default void write() { 11 | // System.out.println("Writer's default method"); 12 | // } 13 | //} 14 | // 15 | //public class Lesson6_2 implements Poet, Writer{ 16 | // 17 | // public static void main(String args[]){ 18 | // Lesson6_2 john = new Lesson6_2(); 19 | // john.write(); // which write method to call, from Poet 20 | // // or, from Writer 21 | // } 22 | //} -------------------------------------------------------------------------------- /src/lessons/group9/MTApp.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | public class MTApp { 4 | 5 | private static int i = 0; 6 | private static Object dummy = new Object(); 7 | 8 | public static void main(String[] args) throws InterruptedException { 9 | Thread t = new Thread(() -> { 10 | int i2 = 0; 11 | while (i2 < 10_000) { 12 | increment(); 13 | i2++; 14 | } 15 | }, "Im thread"); 16 | 17 | Thread t2 = new Thread(() -> { 18 | int i2 = 0; 19 | while (i2 < 10_000) { 20 | increment(); 21 | i2++; 22 | } 23 | }, "Im thread"); 24 | 25 | t.start(); 26 | t2.start(); 27 | System.out.println(Thread.currentThread().getName()); 28 | t.join(); 29 | t2.join(); 30 | System.out.println(i); 31 | 32 | } 33 | 34 | // public synchronized static void increment() { 35 | // ++i; 36 | // } 37 | 38 | public static void increment() { 39 | synchronized (dummy) { 40 | ++i; 41 | } 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/lessons/group9/NewFile.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | public class NewFile { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/lessons/group9/OpenLesson.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | public class OpenLesson { 4 | 5 | private String name; 6 | private int age; 7 | 8 | public OpenLesson(String name, int age) { 9 | super(); 10 | this.name = name; 11 | this.age = age; 12 | } 13 | 14 | public static void main(String[] args) { 15 | System.out.println("hello world"); 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public int getAge() { 27 | return age; 28 | } 29 | 30 | public void setAge(int age) { 31 | this.age = age; 32 | } 33 | 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/lessons/group9/Test1.java: -------------------------------------------------------------------------------- 1 | package lessons.group9; 2 | 3 | public class Test1 { 4 | 5 | } 6 | 7 | interface Z { 8 | void eat(); 9 | } 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/multithreading/Lesson.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class Lesson { 4 | 5 | 6 | // public boolean add(E e) { 7 | // modCount++; 8 | // ensureCapacityHelper(elementCount + 1); 9 | // synchronized (this) { 10 | // elementData[elementCount++] = e; 11 | // this.wait(); 12 | // } 13 | // return true; 14 | // } 15 | 16 | public static void main(String[] args) { 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/multithreading/StartThread.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class StartThread { 6 | 7 | public static void main(String[] args) throws InterruptedException { 8 | Thread t = new Thread(() -> { 9 | try { 10 | TimeUnit.SECONDS.sleep(1); 11 | } catch (InterruptedException e1) { 12 | } 13 | System.out.println("Hello from other thread " + Thread.currentThread().getName()); 14 | }); 15 | t.setDaemon(true); 16 | t.start(); 17 | Ex e = new Ex(); 18 | e.setDaemon(true); 19 | e.start(); 20 | e.join(); 21 | System.out.println("Main thread " + Thread.currentThread().getName()); 22 | TimeUnit.SECONDS.sleep(2); 23 | System.out.println("MAIN THREAD IS FINISHED"); 24 | } 25 | } 26 | 27 | class Ex extends Thread { 28 | 29 | @Override 30 | public void run() { 31 | System.out.println("Hello from other thread " + Thread.currentThread().getName()); 32 | } 33 | } 34 | 35 | class Ex2 implements Runnable { 36 | 37 | @Override 38 | public void run() { 39 | // TODO Auto-generated method stub 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/multithreading/demo/CreditRatingService.java: -------------------------------------------------------------------------------- 1 | package multithreading.demo; 2 | 3 | import solid.s.User; 4 | 5 | public class CreditRatingService { 6 | 7 | public static Double getCreditRating(User user) { 8 | // TODO Auto-generated method stub 9 | return null; 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/multithreading/demo/UserService.java: -------------------------------------------------------------------------------- 1 | package multithreading.demo; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import solid.s.User; 6 | 7 | public class UserService { 8 | 9 | public static User getUserDetails(String userId) { 10 | return null; 11 | // TODO Auto-generated method stub 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/multithreading/examples1/CompletableFuture1.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | 6 | 7 | public class CompletableFuture1 { 8 | 9 | public static void main(String[] args) throws ExecutionException, InterruptedException { 10 | CompletableFuture future = new CompletableFuture<>(); 11 | 12 | CompletableFuture.supplyAsync(() -> { 13 | System.out.println(Thread.currentThread().getName()); 14 | System.out.println(Thread.currentThread().isDaemon()); 15 | try { 16 | Thread.sleep(1000); 17 | } catch (Exception e) { 18 | // TODO Auto-generated catch block 19 | e.printStackTrace(); 20 | } 21 | System.out.println("HERE"); 22 | 23 | // do get request 24 | return null; 25 | }); 26 | System.out.println("NEXT LINE"); 27 | 28 | future.complete("42"); 29 | 30 | future 31 | .thenAccept(System.out::println) 32 | .thenAccept(v -> System.out.println("done")); 33 | System.out.println("Finished"); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/multithreading/examples1/ConcurrentUtils.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class ConcurrentUtils { 7 | 8 | public static void stop(ExecutorService executor) { 9 | try { 10 | executor.shutdown(); 11 | executor.awaitTermination(60, TimeUnit.SECONDS); 12 | } 13 | catch (InterruptedException e) { 14 | System.err.println("termination interrupted"); 15 | } 16 | finally { 17 | if (!executor.isTerminated()) { 18 | System.err.println("killing non-finished tasks"); 19 | } 20 | executor.shutdownNow(); 21 | } 22 | } 23 | 24 | public static void sleep(int seconds) { 25 | try { 26 | TimeUnit.SECONDS.sleep(seconds); 27 | } catch (InterruptedException e) { 28 | throw new IllegalStateException(e); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/multithreading/examples1/DeadLockExample.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class DeadLockExample { 7 | 8 | static A a = new A(); 9 | static B b = new B(); 10 | 11 | public static void doSmth1() { 12 | synchronized (a) { 13 | System.out.println("Caught A object"); 14 | try { 15 | TimeUnit.SECONDS.sleep(1); 16 | } catch (InterruptedException e) { 17 | e.printStackTrace(); 18 | } 19 | synchronized (b) { 20 | System.out.println("You can never get here"); 21 | } 22 | } 23 | } 24 | 25 | public static void doSmth2() { 26 | synchronized (b) { 27 | System.out.println("Caught B object"); 28 | synchronized (a) { 29 | System.out.println("You can never get here"); 30 | } 31 | } 32 | } 33 | 34 | public static void main(String[] args) { 35 | Thread t1 = new Thread(DeadLockExample::doSmth1); 36 | Thread t2 = new Thread(DeadLockExample::doSmth2); 37 | 38 | t1.start(); 39 | t2.start(); 40 | 41 | // CompletableFuture.supplyAsync(() -> { 42 | // System.out.println("SMTH"); 43 | // return null; 44 | // }); 45 | 46 | 47 | } 48 | 49 | } 50 | 51 | class A { 52 | 53 | } 54 | 55 | class B { 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/multithreading/examples1/Lock1.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | import java.util.stream.IntStream; 7 | 8 | public class Lock1 { 9 | 10 | private static final int NUM_INCREMENTS = 10000; 11 | 12 | private static ReentrantLock lock = new ReentrantLock(); 13 | 14 | private static int count = 0; 15 | 16 | private static void increment() { 17 | lock.lock(); 18 | try { 19 | count++; 20 | } finally { 21 | lock.unlock(); 22 | } 23 | } 24 | 25 | private synchronized static void incrementSynch2() { 26 | count++; 27 | } 28 | 29 | private static void incrementSynch() { 30 | synchronized (Lock1.class) { 31 | count++; 32 | } 33 | } 34 | 35 | public static void main(String[] args) { 36 | testLock(); 37 | } 38 | 39 | private static void testLock() { 40 | count = 0; 41 | 42 | ExecutorService executor = Executors.newFixedThreadPool(2); 43 | 44 | IntStream.range(0, NUM_INCREMENTS).forEach(i -> executor.submit(Lock1::increment)); 45 | 46 | ConcurrentUtils.stop(executor); 47 | 48 | System.out.println(count); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/multithreading/examples1/Lock2.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class Lock2 { 8 | 9 | public static void main(String[] args) { 10 | ExecutorService executor = Executors.newFixedThreadPool(2); 11 | 12 | ReentrantLock lock = new ReentrantLock(); 13 | 14 | executor.submit(() -> { 15 | lock.lock(); 16 | // lock.tryLock() 17 | try { 18 | ConcurrentUtils.sleep(1); 19 | } finally { 20 | lock.unlock(); 21 | } 22 | }); 23 | 24 | executor.submit(() -> { 25 | System.out.println("Hold count: " + lock.getHoldCount()); 26 | System.out.println("Queue lenght " + lock.getQueueLength()); 27 | System.out.println("Locked: " + lock.isLocked()); 28 | System.out.println("Held by me: " + lock.isHeldByCurrentThread()); 29 | ConcurrentUtils.sleep(2); 30 | boolean locked = lock.tryLock(); 31 | System.out.println("Lock acquired: " + locked); 32 | }); 33 | 34 | ConcurrentUtils.stop(executor); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/multithreading/examples1/Lock3.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.locks.ReadWriteLock; 8 | import java.util.concurrent.locks.ReentrantReadWriteLock; 9 | 10 | public class Lock3 { 11 | 12 | public static void main(String[] args) { 13 | ExecutorService executor = Executors.newFixedThreadPool(2); 14 | 15 | Map map = new HashMap<>(); 16 | 17 | ReadWriteLock lock = new ReentrantReadWriteLock(); 18 | 19 | executor.submit(() -> { 20 | lock.writeLock().lock(); 21 | try { 22 | ConcurrentUtils.sleep(3); 23 | map.put("foo", "bar"); 24 | } finally { 25 | lock.writeLock().unlock(); 26 | } 27 | }); 28 | 29 | Runnable readTask = () -> { 30 | lock.readLock().lock(); 31 | try { 32 | System.out.println(map.get("foo")); 33 | ConcurrentUtils.sleep(1); 34 | } finally { 35 | lock.readLock().unlock(); 36 | } 37 | }; 38 | executor.submit(readTask); 39 | executor.submit(readTask); 40 | 41 | ConcurrentUtils.stop(executor); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/multithreading/examples1/Semaphore2.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.Semaphore; 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.stream.IntStream; 8 | 9 | public class Semaphore2 { 10 | 11 | private static Semaphore semaphore = new Semaphore(5); 12 | 13 | public static void main(String[] args) { 14 | ExecutorService executor = Executors.newFixedThreadPool(10); 15 | 16 | IntStream.range(0, 10) 17 | .forEach(i -> executor.submit(Semaphore2::doWork)); 18 | 19 | ConcurrentUtils.stop(executor); 20 | } 21 | 22 | private static void doWork() { 23 | boolean permit = false; 24 | try { 25 | permit = semaphore.tryAcquire(1, TimeUnit.SECONDS); 26 | if (permit) { 27 | System.out.println("Semaphore acquired"); 28 | ConcurrentUtils.sleep(5); 29 | } else { 30 | System.out.println("Could not acquire semaphore"); 31 | } 32 | } catch (InterruptedException e) { 33 | throw new IllegalStateException(e); 34 | } finally { 35 | if (permit) { 36 | semaphore.release(); 37 | } 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/multithreading/examples1/Synchronized2.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.stream.IntStream; 6 | 7 | 8 | public class Synchronized2 { 9 | 10 | private static final int NUM_INCREMENTS = 10000; 11 | 12 | private static int count = 0; 13 | 14 | public static void main(String[] args) { 15 | testSyncIncrement(); 16 | } 17 | 18 | private static void testSyncIncrement() { 19 | count = 0; 20 | 21 | ExecutorService executor = Executors.newFixedThreadPool(2); 22 | 23 | IntStream.range(0, NUM_INCREMENTS) 24 | .forEach(i -> executor.submit(Synchronized2::incrementSync)); 25 | 26 | ConcurrentUtils.stop(executor); 27 | 28 | System.out.println(count); 29 | } 30 | 31 | private static void incrementSync() { 32 | synchronized (Synchronized2.class) { 33 | count = count + 1; 34 | } 35 | } 36 | 37 | // private static synchronized void incrementSync() { 38 | // count = count + 1; 39 | // } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/multithreading/examples1/VolatileDemo.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | public class VolatileDemo { 4 | 5 | private static int MY_INT = 0; 6 | 7 | public static void main(String[] args) { 8 | new ChangeListener().start(); 9 | new ChangeMaker().start(); 10 | } 11 | 12 | static class ChangeListener extends Thread { 13 | @Override 14 | public void run() { 15 | int local_value = MY_INT; 16 | System.out.println("LOCAL VALUE " + local_value); 17 | while (local_value < 5) { 18 | 19 | if (local_value != MY_INT) { 20 | System.out.println("Got Change for MY_INT : " + MY_INT); 21 | local_value = MY_INT; 22 | } 23 | } 24 | } 25 | } 26 | 27 | static class ChangeMaker extends Thread { 28 | @Override 29 | public void run() { 30 | 31 | int local_value = MY_INT; 32 | while (MY_INT < 5) { 33 | System.out.println("Incrementing MY_INT to " + (local_value + 1)); 34 | MY_INT = ++local_value; 35 | try { 36 | Thread.sleep(5000); 37 | } catch (InterruptedException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/multithreading/examples1/VolatileExample.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples1; 2 | 3 | class ExampleThread extends Thread { 4 | private int testValue; 5 | 6 | public ExampleThread(String str) { 7 | super(str); 8 | } 9 | 10 | public void run() { 11 | for (int i = 0; i < 3; i++) { 12 | try { 13 | System.out.println(getName() + " : " + i); 14 | if (getName().equals("Thread 1")) { 15 | testValue = 10; 16 | System.out.println(testValue); 17 | } 18 | if (getName().equals("Thread 2")) { 19 | System.out.println("Test Value : " + testValue); 20 | } 21 | Thread.sleep(1000); 22 | } catch (InterruptedException exception) { 23 | exception.printStackTrace(); 24 | } 25 | } 26 | } 27 | } 28 | 29 | public class VolatileExample { 30 | public static void main(String args[]) { 31 | new ExampleThread("Thread 1").start(); 32 | new ExampleThread("Thread 2").start(); 33 | } 34 | } -------------------------------------------------------------------------------- /src/multithreading/examples2/deadlock_11/Account.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples2.deadlock_11; 2 | 3 | /** 4 | * Codes with minor comments are from 5 | * 6 | * http://www.caveofprogramming.com/youtube/ 7 | * 8 | *
9 | * also freely available at 10 | * 11 | * https://www.udemy.com/java-multithreading/?couponCode=FREE 12 | * 13 | * 14 | * @author Z.B. Celik 15 | */ 16 | class Account { 17 | 18 | private int balance = 10000; 19 | 20 | public void deposit(int amount) { 21 | balance += amount; 22 | } 23 | 24 | public void withdraw(int amount) { 25 | balance -= amount; 26 | } 27 | 28 | public int getBalance() { 29 | return balance; 30 | } 31 | 32 | public static void transfer(Account acc1, Account acc2, int amount) { 33 | acc1.withdraw(amount); 34 | acc2.deposit(amount); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/multithreading/examples2/lockobjects/App.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples2.lockobjects; 2 | 3 | /** 4 | * Codes with minor comments are from 5 | * 6 | * http://www.caveofprogramming.com/youtube/ 7 | * 8 | *
9 | * also freely available at 10 | * 11 | * https://www.udemy.com/java-multithreading/?couponCode=FREE 12 | * 13 | * 14 | * @author Z.B. Celik 15 | */ 16 | public class App { 17 | 18 | public static void main(String[] args) { 19 | System.out.println("Synchronized Objects: "); 20 | Worker worker = new Worker(); 21 | worker.main(); 22 | System.out.println("Synchronized Methods: "); 23 | WorkerMethodsSynchronized worker2 = new WorkerMethodsSynchronized(); 24 | worker2.main(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/multithreading/examples2/startingthreads/ApplicationAnonymous.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples2.startingthreads; 2 | 3 | /** 4 | * Starting threads using the Thread constructor with anonymous classes 5 | *

6 | * Codes with minor comments are from 7 | * 8 | * http://www.caveofprogramming.com/youtube/ 9 | * 10 | *
11 | * also freely available at 12 | * 13 | * https://www.udemy.com/java-multithreading/?couponCode=FREE 14 | * 15 | * 16 | * @author Z.B. Celik 17 | */ 18 | public class ApplicationAnonymous { 19 | 20 | public static void main(String[] args) { 21 | Thread thread1 = new Thread(new Runnable() { 22 | @Override 23 | public void run() { 24 | for (int i = 0; i < 5; i++) { 25 | System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); 26 | 27 | try { 28 | Thread.sleep(100); 29 | } catch (InterruptedException ignored) {} 30 | } 31 | } 32 | }); 33 | 34 | thread1.start(); 35 | System.out.println("Main is finished"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/multithreading/examples2/startingthreads/ApplicationExtends.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples2.startingthreads; 2 | 3 | /** 4 | * Starting Threads with extends 5 | *

6 | * Codes with minor comments are from 7 | * 8 | * http://www.caveofprogramming.com/youtube/ 9 | * 10 | *
11 | * also freely available at 12 | * 13 | * https://www.udemy.com/java-multithreading/?couponCode=FREE 14 | * 15 | * 16 | * @author Z.B. Celik 17 | */ 18 | class Runner extends Thread { 19 | 20 | @Override 21 | public void run() { 22 | for (int i = 0; i < 5; i++) { 23 | System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); 24 | try { 25 | Thread.sleep(100); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | } 32 | 33 | public class ApplicationExtends { 34 | 35 | public static void main(String[] args) { 36 | Runner runner1 = new Runner(); 37 | runner1.start(); 38 | 39 | Runner runner2 = new Runner(); 40 | runner2.start(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/multithreading/examples2/startingthreads/ApplicationRunnable.java: -------------------------------------------------------------------------------- 1 | package multithreading.examples2.startingthreads; 2 | 3 | /** 4 | * Starting Threads using Runnable Interface 5 | *

6 | * Codes with minor comments are from 7 | * 8 | * http://www.caveofprogramming.com/youtube/ 9 | * 10 | *
11 | * also freely available at 12 | * 13 | * https://www.udemy.com/java-multithreading/?couponCode=FREE 14 | * 15 | * 16 | * @author Z.B. Celik 17 | */ 18 | class RunnerRunnable implements Runnable { 19 | 20 | @Override 21 | public void run() { 22 | for (int i = 0; i < 5; i++) { 23 | System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); 24 | 25 | try { 26 | Thread.sleep(100); 27 | } catch (InterruptedException e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | } 32 | } 33 | 34 | public class ApplicationRunnable { 35 | 36 | public static void main(String[] args) { 37 | Thread thread1 = new Thread(new RunnerRunnable()); 38 | Thread thread2 = new Thread(new RunnerRunnable()); 39 | thread1.start(); 40 | thread2.start(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/multithreading/waitnotify/Message.java: -------------------------------------------------------------------------------- 1 | package multithreading.waitnotify; 2 | 3 | 4 | public class Message { 5 | private String msg; 6 | 7 | public Message(String str){ 8 | this.msg=str; 9 | } 10 | 11 | public String getMsg() { 12 | return msg; 13 | } 14 | 15 | public void setMsg(String str) { 16 | this.msg=str; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/multithreading/waitnotify/Notifier.java: -------------------------------------------------------------------------------- 1 | package multithreading.waitnotify; 2 | 3 | public class Notifier implements Runnable { 4 | 5 | private Message msg; 6 | 7 | public Notifier(Message msg) { 8 | this.msg = msg; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | String name = Thread.currentThread().getName(); 14 | System.out.println(name + " started"); 15 | try { 16 | Thread.sleep(1000); 17 | synchronized (msg) { 18 | msg.setMsg(name + " Notifier work done"); 19 | msg.notify(); 20 | // msg.notifyAll(); 21 | } 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/multithreading/waitnotify/WaitNotifyTest.java: -------------------------------------------------------------------------------- 1 | package multithreading.waitnotify; 2 | 3 | public class WaitNotifyTest { 4 | 5 | public static void main(String[] args) { 6 | Message msg = new Message("process it"); 7 | Waiter waiter = new Waiter(msg); 8 | Thread t1 = new Thread(waiter,"READER 1"); 9 | // t1.setPriority(1); 10 | t1.start(); 11 | 12 | Waiter waiter1 = new Waiter(msg); 13 | Thread t2 = new Thread(waiter1, "READER 2"); 14 | // t2.setPriority(9); 15 | t2.start(); 16 | 17 | Notifier notifier = new Notifier(msg); 18 | new Thread(notifier, "NOTIFIER").start(); 19 | System.out.println("All the threads are started"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/multithreading/waitnotify/Waiter.java: -------------------------------------------------------------------------------- 1 | package multithreading.waitnotify; 2 | 3 | public class Waiter implements Runnable { 4 | 5 | private Message msg; 6 | 7 | public Waiter(Message m) { 8 | this.msg = m; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | String name = Thread.currentThread().getName(); 14 | synchronized (msg) { 15 | try { 16 | System.out.println(name + 17 | " waiting to get notified at time:" 18 | + System.currentTimeMillis()); 19 | msg.wait(); 20 | 21 | // while (!condition user.getSecurityNumber.equals(111)) { 22 | // msg.wait(); 23 | // } 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | System.out.println(name + " waiter thread got notified at time:" + System.currentTimeMillis()); 28 | // process the message now 29 | System.out.println(name + " processed: " + msg.getMsg()); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/oop/DemoYacht.java: -------------------------------------------------------------------------------- 1 | package oop; 2 | 3 | 4 | 5 | public class DemoYacht { 6 | 7 | public static void main(String[] args) { 8 | Yacht y = new Yacht(); 9 | 10 | y.name = "123123"; 11 | y.name = null; 12 | y.lenght = 1; 13 | 14 | y.setName("asdasd"); 15 | 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/oop/InitOrder.java: -------------------------------------------------------------------------------- 1 | package oop; 2 | 3 | public class InitOrder { 4 | private Parent p; 5 | 6 | public InitOrder() { 7 | p = new Parent(); 8 | } 9 | // || 10 | public InitOrder(Parent p) { 11 | this.p = p; 12 | } 13 | 14 | public static void main(String[] args) { 15 | Parent p = new Child(); 16 | System.out.println("====================="); 17 | Parent p2 = new Child(); 18 | // System.out.println(Parent.class); 19 | } 20 | 21 | } 22 | 23 | 24 | class Parent { 25 | static { 26 | System.out.println("Static init block parent"); 27 | } 28 | 29 | { 30 | System.out.println("Init block parent"); 31 | } 32 | 33 | public Parent() { 34 | System.out.println("Parent constructor"); 35 | } 36 | 37 | } 38 | 39 | class Child extends Parent { 40 | static { 41 | System.out.println("Static init block child"); 42 | } 43 | 44 | { 45 | System.out.println("Init block child"); 46 | } 47 | 48 | public Child() { 49 | System.out.println("child constructor"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/oop/cars/Cabrio.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class Cabrio extends Car { 4 | int i; 5 | 6 | public Cabrio(Engine engine) { 7 | this.setEngine(engine); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/oop/cars/Car.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class Car { 4 | private Engine engine; 5 | protected int i; 6 | 7 | public Engine getEngine() { 8 | return this.engine; 9 | } 10 | 11 | public void setEngine(Engine engine) { 12 | // validate engine 13 | this.engine = engine; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/oop/cars/Demo.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class Demo { 4 | 5 | public static void main(String[] args) { 6 | Car cabrio = new Cabrio(new DieselEngine()); 7 | Car petrolCabrio = new Cabrio(new PetrolEngine()); 8 | 9 | Car sedan = new Sedan(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/oop/cars/DieselEngine.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class DieselEngine extends Engine { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/oop/cars/Engine.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class Engine { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/oop/cars/PetrolEngine.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class PetrolEngine extends Engine { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/oop/cars/Sedan.java: -------------------------------------------------------------------------------- 1 | package oop.cars; 2 | 3 | public class Sedan extends Car { 4 | 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/cloning/CloneDemo.java: -------------------------------------------------------------------------------- 1 | package oop.cloning; 2 | 3 | //import org.apache.commons.lang3.*; 4 | 5 | public class CloneDemo { 6 | 7 | public static void main(String[] args) throws CloneNotSupportedException { 8 | A a = new A(); 9 | A clone = (A)a.clone(); 10 | System.out.println("a = " + a); 11 | System.out.println("a == clone: " + (a == clone)); 12 | System.out.println("clone = " + clone); 13 | System.out.println(a.b == clone.b); 14 | 15 | } 16 | 17 | } 18 | 19 | class A implements Cloneable { 20 | int i; 21 | String s; 22 | B b; 23 | 24 | { 25 | i = 10; 26 | s = "some text"; 27 | b = new B(); 28 | } 29 | 30 | @Override 31 | public Object clone() throws CloneNotSupportedException { 32 | A a = (A)super.clone(); 33 | // Deep cloning 34 | return a; 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | return "A [i=" + i + ", s=" + s + ", b=" + b + "]"; 40 | } 41 | 42 | 43 | 44 | } 45 | 46 | class B { 47 | int i; 48 | String s; 49 | 50 | { 51 | i = 20; 52 | s = "B some text"; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return "B [i=" + i + ", s=" + s + "]"; 58 | } 59 | } -------------------------------------------------------------------------------- /src/oop/cloning/Test.java: -------------------------------------------------------------------------------- 1 | package oop.cloning; 2 | 3 | public class Test { 4 | 5 | public static void main(String[] args) { 6 | String s = ""; 7 | 8 | } 9 | 10 | } 11 | 12 | class StringWrap { 13 | 14 | public void test() throws CloneNotSupportedException { 15 | this.clone(); 16 | } 17 | public static void main(String[] args) 18 | { 19 | Nil n = new Nil(); 20 | // Object obj=((Object)n).clone(); 21 | 22 | 23 | 24 | } 25 | } 26 | 27 | class Nil implements Cloneable { 28 | 29 | 30 | } -------------------------------------------------------------------------------- /src/oop/diamandissue/I1.java: -------------------------------------------------------------------------------- 1 | package oop.diamandissue; 2 | 3 | public interface I1 { 4 | 5 | static String doSmth() { 6 | return ""; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/diamandissue/I2.java: -------------------------------------------------------------------------------- 1 | package oop.diamandissue; 2 | 3 | public interface I2 { 4 | 5 | default String doSmth() { 6 | return ""; 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/diamandissue/Impl.java: -------------------------------------------------------------------------------- 1 | package oop.diamandissue; 2 | 3 | public class Impl implements I1, I2 { 4 | 5 | public static void main(String[] args) { 6 | I2 i2 = new Impl(); 7 | System.out.println(i2.doSmth()); 8 | System.out.println(I1.doSmth()); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/oop/protecteddemo/DemoProtected.java: -------------------------------------------------------------------------------- 1 | package oop.protecteddemo; 2 | 3 | import oop.Yacht; 4 | 5 | public class DemoProtected extends Yacht { 6 | 7 | public static void main(String[] args) { 8 | Yacht y = new Yacht(); 9 | // y.i = 1; 10 | } 11 | 12 | 13 | } 14 | 15 | class SuperYacht extends Yacht { 16 | 17 | public SuperYacht(int lenght) { 18 | this.lenght = lenght; 19 | 20 | } 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/adapter/Client.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.adapter; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | int[] numbers = new int[]{34, 2, 4, 12, 1}; 6 | 7 | // NumberSorter ns = new NumberSorter(); 8 | // ns.sort(numbers); 9 | 10 | Sorter sorter = new SortListAdapter(); 11 | sorter.sort(numbers); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/adapter/NumberSorter.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.adapter; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /* This is our adaptee, a third party implementation of a 7 | * number sorter that deals with Lists, not arrays. */ 8 | public class NumberSorter { 9 | public List sort(List numbers) { 10 | // sort and return 11 | return new ArrayList(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/adapter/SortListAdapter.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.adapter; 2 | 3 | public class SortListAdapter implements Sorter { 4 | private NumberSorter numberSorter; 5 | 6 | public SortListAdapter() { 7 | numberSorter = new NumberSorter(); 8 | } 9 | 10 | @Override 11 | public int[] sort(int[] numbers) { 12 | // convert the array to a List and call variable numberList 13 | // call the adaptee 14 | // numberList = numberSorter.sort(numberList); 15 | // convert the list back to an array and return 16 | // return sortedNumberArray; 17 | return null; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/adapter/Sorter.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.adapter; 2 | 3 | //this is our Target interface 4 | public interface Sorter{ 5 | public int[] sort(int[] numbers); 6 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/command/Client.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.command; 2 | 3 | //Client 4 | 5 | public class Client { 6 | 7 | public static void main(String[] args) { 8 | 9 | RemoteControl control = new RemoteControl(); 10 | 11 | Light light = new Light(); 12 | 13 | Command lightsOn = new LightOnCommand(light); 14 | 15 | Command lightsOff = new LightOffCommand(light); 16 | 17 | // switch on 18 | 19 | control.setCommand(lightsOn); 20 | 21 | control.pressButton(); 22 | 23 | // switch off 24 | 25 | control.setCommand(lightsOff); 26 | 27 | control.pressButton(); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/command/Command.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.command; 2 | 3 | public interface Command { 4 | public void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/command/Light.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.command; 2 | 3 | //Receiver 4 | 5 | public class Light { 6 | 7 | private boolean on; 8 | 9 | public void switchOn() { 10 | 11 | on = true; 12 | 13 | } 14 | 15 | public void switchOff() { 16 | 17 | on = false; 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/command/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.command; 2 | 3 | //Concrete Command 4 | 5 | public class LightOffCommand implements Command { 6 | 7 | // reference to the light 8 | 9 | private Light light; 10 | 11 | public LightOffCommand(Light light) { 12 | this.light = light; 13 | } 14 | 15 | public void execute() { 16 | light.switchOff(); 17 | System.out.println("Light is off"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/command/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.command; 2 | 3 | //Concrete Command 4 | 5 | public class LightOnCommand implements Command { 6 | 7 | // reference to the light 8 | 9 | private Light light; 10 | 11 | public LightOnCommand(Light light) { 12 | 13 | this.light = light; 14 | 15 | } 16 | 17 | public void execute() { 18 | light.switchOn(); 19 | System.out.println("Light is on"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/command/RemoteControl.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.command; 2 | 3 | //Invoker 4 | 5 | public class RemoteControl { 6 | 7 | private Command command; 8 | 9 | public void setCommand(Command command) { 10 | this.command = command; 11 | } 12 | 13 | public void pressButton() { 14 | command.execute(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/Client.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | public class Client { 7 | public static void main(String[] args) { 8 | TravelFacade facade = new TravelFacade(); 9 | List flightsAndHotels = 10 | facade.getFlightsAndHotels(new Date(), new Date()); 11 | } 12 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/FacadeMain.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | public class FacadeMain { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/Flight.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | public class Flight { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/FlightBooker.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Date; 6 | import java.util.List; 7 | 8 | public class FlightBooker { 9 | public List getFlightsFor(Date from, Date to) { 10 | 11 | // returns flights available in the particular date range 12 | return Collections.emptyList(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/Hotel.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | public class Hotel { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/HotelBooker.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | import java.util.Collections; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | public class HotelBooker { 8 | public List getHotelsFor(Date from, Date to) { 9 | //returns hotels available in the particular date range }} 10 | return Collections.emptyList(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/TravelFacade.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | import java.util.Collections; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | public class TravelFacade { 8 | private HotelBooker hotelBooker; 9 | private FlightBooker flightBooker; 10 | 11 | public List getFlightsAndHotels(Date from, Date to) { 12 | List flights = flightBooker.getFlightsFor(from, to); 13 | List hotels = hotelBooker.getHotelsFor(from, to); 14 | // process and return 15 | return Collections.emptyList(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/facade/TravelRoute.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.facade; 2 | 3 | public class TravelRoute { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/strategy/Client.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.strategy; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class Client { 8 | 9 | public static void main(String[] args) { 10 | 11 | CompressionContext ctx = new CompressionContext(); 12 | 13 | // we could assume context is already set by preferences 14 | 15 | ctx.setCompressionStrategy(new ZipCompressionStrategy()); 16 | 17 | // get a list of files... 18 | List fileList = new ArrayList<>(); 19 | ctx.createArchive(fileList); 20 | 21 | ctx.createArchive(fileList, Client::doSmth); 22 | 23 | ctx.createArchive(fileList, (files) -> {}); 24 | 25 | } 26 | 27 | public static void doSmth(List files) { 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/strategy/CompressionContext.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.strategy; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class CompressionContext { 8 | 9 | private CompressionStrategy strategy; 10 | 11 | // this can be set at runtime by the application preferences 12 | 13 | public void setCompressionStrategy(CompressionStrategy strategy) { 14 | this.strategy = strategy; 15 | } 16 | 17 | // use the strategy 18 | public void createArchive(List files) { 19 | // do smth 20 | strategy.compressFiles(files); 21 | // do smth 22 | } 23 | 24 | public void createArchive(List files, CompressionStrategy cs) { 25 | // do smth 26 | strategy.compressFiles(files); 27 | // do smth 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/strategy/CompressionStrategy.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.strategy; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | //Strategy Interface 8 | 9 | @FunctionalInterface 10 | public interface CompressionStrategy { 11 | 12 | public void compressFiles(List files); 13 | 14 | default void doSmth(){ 15 | 16 | }; 17 | 18 | static void doSmth2(){ 19 | 20 | }; 21 | } 22 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/strategy/RarCompressionStrategy.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.strategy; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class RarCompressionStrategy implements CompressionStrategy { 8 | 9 | @Override 10 | public void compressFiles(List files) { 11 | 12 | // using RAR approach 13 | 14 | } 15 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/strategy/ZipCompressionStrategy.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.strategy; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class ZipCompressionStrategy implements CompressionStrategy { 8 | 9 | @Override 10 | public void compressFiles(List files) { 11 | //using ZIP approach 12 | 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/templmethod/AndroidCompiler.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.templmethod; 2 | 3 | public class AndroidCompiler extends CrossCompiler { 4 | 5 | protected void collectSource() { 6 | 7 | // anything specific to this class 8 | 9 | } 10 | 11 | protected void compileToTarget() { 12 | 13 | // android specific compilation 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/basicpatterns/templmethod/Client.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.templmethod; 2 | 3 | public class Client { 4 | 5 | public static void main(String[] args) { 6 | 7 | CrossCompiler iphone = new IPhoneCompiler(); 8 | iphone.crossCompile(); 9 | CrossCompiler android = new AndroidCompiler(); 10 | android.crossCompile(); 11 | 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/templmethod/CrossCompiler.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.templmethod; 2 | 3 | public abstract class CrossCompiler { 4 | 5 | public final void crossCompile() { 6 | collectSource(); 7 | doSmthImportant(); 8 | // could be some general methods 9 | compileToTarget(); 10 | } 11 | 12 | private void doSmthImportant() { 13 | // TODO Auto-generated method stub 14 | 15 | } 16 | 17 | protected abstract void collectSource(); 18 | 19 | protected abstract void compileToTarget(); 20 | 21 | } -------------------------------------------------------------------------------- /src/patterns/basicpatterns/templmethod/IPhoneCompiler.java: -------------------------------------------------------------------------------- 1 | package patterns.basicpatterns.templmethod; 2 | 3 | public class IPhoneCompiler extends CrossCompiler { 4 | 5 | protected void collectSource() { 6 | 7 | // anything specific to this class 8 | 9 | } 10 | 11 | protected void compileToTarget() { 12 | 13 | // iphone specific compilation 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/bridge/AdvancedRemote.java: -------------------------------------------------------------------------------- 1 | package patterns.bridge; 2 | 3 | public class AdvancedRemote extends BasicRemote { 4 | 5 | public AdvancedRemote(Device device) { 6 | super.device = device; 7 | } 8 | 9 | public void mute() { 10 | System.out.println("Remote: mute"); 11 | device.setVolume(0); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/bridge/BasicRemote.java: -------------------------------------------------------------------------------- 1 | package patterns.bridge; 2 | 3 | public class BasicRemote implements Remote { 4 | protected Device device; 5 | 6 | public BasicRemote() {} 7 | 8 | public BasicRemote(Device device) { 9 | this.device = device; 10 | } 11 | 12 | @Override 13 | public void power() { 14 | System.out.println("Remote: power toggle"); 15 | if (device.isEnabled()) { 16 | device.disable(); 17 | } else { 18 | device.enable(); 19 | } 20 | } 21 | 22 | @Override 23 | public void volumeDown() { 24 | System.out.println("Remote: volume down"); 25 | device.setVolume(device.getVolume() - 10); 26 | } 27 | 28 | @Override 29 | public void volumeUp() { 30 | System.out.println("Remote: volume up"); 31 | device.setVolume(device.getVolume() + 10); 32 | } 33 | 34 | @Override 35 | public void channelDown() { 36 | System.out.println("Remote: channel down"); 37 | device.setChannel(device.getChannel() - 1); 38 | } 39 | 40 | @Override 41 | public void channelUp() { 42 | System.out.println("Remote: channel up"); 43 | device.setChannel(device.getChannel() + 1); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/patterns/bridge/Demo.java: -------------------------------------------------------------------------------- 1 | package patterns.bridge; 2 | 3 | public class Demo { 4 | public static void main(String[] args) { 5 | testDevice(new Tv()); 6 | testDevice(new Radio()); 7 | } 8 | 9 | public static void testDevice(Device device) { 10 | System.out.println("Tests with basic remote."); 11 | BasicRemote basicRemote = new BasicRemote(device); 12 | basicRemote.power(); 13 | device.printStatus(); 14 | 15 | System.out.println("Tests with advanced remote."); 16 | AdvancedRemote advancedRemote = new AdvancedRemote(device); 17 | advancedRemote.power(); 18 | advancedRemote.mute(); 19 | device.printStatus(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/patterns/bridge/Device.java: -------------------------------------------------------------------------------- 1 | package patterns.bridge; 2 | 3 | public interface Device { 4 | public boolean isEnabled(); 5 | 6 | public void enable(); 7 | 8 | public void disable(); 9 | 10 | public int getVolume(); 11 | 12 | public void setVolume(int percent); 13 | 14 | public int getChannel(); 15 | 16 | public void setChannel(int channel); 17 | 18 | public void printStatus(); 19 | } 20 | -------------------------------------------------------------------------------- /src/patterns/bridge/Remote.java: -------------------------------------------------------------------------------- 1 | package patterns.bridge; 2 | 3 | public interface Remote { 4 | public void power(); 5 | 6 | public void volumeDown(); 7 | 8 | public void volumeUp(); 9 | 10 | public void channelDown(); 11 | 12 | public void channelUp(); 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/ATMDispenseChain.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ATMDispenseChain { 6 | 7 | private final DispenseChain dispenseChain; 8 | 9 | public ATMDispenseChain() { 10 | // initialize the chain 11 | this.dispenseChain = new Dollar50Dispenser(); 12 | final DispenseChain dispenseChain2 = new Dollar20Dispenser(); 13 | final DispenseChain dispenseChain3 = new Dollar10Dispenser(); 14 | 15 | // set the chain of responsibility 16 | dispenseChain.setNextChain(dispenseChain2); 17 | dispenseChain2.setNextChain(dispenseChain3); 18 | 19 | } 20 | 21 | public static void main(final String[] args) { 22 | final ATMDispenseChain atmDispenser = new ATMDispenseChain(); 23 | while (true) { 24 | int amount = 0; 25 | System.out.println("Enter amount to dispense"); 26 | final Scanner input = new Scanner(System.in); 27 | amount = input.nextInt(); 28 | if (amount % 10 != 0) { 29 | System.out.println("Amount should be in multiple of 10s."); 30 | return; 31 | } 32 | // process the request 33 | atmDispenser.dispenseChain.dispense(new Currency(amount)); 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/ATMDispenseChain2.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ATMDispenseChain2 { 6 | 7 | private final DispenseChain dispenseChain; 8 | 9 | public ATMDispenseChain2() { 10 | // initialize the chain 11 | this.dispenseChain = new ConcreteDespenser(50); 12 | final DispenseChain dispenseChain2 = new ConcreteDespenser(20); 13 | final DispenseChain dispenseChain3 = new ConcreteDespenser(10); 14 | 15 | // set the chain of responsibility 16 | dispenseChain.setNextChain(dispenseChain2); 17 | dispenseChain2.setNextChain(dispenseChain3); 18 | } 19 | 20 | public static void main(final String[] args) { 21 | final ATMDispenseChain2 atmDispenser = new ATMDispenseChain2(); 22 | while (true) { 23 | int amount = 0; 24 | System.out.println("Enter amount to dispense"); 25 | final Scanner input = new Scanner(System.in); 26 | amount = input.nextInt(); 27 | if (amount % 10 != 0) { 28 | System.out.println("Amount should be in multiple of 10s."); 29 | return; 30 | } 31 | // process the request 32 | atmDispenser.dispenseChain.dispense(new Currency(amount)); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/ConcreteDespenser.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | public class ConcreteDespenser implements DispenseChain { 4 | 5 | private DispenseChain nextChain; 6 | private int currencyValue; 7 | 8 | public ConcreteDespenser(int currencyValue) { 9 | this.currencyValue = currencyValue; 10 | } 11 | 12 | @Override 13 | public void setNextChain(DispenseChain nextChain) { 14 | this.nextChain = nextChain; 15 | } 16 | 17 | @Override 18 | public void dispense(Currency cur) { 19 | if (cur.getAmount() >= currencyValue) { 20 | int num = cur.getAmount() / currencyValue; 21 | int remainder = cur.getAmount() % currencyValue; 22 | System.out.println("Dispensing " + num + " " + currencyValue + "$ note"); 23 | if (remainder != 0) 24 | this.nextChain.dispense(new Currency(remainder)); 25 | } else { 26 | this.nextChain.dispense(cur); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/Currency.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | public class Currency { 4 | 5 | private int amount; 6 | 7 | public Currency(int amt){ 8 | this.amount=amt; 9 | } 10 | 11 | public int getAmount(){ 12 | return this.amount; 13 | } 14 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/DispenseChain.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | public interface DispenseChain { 4 | 5 | void setNextChain(DispenseChain nextChain); 6 | 7 | void dispense(Currency cur); 8 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/Dollar10Dispenser.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | public class Dollar10Dispenser implements DispenseChain { 4 | 5 | private DispenseChain chain; 6 | 7 | @Override 8 | public void setNextChain(DispenseChain nextChain) { 9 | this.chain = nextChain; 10 | } 11 | 12 | @Override 13 | public void dispense(Currency cur) { 14 | if (cur.getAmount() >= 10) { 15 | int num = cur.getAmount() / 10; 16 | int remainder = cur.getAmount() % 10; 17 | System.out.println("Dispensing " + num + " 10$ note"); 18 | if (remainder != 0) { 19 | this.chain.dispense(new Currency(remainder)); 20 | } 21 | } else { 22 | this.chain.dispense(cur); 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/Dollar20Dispenser.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | public class Dollar20Dispenser implements DispenseChain { 4 | 5 | private DispenseChain chain; 6 | 7 | @Override 8 | public void setNextChain(DispenseChain nextChain) { 9 | this.chain = nextChain; 10 | } 11 | 12 | @Override 13 | public void dispense(Currency cur) { 14 | if (cur.getAmount() >= 20) { 15 | int num = cur.getAmount() / 20; 16 | int remainder = cur.getAmount() % 20; 17 | System.out.println("Dispensing " + num + " 20$ note"); 18 | if (remainder != 0) { 19 | this.chain.dispense(new Currency(remainder)); 20 | } 21 | } else { 22 | this.chain.dispense(cur); 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/chain/Dollar50Dispenser.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.chain; 2 | 3 | public class Dollar50Dispenser implements DispenseChain { 4 | 5 | private DispenseChain chain; 6 | 7 | @Override 8 | public void setNextChain(DispenseChain nextChain) { 9 | this.chain = nextChain; 10 | } 11 | 12 | @Override 13 | public void dispense(Currency cur) { 14 | if (cur.getAmount() >= 50) { 15 | int num = cur.getAmount() / 50; 16 | int remainder = cur.getAmount() % 50; 17 | System.out.println("Dispensing " + num + " 50$ note"); 18 | if (remainder != 0) 19 | this.chain.dispense(new Currency(remainder)); 20 | } else { 21 | this.chain.dispense(cur); 22 | } 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/decorator/BasicCar.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.decorator; 2 | 3 | public class BasicCar implements Car { 4 | 5 | @Override 6 | public void assemble() { 7 | System.out.print("Basic Car."); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/patterns/chainpatterns/decorator/Car.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.decorator; 2 | 3 | public interface Car { 4 | 5 | public void assemble(); 6 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/decorator/CarDecorator.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.decorator; 2 | 3 | public class CarDecorator implements Car { 4 | 5 | private Car car; 6 | 7 | public CarDecorator(Car c) { 8 | this.car = c; 9 | } 10 | 11 | @Override 12 | public void assemble() { 13 | this.car.assemble(); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/patterns/chainpatterns/decorator/DecoratorPatternTest.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.decorator; 2 | 3 | public class DecoratorPatternTest { 4 | 5 | public static void main(final String[] args) { 6 | final Car sportsCar = new SportsCar(new BasicCar()); 7 | sportsCar.assemble(); 8 | System.out.println("\n*****"); 9 | 10 | final Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar())); 11 | sportsLuxuryCar.assemble(); 12 | System.out.println("\n*****"); 13 | 14 | final Car car = new BasicCar(); 15 | car.assemble(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/patterns/chainpatterns/decorator/LuxuryCar.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.decorator; 2 | 3 | public class LuxuryCar extends CarDecorator { 4 | 5 | public LuxuryCar(Car c) { 6 | super(c); 7 | } 8 | 9 | @Override 10 | public void assemble() { 11 | super.assemble(); 12 | System.out.print(" Adding features of Luxury Car."); 13 | } 14 | } -------------------------------------------------------------------------------- /src/patterns/chainpatterns/decorator/SportsCar.java: -------------------------------------------------------------------------------- 1 | package patterns.chainpatterns.decorator; 2 | 3 | public class SportsCar extends CarDecorator { 4 | 5 | public SportsCar(Car c) { 6 | super(c); 7 | } 8 | 9 | @Override 10 | public void assemble() { 11 | super.assemble(); 12 | System.out.print(" Adding features of Sports Car."); 13 | } 14 | } -------------------------------------------------------------------------------- /src/patterns/composite/Circle.java: -------------------------------------------------------------------------------- 1 | package patterns.composite; 2 | 3 | import java.awt.*; 4 | 5 | public class Circle extends BaseShape { 6 | public int radius; 7 | 8 | public Circle(int x, int y, int radius, Color color) { 9 | super(x, y, color); 10 | this.radius = radius; 11 | } 12 | 13 | @Override 14 | public int getWidth() { 15 | return radius * 2; 16 | } 17 | 18 | @Override 19 | public int getHeight() { 20 | return radius * 2; 21 | } 22 | 23 | public void paint(Graphics graphics) { 24 | super.paint(graphics); 25 | graphics.drawOval(x, y, getWidth() - 1, getHeight() - 1); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/patterns/composite/Demo.java: -------------------------------------------------------------------------------- 1 | package patterns.composite; 2 | 3 | import java.awt.Color; 4 | 5 | public class Demo { 6 | public static void main(String[] args) { 7 | ImageEditor editor = new ImageEditor(); 8 | 9 | editor.loadShapes( 10 | new Circle(10, 10, 10, Color.BLUE), 11 | 12 | new CompoundShape( 13 | new Circle(110, 110, 50, Color.RED), 14 | new Dot(160, 160, Color.RED) 15 | ), 16 | 17 | new CompoundShape( 18 | new Rectangle(250, 250, 100, 100, Color.GREEN), 19 | new Dot(240, 240, Color.GREEN), 20 | new Dot(240, 360, Color.GREEN), 21 | new Dot(360, 360, Color.GREEN), 22 | new Dot(360, 240, Color.GREEN) 23 | ) 24 | ); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/patterns/composite/Dot.java: -------------------------------------------------------------------------------- 1 | package patterns.composite; 2 | 3 | import java.awt.*; 4 | 5 | public class Dot extends BaseShape { 6 | private final int DOT_SIZE = 3; 7 | 8 | public Dot(int x, int y, Color color) { 9 | super(x, y, color); 10 | } 11 | 12 | @Override 13 | public int getWidth() { 14 | return DOT_SIZE; 15 | } 16 | 17 | @Override 18 | public int getHeight() { 19 | return DOT_SIZE; 20 | } 21 | 22 | @Override 23 | public void paint(Graphics graphics) { 24 | super.paint(graphics); 25 | graphics.fillRect(x - 1, y - 1, getWidth(), getHeight()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/patterns/composite/Rectangle.java: -------------------------------------------------------------------------------- 1 | package patterns.composite; 2 | 3 | import java.awt.*; 4 | 5 | public class Rectangle extends BaseShape { 6 | public int width; 7 | public int height; 8 | 9 | public Rectangle(int x, int y, int width, int height, Color color) { 10 | super(x, y, color); 11 | this.width = width; 12 | this.height = height; 13 | } 14 | 15 | @Override 16 | public int getWidth() { 17 | return width; 18 | } 19 | 20 | @Override 21 | public int getHeight() { 22 | return height; 23 | } 24 | 25 | @Override 26 | public void paint(Graphics graphics) { 27 | super.paint(graphics); 28 | graphics.drawRect(x, y, getWidth() - 1, getHeight() - 1); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/patterns/composite/Shape.java: -------------------------------------------------------------------------------- 1 | package patterns.composite; 2 | 3 | import java.awt.*; 4 | 5 | public interface Shape { 6 | public int getX(); 7 | public int getY(); 8 | public int getWidth(); 9 | public int getHeight(); 10 | public void move(int x, int y); 11 | public Boolean isInsideBounds(int x, int y); 12 | public void select(); 13 | public void unSelect(); 14 | public Boolean isSelected(); 15 | public void paint(Graphics graphics); 16 | } 17 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/Computer.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public abstract class Computer { 4 | 5 | public abstract String getRAM(); 6 | 7 | public abstract String getHDD(); 8 | 9 | public abstract String getCPU(); 10 | 11 | @Override 12 | public String toString() { 13 | return "RAM= " + this.getRAM() + ", HDD=" + this.getHDD() + ", CPU=" + this.getCPU(); 14 | } 15 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/ComputerAbstractFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public interface ComputerAbstractFactory { 4 | 5 | public Computer createComputer(); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/ComputerFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public class ComputerFactory { 4 | 5 | public static Computer getComputer(ComputerAbstractFactory factory){ 6 | return factory.createComputer(); 7 | } 8 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/PC.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public class PC extends Computer { 4 | 5 | private String ram; 6 | private String hdd; 7 | private String cpu; 8 | 9 | public PC(String ram, String hdd, String cpu){ 10 | this.ram=ram; 11 | this.hdd=hdd; 12 | this.cpu=cpu; 13 | } 14 | @Override 15 | public String getRAM() { 16 | return this.ram; 17 | } 18 | 19 | @Override 20 | public String getHDD() { 21 | return this.hdd; 22 | } 23 | 24 | @Override 25 | public String getCPU() { 26 | return this.cpu; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/PCFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public class PCFactory implements ComputerAbstractFactory { 4 | 5 | private String ram; 6 | private String hdd; 7 | private String cpu; 8 | 9 | public PCFactory(String ram, String hdd, String cpu) { 10 | this.ram = ram; 11 | this.hdd = hdd; 12 | this.cpu = cpu; 13 | } 14 | 15 | @Override 16 | public Computer createComputer() { 17 | return new PC(ram, hdd, cpu); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/Server.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public class Server extends Computer { 4 | 5 | private String ram; 6 | private String hdd; 7 | private String cpu; 8 | 9 | public Server(String ram, String hdd, String cpu){ 10 | this.ram=ram; 11 | this.hdd=hdd; 12 | this.cpu=cpu; 13 | } 14 | @Override 15 | public String getRAM() { 16 | return this.ram; 17 | } 18 | 19 | @Override 20 | public String getHDD() { 21 | return this.hdd; 22 | } 23 | 24 | @Override 25 | public String getCPU() { 26 | return this.cpu; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/ServerFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public class ServerFactory implements ComputerAbstractFactory { 4 | 5 | private String ram; 6 | private String hdd; 7 | private String cpu; 8 | 9 | public ServerFactory(String ram, String hdd, String cpu){ 10 | this.ram=ram; 11 | this.hdd=hdd; 12 | this.cpu=cpu; 13 | } 14 | 15 | @Override 16 | public Computer createComputer() { 17 | return new Server(ram,hdd,cpu); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/computerfactory/TestDesignPatterns.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.computerfactory; 2 | 3 | public class TestDesignPatterns { 4 | 5 | public static void main(String[] args) { 6 | testAbstractFactory(); 7 | } 8 | 9 | private static void testAbstractFactory() { 10 | Computer pc = ComputerFactory.getComputer(new PCFactory("2 GB","500 GB","2.4 GHz")); 11 | Computer server = ComputerFactory.getComputer(new ServerFactory("16 GB","1 TB","2.9 GHz")); 12 | System.out.println("AbstractFactory PC Config::"+pc); 13 | System.out.println("AbstractFactory Server Config::"+server); 14 | } 15 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/Archer.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder; 2 | 3 | public interface Archer { 4 | public void shoot(); 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/Client.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder; 2 | 3 | public class Client { 4 | 5 | private SquadronFactory factory; 6 | 7 | private Mage mage; 8 | private Archer archer; 9 | private Warrior warrior; 10 | 11 | public Client(SquadronFactory factory) { 12 | this.factory = factory; 13 | } 14 | 15 | public static void main(String[] args) { 16 | SquadronFactory factory = new ElfSquadronFactory(); 17 | Client client = new Client(factory); 18 | 19 | client.createSquadron(factory); 20 | client.createSquadron(); 21 | 22 | } 23 | 24 | private void createSquadron(SquadronFactory factory) { 25 | this.mage = factory.createMage(); 26 | this.archer = factory.createArcher(); 27 | this.warrior = factory.createWarrior(); 28 | } 29 | 30 | private void createSquadron() { 31 | this.mage = this.factory.createMage(); 32 | this.archer = this.factory.createArcher(); 33 | this.warrior = this.factory.createWarrior(); 34 | } 35 | 36 | public void setFactory(SquadronFactory factory) { 37 | this.factory = factory; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/ElfSquadronFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder; 2 | 3 | import java.util.List; 4 | 5 | import patterns.creationalpatterns.abstractfactory.squadbuilder.elfsquade.ElfArcher; 6 | import patterns.creationalpatterns.abstractfactory.squadbuilder.elfsquade.ElfMage; 7 | import patterns.creationalpatterns.abstractfactory.squadbuilder.elfsquade.ElfWarrior; 8 | 9 | public class ElfSquadronFactory extends SquadronFactory { 10 | public Mage createMage() { 11 | return new ElfMage(); 12 | } 13 | 14 | public Archer createArcher() { 15 | return new ElfArcher(); 16 | } 17 | 18 | public Warrior createWarrior() { 19 | return new ElfWarrior(); 20 | } 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/Mage.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder; 2 | 3 | public interface Mage { 4 | public void cast(); 5 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/SquadronFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder; 2 | 3 | public abstract class SquadronFactory { 4 | public abstract Mage createMage(); 5 | 6 | public abstract Archer createArcher(); 7 | 8 | public abstract Warrior createWarrior(); 9 | } 10 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/Warrior.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder; 2 | 3 | public interface Warrior { 4 | public void attack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/elfsquade/ElfArcher.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder.elfsquade; 2 | 3 | import patterns.creationalpatterns.abstractfactory.squadbuilder.Archer; 4 | 5 | public class ElfArcher implements Archer { 6 | public void shoot() { 7 | } 8 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/elfsquade/ElfMage.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder.elfsquade; 2 | 3 | import patterns.creationalpatterns.abstractfactory.squadbuilder.Mage; 4 | 5 | public class ElfMage implements Mage { 6 | public void cast() { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/squadbuilder/elfsquade/ElfWarrior.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.squadbuilder.elfsquade; 2 | 3 | import patterns.creationalpatterns.abstractfactory.squadbuilder.Warrior; 4 | 5 | public class ElfWarrior implements Warrior { 6 | public void attack() { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/AbstractWidgetFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //AbstractFactory 4 | 5 | public interface AbstractWidgetFactory { 6 | 7 | public Window createWindow(); 8 | // public Scroll createScroll(); 9 | // create buttons, scroll bar etc 10 | } 11 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/GUIBuilder.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //Client 4 | 5 | public class GUIBuilder { 6 | 7 | public void buildWindow(AbstractWidgetFactory widgetFactory) { 8 | 9 | Window window = widgetFactory.createWindow(); 10 | window.setTitle("New Window"); 11 | 12 | // button widgetFactory.createButton(); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/MSWindow.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //ConcreteProductA1 4 | 5 | public class MSWindow implements Window { 6 | 7 | public void repaint() { 8 | 9 | // MS Windows specific behaviour 10 | 11 | } 12 | 13 | @Override 14 | public void setTitle(final String text) { 15 | // TODO Auto-generated method stub 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/MacOSXWidgetFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //ConcreteFactory2 4 | 5 | public class MacOSXWidgetFactory implements AbstractWidgetFactory { 6 | 7 | // create a MacOSXWindow 8 | 9 | @Override 10 | public Window createWindow() { 11 | final MacOSXWindow window = new MacOSXWindow(); 12 | return window; 13 | } 14 | 15 | // create whatever you need for this widget 16 | } 17 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/MacOSXWindow.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //ConcreteProductA2 4 | 5 | public class MacOSXWindow implements Window { 6 | 7 | @Override 8 | public void repaint() { 9 | 10 | // Mac OSX specific behaviour 11 | 12 | } 13 | 14 | @Override 15 | public void setTitle(final String text) { 16 | // TODO Auto-generated method stub 17 | 18 | } 19 | 20 | // create whatever you need for this widget 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/Main.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | public class Main { 4 | 5 | public static void main(final String[] args) { 6 | final GUIBuilder builder = new GUIBuilder(); 7 | 8 | AbstractWidgetFactory widgetFactory = null; 9 | 10 | // check what platform we're on 11 | final String platform = "MACOSX"; 12 | if (platform.equals("MACOSX")) { 13 | 14 | widgetFactory = new MacOSXWidgetFactory(); 15 | 16 | } else { 17 | widgetFactory = new MsWindowsWidgetFactory(); 18 | } 19 | 20 | builder.buildWindow(widgetFactory); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/MsWindowsWidgetFactory.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //ConcreteFactory1 4 | 5 | public class MsWindowsWidgetFactory implements AbstractWidgetFactory { 6 | 7 | // create an MSWindow 8 | 9 | public Window createWindow() { 10 | 11 | final MSWindow window = new MSWindow(); 12 | 13 | return window; 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/abstractfactory/windowfactory/Window.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.abstractfactory.windowfactory; 2 | 3 | //Our AbstractProduct 4 | 5 | public interface Window { 6 | 7 | public void setTitle(String text); 8 | 9 | public void repaint(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/builder/BuilderExample.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.builder; 2 | 3 | public class BuilderExample { 4 | public static void main(final String[] args) { 5 | final ComputerDirector director = new ComputerDirector(); 6 | final ComputerBuilder cheapComputerBuilder = new CheapComputerBuilder(); 7 | 8 | director.setComputerBuilder(cheapComputerBuilder); 9 | Computer computer = director.constructComputer(); 10 | // director.getResult(); 11 | 12 | // ================================== 13 | 14 | final Computer computer2 = director.getComputer(); 15 | System.out.println(computer2); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/builder/CheapComputerBuilder.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.builder; 2 | 3 | public class CheapComputerBuilder extends ComputerBuilder { 4 | @Override 5 | public void buildSystemBlock() { 6 | computer.setSystemBlock("Everest"); 7 | } 8 | 9 | @Override 10 | public void buildDisplay() { 11 | computer.setDisplay("CRT"); 12 | } 13 | 14 | @Override 15 | public void buildManipulators() { 16 | computer.setManipulators("mouse+keyboard"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/builder/Computer.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.builder; 2 | 3 | public class Computer { 4 | private String display = null; 5 | private String systemBlock = null; 6 | private String manipulators = null; 7 | 8 | public void setDisplay(final String display) { 9 | this.display = display; 10 | } 11 | 12 | public void setSystemBlock(final String systemBlock) { 13 | this.systemBlock = systemBlock; 14 | } 15 | 16 | public void setManipulators(final String manipulators) { 17 | this.manipulators = manipulators; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return "Computer [display=" + display + ", systemBlock=" + systemBlock + ", manipulators=" + manipulators + "]"; 23 | } 24 | } 25 | 26 | abstract class ComputerBuilder { 27 | protected Computer computer; 28 | 29 | public Computer getComputer() { 30 | return computer; 31 | } 32 | 33 | public void createNewComputer() { 34 | computer = new Computer(); 35 | } 36 | 37 | public abstract void buildSystemBlock(); 38 | 39 | public abstract void buildDisplay(); 40 | 41 | public abstract void buildManipulators(); 42 | } 43 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/builder/ComputerDirector.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.builder; 2 | 3 | public class ComputerDirector { 4 | private ComputerBuilder computerBuilder; 5 | 6 | public void setComputerBuilder(final ComputerBuilder computerBuilder) { 7 | this.computerBuilder = computerBuilder; 8 | } 9 | 10 | public Computer getComputer() { 11 | return computerBuilder.getComputer(); 12 | } 13 | 14 | public Computer constructComputer() { 15 | computerBuilder.createNewComputer(); 16 | computerBuilder.buildSystemBlock(); 17 | computerBuilder.buildDisplay(); 18 | computerBuilder.buildManipulators(); 19 | return computerBuilder.getComputer(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/builder/easybuilder/Account.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.builder.easybuilder; 2 | 3 | public class Account { 4 | 5 | private String userId; 6 | private String token; 7 | 8 | private Account() { 9 | // private constructor 10 | } 11 | 12 | public String getUserId() { 13 | return userId; 14 | } 15 | 16 | public String getToken() { 17 | return token; 18 | } 19 | 20 | public static Builder newBuilder() { 21 | return new Account().new Builder(); 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | return "Account [userId=" + userId + ", token=" + token + "]"; 27 | } 28 | 29 | // TODO to fix public class 30 | public class Builder { 31 | 32 | private Builder() { 33 | // private constructor 34 | } 35 | 36 | public Builder setUserId(String userId) { 37 | Account.this.userId = userId; 38 | 39 | return this; 40 | } 41 | 42 | public Builder setToken(String token) { 43 | Account.this.token = token; 44 | 45 | return this; 46 | } 47 | 48 | public Account build() { 49 | return Account.this; 50 | } 51 | 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/builder/easybuilder/Demo.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.builder.easybuilder; 2 | 3 | public class Demo { 4 | 5 | public static void main(String[] args) { 6 | Account account = Account.newBuilder() 7 | .setToken("hello") 8 | .setUserId("habr") 9 | .build(); 10 | System.out.println(account); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/FactoryMethodDemo.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public class FactoryMethodDemo { 4 | 5 | public static void main(String[] args) { 6 | TankCreator tankCreator = new USSRTankCreator(); 7 | 8 | Tank tank = tankCreator.getTank("T-34"); 9 | System.out.println(tank.getDescription()); 10 | 11 | tank = tankCreator.getTank("T-35"); 12 | System.out.println(tank.getDescription()); 13 | 14 | tank = tankCreator.getTank("T-38"); 15 | System.out.println(tank.getDescription()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/T34Tank.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public class T34Tank implements Tank { 4 | private static final String NAME = "T-34"; 5 | private static final String COUNTRY = "USSR"; 6 | 7 | public String getDescription() { 8 | return NAME + " " + COUNTRY; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/T35Tank.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public class T35Tank implements Tank { 4 | 5 | private static final String NAME = "T-35"; 6 | private static final String COUNTRY = "USSR"; 7 | 8 | 9 | public String getDescription() { 10 | return NAME + " " + COUNTRY; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/T38Tank.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public class T38Tank implements Tank { 4 | 5 | private static final String NAME = "T-38"; 6 | private static final String COUNTRY = "USSR"; 7 | 8 | public String getDescription() { 9 | return NAME + " " + COUNTRY; 10 | } 11 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/Tank.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public interface Tank { 4 | String getDescription(); 5 | } 6 | -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/TankCreator.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public interface TankCreator { 4 | Tank getTank(String name); 5 | } -------------------------------------------------------------------------------- /src/patterns/creationalpatterns/factorymethod/USSRTankCreator.java: -------------------------------------------------------------------------------- 1 | package patterns.creationalpatterns.factorymethod; 2 | 3 | public class USSRTankCreator implements TankCreator { 4 | 5 | @Override 6 | public Tank getTank(String name) { 7 | if ("T-34".equals(name)) { 8 | return new T34Tank(); 9 | } else if ("T-35".equals(name)) { 10 | return new T35Tank(); 11 | } else if ("T-38".equals(name)) { 12 | return new T38Tank(); 13 | } 14 | return null; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/patterns/singleton/SingletonDemo.java: -------------------------------------------------------------------------------- 1 | package patterns.singleton; 2 | 3 | // thread unsafe 4 | // EJB 5 | public class SingletonDemo { 6 | 7 | private static SingletonDemo instance; 8 | 9 | private SingletonDemo() { 10 | } 11 | 12 | public SingletonDemo getInstance() { 13 | if (instance == null) { 14 | instance = new SingletonDemo(); 15 | } 16 | return instance; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/reflection/Main.java: -------------------------------------------------------------------------------- 1 | package reflection; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.util.Scanner; 6 | 7 | public class Main { 8 | 9 | public static final String CONSTANT_SOME = "Constanct"; 10 | 11 | public static void main(String[] args) throws IOException { 12 | final int a = 10; 13 | 14 | } 15 | 16 | void test(final String s) { 17 | if (s == null) 18 | return; 19 | 20 | } 21 | 22 | private void testMethod(String[] str) { 23 | System.out.println(str[0]); 24 | } 25 | 26 | private void testMethod(String str, Integer i) { 27 | System.out.println(str); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/reflection/PracticeExampleCar.java: -------------------------------------------------------------------------------- 1 | package reflection; 2 | 3 | public class PracticeExampleCar { 4 | 5 | private Engine engine; 6 | 7 | private class PetrolEngine implements Engine { 8 | 9 | } 10 | 11 | private class DieselEngine implements Engine { 12 | 13 | } 14 | 15 | } 16 | 17 | interface Engine { 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/reflection/example-config.xml: -------------------------------------------------------------------------------- 1 | ... 2 | .. 3 | .. 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/resources_en.properties: -------------------------------------------------------------------------------- 1 | table = table 2 | apple = apple -------------------------------------------------------------------------------- /src/resources_ru.properties: -------------------------------------------------------------------------------- 1 | table = \u0441\u0442\u043e\u043b 2 | apple = \u044f\u0431\u043b\u043e\u043a\u043e -------------------------------------------------------------------------------- /src/scanner/Demo.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/src/scanner/Demo.java -------------------------------------------------------------------------------- /src/solid/d/problem/WeatherAggregator.java: -------------------------------------------------------------------------------- 1 | package solid.d.problem; 2 | 3 | public class WeatherAggregator { 4 | private WeatherApi1 weatherApi1 = new WeatherApi1(); 5 | private WeatherApi2 weatherApi2 = new WeatherApi2(); 6 | 7 | public double getTemperature() { 8 | return (weatherApi1.getTemperatureCelcius() 9 | + toCelcius( 10 | weatherApi2.getTemperatureFahrenheit())) / 2; 11 | } 12 | 13 | private double toCelcius(double temperatureFahrenheit) { 14 | return (temperatureFahrenheit - 32) / 1.8f; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/solid/d/problem/WeatherApi1.java: -------------------------------------------------------------------------------- 1 | package solid.d.problem; 2 | 3 | public class WeatherApi1 { 4 | 5 | public int getTemperatureCelcius() { 6 | // TODO Auto-generated method stub 7 | return 0; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/solid/d/problem/WeatherApi2.java: -------------------------------------------------------------------------------- 1 | package solid.d.problem; 2 | 3 | public class WeatherApi2 { 4 | 5 | public double getTemperatureFahrenheit() { 6 | // TODO Auto-generated method stub 7 | return 0; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/solid/d/solution/WeatherAggregator.java: -------------------------------------------------------------------------------- 1 | package solid.d.solution; 2 | 3 | import java.util.List; 4 | 5 | public class WeatherAggregator { 6 | private List weatherSources; 7 | 8 | public WeatherAggregator(List weatherSources) { 9 | this.weatherSources = weatherSources; 10 | } 11 | 12 | public double getTemperature() { 13 | return weatherSources 14 | .stream() 15 | .mapToDouble(WeatherSource::getTemperatureCelcius) 16 | .average() 17 | .getAsDouble(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/solid/d/solution/WeatherApi2.java: -------------------------------------------------------------------------------- 1 | package solid.d.solution; 2 | 3 | public class WeatherApi2 implements WeatherSource { 4 | @Override 5 | public double getTemperatureCelcius() { 6 | return toCelcius(getTemperatureFahrenheit()); 7 | } 8 | 9 | private double getTemperatureFahrenheit() { 10 | return 0; 11 | // some logic 12 | } 13 | 14 | private double toCelcius(double temperatureFahrenheit) { 15 | return (temperatureFahrenheit - 32) / 1.8f; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/solid/d/solution/WeatherSource.java: -------------------------------------------------------------------------------- 1 | package solid.d.solution; 2 | 3 | public interface WeatherSource { 4 | double getTemperatureCelcius(); 5 | } 6 | -------------------------------------------------------------------------------- /src/solid/l/Bird2.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | public class Bird2 { 4 | 5 | public void eat() { 6 | } 7 | 8 | } 9 | 10 | class FlightBird extends Bird2 { 11 | 12 | public void fly() { 13 | } 14 | } 15 | 16 | 17 | class NonFlight extends Bird2 {} -------------------------------------------------------------------------------- /src/solid/l/BirdTest.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class BirdTest { 7 | 8 | public static void main(String[] args) { 9 | List birdList = new ArrayList(); 10 | birdList.add(new Bird()); 11 | birdList.add(new Crow()); 12 | birdList.add(new Ostrich()); 13 | letTheBirdsFly(birdList); 14 | } 15 | 16 | static void letTheBirdsFly(List birdList) { 17 | for (Bird b : birdList) { 18 | b.fly(); 19 | } 20 | } 21 | } 22 | 23 | class Bird { 24 | 25 | public void fly() { 26 | } 27 | 28 | public void eat() { 29 | } 30 | 31 | } 32 | 33 | class Crow extends Bird { 34 | } 35 | 36 | class Ostrich extends Bird { 37 | @Override 38 | public void fly() { 39 | throw new UnsupportedOperationException(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/solid/o/ExtendLoanHandler.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class ExtendLoanHandler extends LoanApprovalHandler2 { 4 | 5 | @Override 6 | public void approveLoan(Validator v) { 7 | // custom logic 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/solid/o/LoanApprovalHandler.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class LoanApprovalHandler { 4 | public void approveLoan(PersonalValidator validator) { 5 | if (validator.isValid()) { 6 | // Process the loan. 7 | } 8 | } 9 | 10 | 11 | 12 | public void approvePersonalLoan(PersonalLoanValidator validator) { 13 | if (validator.isValid()) { 14 | // Process the loan. 15 | } 16 | } 17 | 18 | public void approveVehicleLoan(VehicleLoanValidator validator) { 19 | if (validator.isValid()) { 20 | // Process the loan. 21 | } 22 | } 23 | } 24 | 25 | class PersonalLoanValidator { 26 | public boolean isValid() { 27 | return false; 28 | // Validation logic 29 | } 30 | } 31 | 32 | class VehicleLoanValidator { 33 | public boolean isValid() { 34 | //Validation logic 35 | return false; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/solid/o/LoanApprovalHandler2.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class LoanApprovalHandler2 { 4 | 5 | public void approveLoan(Validator validator) { 6 | if ( validator.isValid()) { 7 | //Process the loan. 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /src/solid/o/PersonalLoanValidator2.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class PersonalLoanValidator2 implements Validator { 4 | public boolean isValid() { 5 | // Validation logic. 6 | return false; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/solid/o/PersonalValidator.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class PersonalValidator implements Validator { 4 | 5 | public boolean isValid() { 6 | // TODO Auto-generated method stub 7 | return false; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/solid/o/Validator.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public interface Validator { 4 | 5 | boolean isValid(); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/solid/o/reportexample/BadReport.java: -------------------------------------------------------------------------------- 1 | package solid.o.reportexample; 2 | 3 | public class BadReport { 4 | enum Type { 5 | ORDERS_PER_DAY, CONVERSION_RATES 6 | } 7 | 8 | Type type; 9 | 10 | String generate(Type type) { 11 | switch (type) { 12 | case ORDERS_PER_DAY: 13 | // do stuff 14 | break; 15 | case CONVERSION_RATES: 16 | // do stuff 17 | break; 18 | } 19 | return null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/solid/o/reportexample/ConversionRatesReport.java: -------------------------------------------------------------------------------- 1 | package solid.o.reportexample; 2 | 3 | public class ConversionRatesReport implements Report { 4 | public String generate() { 5 | // do stuff 6 | return null; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/solid/o/reportexample/OrdersPerDayReport.java: -------------------------------------------------------------------------------- 1 | package solid.o.reportexample; 2 | 3 | public class OrdersPerDayReport implements Report { 4 | public String generate() { 5 | 6 | // do stuff 7 | return null; 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/solid/o/reportexample/Report.java: -------------------------------------------------------------------------------- 1 | package solid.o.reportexample; 2 | 3 | public interface Report { 4 | String generate(); 5 | } 6 | -------------------------------------------------------------------------------- /src/solid/s/MailboxSettingService.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class MailboxSettingService { 4 | public void changeEmail(User user) { 5 | if (checkAccess(user)) { 6 | // Grant option to change 7 | } 8 | } 9 | 10 | public void setAutoReply(User user) { 11 | 12 | } 13 | 14 | public void changeSignature(User user) { 15 | 16 | } 17 | 18 | public boolean checkAccess(User user) { 19 | // Verify if the user is valid. 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /src/solid/s/MailboxSettingService2.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class MailboxSettingService2 { 4 | 5 | private SecurityService ss = new SecurityService(); 6 | 7 | public void changeEmail(User user) { 8 | if (ss.checkAccess(user)) { 9 | // Grant option to change 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/solid/s/SecurityService.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class SecurityService { 4 | public boolean checkAccess(User user) { 5 | // check the access. 6 | return false; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/solid/s/User.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class User { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/string/Test.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | public class Test { 4 | 5 | public static void main(String[] args) { 6 | long n = 461012; 7 | 8 | System.out.format("resulasasd is %b and %d and %s", true, 10, "asd"); // --> "00461012" 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/syntax/Demo.java: -------------------------------------------------------------------------------- 1 | package syntax; 2 | 3 | public class Demo { 4 | 5 | public static void main(String[] args) { 6 | byte b = -12; 7 | int i = 10; 8 | double d = 12.0; 9 | float f = 12.0F; 10 | char c = 10; 11 | long l = 10L; 12 | b = (byte) 129; 13 | String s = "hello"; 14 | 15 | double e = b + i + c + l + f + d; 16 | // System.out.println(d2); 17 | 18 | int i2 = i++ + i-- + ++i - i--; 19 | // System.out.println(i); 20 | 21 | i += 2; 22 | 23 | int i3 = 2; 24 | int i4 = 4; 25 | 26 | // System.out.println(i3 & i4); 27 | 28 | // + 29 | // - 30 | // ++ 31 | // -- 32 | // / 33 | // * 34 | // += 35 | // -= 36 | // /= 37 | // *= 38 | // | 39 | // & 40 | // ^ 41 | // % 42 | // ~ 43 | // ! 44 | // >> 45 | // << 46 | // <<< 47 | // || 48 | // && 49 | 50 | System.out.println(7 % 8); 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/test/HW6Discussion.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | import java.util.ArrayList; 4 | import java.util.function.Function; 5 | 6 | public class HW6Discussion { 7 | 8 | // public double getWeightOfPodarok(ArrayList box){ 9 | // return box.stream().map(b -> b.getWeight()) 10 | // .collect(Collectors.summarizingDouble( ? :: ? )); 11 | // } 12 | 13 | public double getWeightOfPodarok(ArrayList box){ 14 | return box.stream().filter(b -> b.getWeight() > 0) 15 | .map(b -> b.getWeight()) 16 | .mapToDouble(b -> b) 17 | // .mapToDouble(Double::doubleValue) 18 | .sum(); 19 | } 20 | } 21 | 22 | class Confection { 23 | 24 | public double getWeight() { 25 | // TODO Auto-generated method stub 26 | return 0; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/Test2.java: -------------------------------------------------------------------------------- 1 | //package test; 2 | // 3 | //import lessons.group2.Lesson6_2; 4 | // 5 | //public class Test2 { 6 | // 7 | // public static void main(String[] args) { 8 | //// Lesson6_2 inst = new Lesson6_2(); 9 | // } 10 | //} 11 | -------------------------------------------------------------------------------- /src/test/TestFunctionalStatic.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | @FunctionalInterface 4 | public interface TestFunctionalStatic { 5 | public void b(); 6 | 7 | static void s() { 8 | System.out.println("s"); 9 | } 10 | 11 | default void f() { 12 | System.out.println("f"); 13 | } 14 | } -------------------------------------------------------------------------------- /src/tests/A.java: -------------------------------------------------------------------------------- 1 | package tests; 2 | 3 | public class A { 4 | 5 | private int i; 6 | 7 | public A() { 8 | i = 10; 9 | } 10 | 11 | public static void main(String[] args) { 12 | int i = 9; 13 | A a = new A(); 14 | while (a.i < 10) { 15 | a.doIt(); 16 | } 17 | 18 | System.out.println(a.hashCode()); 19 | } 20 | 21 | private static void doIt() { 22 | // i++; 23 | 24 | } 25 | 26 | @Override 27 | public int hashCode() { 28 | final int prime = 31; 29 | int result = 1; 30 | result = prime * result + i; 31 | return result; 32 | } 33 | 34 | @Override 35 | public boolean equals(Object obj) { 36 | if (this == obj) 37 | return true; 38 | if (obj == null) 39 | return false; 40 | if (getClass() != obj.getClass()) 41 | return false; 42 | A other = (A) obj; 43 | if (i != other.i) 44 | return false; 45 | return true; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /task03_in.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/task03_in.txt -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | test sdfjksld test ksd sdf ksd skdjsd f 2 | sdf sdfk jsldkf sdf 3 | sdf lskjdf lksjdflksdfss 4 | asdasda 5 | -------------------------------------------------------------------------------- /test/TestDemoIntegrationTest.java: -------------------------------------------------------------------------------- 1 | //import org.junit.Test; 2 | // 3 | //public class TestDemoIntegrationTest { 4 | // 5 | // @Test 6 | // public void test() { 7 | // BankService bs = new BankService(); 8 | // bs.transferMoney(1, 2, 100, new TransferOption() { 9 | // private ImportantService is; 10 | // 11 | // @Override 12 | // public String someImportantMethod() { 13 | // int importantMethod = is.importantMethod(); 14 | // if (importantMethod > 1) { 15 | // return "SAME VALUE"; 16 | // } else { 17 | // return "SAME VALUE"; 18 | // } 19 | // } 20 | // }); 21 | // 22 | // } 23 | // 24 | //} 25 | // 26 | //class BankService { 27 | // 28 | // public void transferMoney(int from, int to, int amount, TransferOption transOpt) { 29 | // 30 | // } 31 | //} 32 | // 33 | //interface TransferOption { 34 | // 35 | // String someImportantMethod(); 36 | //} 37 | // 38 | //interface ImportantService { 39 | // int importantMethod(); 40 | //} 41 | -------------------------------------------------------------------------------- /test/junit/BankTest.java: -------------------------------------------------------------------------------- 1 | //package junit; 2 | // 3 | //import static org.junit.Assert.*; 4 | // 5 | //import org.junit.Before; 6 | //import org.junit.Test; 7 | // 8 | //public class BankTest { 9 | // 10 | // private Bank testInstance; 11 | // 12 | // @Before 13 | // public void setUp() { 14 | // testInstance = new Bank(); 15 | // System.out.println("asd"); 16 | // } 17 | // 18 | // @Test 19 | // public void shouldAddClientToBank() { 20 | // Client clientToBeAdded = new Client(); 21 | // 22 | // testInstance.addClient(clientToBeAdded); 23 | // 24 | // assertSame(clientToBeAdded, testInstance.getClients().get(0)); 25 | // System.out.println(testInstance.hashCode()); 26 | // } 27 | // 28 | // @Test 29 | // public void test() { 30 | // System.out.println(testInstance.hashCode()); 31 | // } 32 | // 33 | // @Test(expected = Throwable.class) 34 | // public void test3() throws Throwable { 35 | // throw new RuntimeException(); 36 | // } 37 | // 38 | //} 39 | -------------------------------------------------------------------------------- /test/labs/practice4/AllTests.java: -------------------------------------------------------------------------------- 1 | //package labs.practice4; 2 | // 3 | //import org.junit.runner.RunWith; 4 | //import org.junit.runners.Suite; 5 | //import org.junit.runners.Suite.SuiteClasses; 6 | // 7 | // 8 | //@RunWith(Suite.class) 9 | //@SuiteClasses({ Part1Test.class, Part2Test.class, Part3Test.class, 10 | // Part4Test.class, Part5Test.class, DemoTest.class}) 11 | //public class AllTests { 12 | // 13 | //} 14 | -------------------------------------------------------------------------------- /test/labs/practice4/DemoTest.java: -------------------------------------------------------------------------------- 1 | //package labs.practice4; 2 | // 3 | //import java.io.IOException; 4 | // 5 | //import org.junit.Test; 6 | // 7 | // 8 | //public class DemoTest { 9 | // 10 | // @Test 11 | // public void testMain() throws IOException { 12 | // Demo.main(new String[]{}); 13 | // } 14 | // 15 | // @Test 16 | // public void constructor() { 17 | // new Demo(); 18 | // } 19 | // 20 | //} 21 | -------------------------------------------------------------------------------- /test/labs/practice4/Part2Test.java: -------------------------------------------------------------------------------- 1 | //package labs.practice4; 2 | // 3 | //import static org.junit.Assert.assertEquals; 4 | // 5 | //import java.io.IOException; 6 | // 7 | //import org.junit.Test; 8 | // 9 | // 10 | //public class Part2Test { 11 | // 12 | // @Test 13 | // public void testFillWithRandomNumbers() throws IOException { 14 | // Part2.fillWithRandomNumbers("text02_Test.txt", 10); 15 | // } 16 | // 17 | // @Test 18 | // public void testSortNumbersFromFile() throws IOException { 19 | // Part2.sortNumbersFromFile("text02_INPUT_Test.txt", "text02_Sorted_Test.txt"); 20 | // String expected = Part2.stringFromFile("text02_MUSTBE_Sorted.txt"); 21 | // String actual = Part2.stringFromFile("text02_Sorted_Test.txt"); 22 | // assertEquals(expected, actual); 23 | // 24 | // } 25 | // 26 | // 27 | // @Test 28 | // public void testMain() throws IOException { 29 | // Part2.main(new String[]{}); 30 | // } 31 | // 32 | // @Test 33 | // public void constructorTest() { 34 | // new Part2(); 35 | // } 36 | // 37 | //} 38 | -------------------------------------------------------------------------------- /test/labs/practice4/Part5Test.java: -------------------------------------------------------------------------------- 1 | //package labs.practice4; 2 | // 3 | //import java.io.ByteArrayInputStream; 4 | //import java.io.InputStream; 5 | //import java.io.UnsupportedEncodingException; 6 | // 7 | //import org.junit.After; 8 | //import org.junit.Before; 9 | //import org.junit.Test; 10 | // 11 | //public class Part5Test { 12 | // 13 | // public static final InputStream STDIN = System.in; 14 | // public static String newline = System.getProperty("line.separator"); 15 | // private static final String ENCODING = "Cp1251"; 16 | // 17 | // @Before 18 | // public void setUp() throws UnsupportedEncodingException { 19 | // ByteArrayInputStream in = new ByteArrayInputStream(("apple en" + newline 20 | // + "apple ru" + newline + "table en" + newline + "table ru" 21 | // + newline + "stop").getBytes(ENCODING)); 22 | // System.setIn(in); 23 | // } 24 | // 25 | // @After 26 | // public void tearDown() { 27 | // System.setIn(STDIN); 28 | // } 29 | // 30 | // @Test 31 | // public void testreadFromConsoleAndPrintResult() { 32 | // Part5.readFromConsoleAndPrintResult(); 33 | // } 34 | // 35 | // @Test 36 | // public void constructor() { 37 | // new Part5(); 38 | // } 39 | // 40 | // @Test 41 | // public void testMain() { 42 | // Part5.main(new String[]{}); 43 | // } 44 | // 45 | // 46 | //} 47 | -------------------------------------------------------------------------------- /test/lessons/group6/TestLesson7.java: -------------------------------------------------------------------------------- 1 | //package lessons.group6; 2 | // 3 | //import static org.hamcrest.CoreMatchers.is; 4 | //import static org.hamcrest.CoreMatchers.isA; 5 | //import static org.junit.Assert.*; 6 | // 7 | //import org.hamcrest.core.IsEqual; 8 | //import org.junit.Before; 9 | //import org.junit.Rule; 10 | //import org.junit.Test; 11 | //import org.junit.rules.ExpectedException; 12 | // 13 | //public class TestLesson7 { 14 | // 15 | // @Rule 16 | // public ExpectedException exceptionRule = ExpectedException.none(); 17 | // 18 | // private Lesson7 testInstance; 19 | // 20 | // @Before 21 | // public void setUp() { 22 | // testInstance = new Lesson7(); 23 | // } 24 | // 25 | // @Test 26 | // public void shouldThrowExceptionWhenIllegalArgiment() { 27 | // exceptionRule.expect(RuntimeException.class); 28 | //// exceptionRule.expectMessage("Some expected meessage"); 29 | // exceptionRule.expectCause(isA(IllegalArgumentException.class)); 30 | // testInstance.sum(null, null); 31 | // } 32 | // 33 | //} 34 | -------------------------------------------------------------------------------- /test11.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/test11.txt -------------------------------------------------------------------------------- /test12.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/test12.txt -------------------------------------------------------------------------------- /test4.txt: -------------------------------------------------------------------------------- 1 | 2 | asda фыфывфв 3 | asda фыфывфв 4 | asda фыфывфв -------------------------------------------------------------------------------- /testWrite.txt: -------------------------------------------------------------------------------- 1 | some text to write 2 | and more text ФСЫФС ФЫСФЫ сыы ФЫСЫ -------------------------------------------------------------------------------- /testWrite2.txt: -------------------------------------------------------------------------------- 1 | some text to write 2 | and more text -------------------------------------------------------------------------------- /testWrite3.txt: -------------------------------------------------------------------------------- 1 | some text to write 2 | and more text -------------------------------------------------------------------------------- /text01_in.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/text01_in.txt -------------------------------------------------------------------------------- /text02.txt: -------------------------------------------------------------------------------- 1 | 18 48 27 22 23 0 41 41 34 31 -------------------------------------------------------------------------------- /text02_INPUT_Test.txt: -------------------------------------------------------------------------------- 1 | 30 23 16 16 9 23 3 18 21 29 -------------------------------------------------------------------------------- /text02_MUSTBE_Sorted.txt: -------------------------------------------------------------------------------- 1 | 3 9 16 16 18 21 23 23 29 30 -------------------------------------------------------------------------------- /text02_SORTED.txt: -------------------------------------------------------------------------------- 1 | 0 18 22 23 27 31 34 41 41 48 -------------------------------------------------------------------------------- /text02_Sorted_Test.txt: -------------------------------------------------------------------------------- 1 | 3 9 16 16 18 21 23 23 29 30 -------------------------------------------------------------------------------- /text02_Test.txt: -------------------------------------------------------------------------------- 1 | 23 17 1 48 24 15 20 14 27 16 -------------------------------------------------------------------------------- /text04.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndriiPiatakha/lectures-java-core/59498c2c146ac7a66549f751b1d5c89afb104174/text04.txt --------------------------------------------------------------------------------