

Head First Java. 3rd Edition (E-book)



Head First Java. 3rd Edition (E-book) - Najlepsze oferty
Head First Java. 3rd Edition (E-book) - Opis
What will you learn from this book?Head First Java is a complete learning experience in Java and object-oriented programming. With this book, you'll learn the Java language with a unique method that goes beyond how-to manuals and helps you become a great programmer. Through puzzles, mysteries, and soul-searching interviews with famous Java objects, you'll quickly get up to speed on Java's fundamentals and advanced topics including lambdas, streams, generics, threading, networking, and the dreaded desktop GUI. If you have experience with another programming language, Head First Java will engage your brain with more modern approaches to coding--the sleeker, faster, and easier to read, write, and maintain Java of today.What's so special about this book?If you've read a Head First book, you know what to expect--a visually rich format designed for the way your brain works. If you haven't, you're in for a treat. With Head First Java, you'll learn Java through a multisensory experience that engages your mind, rather than by means of a text-heavy approach that puts you to sleep. Spis treści: Other books in OReillys Head First seriesTable of Contents (the real thing)How to Use This Book: IntroWho is this book for?Who should probably back away from this book?We know what youre thinkingAnd we know what your brain is thinkingMetacognition: thinking about thinkingHeres what WE did:Heres what YOU can do to bend your brain into submissionWhat you need for this book:Last-minute things you need to know:Technical Reviewers for the 3rd EditionOther people to acknowledge for the 3rd (...) więcej EditionTechnical Editors for the 2nd EditionOther people to credit, for the 2nd EditionJust when you thought there wouldnt be any more acknowledgments*1. Breaking the Surface: Dive In: A Quick DipThe way Java worksWhat youll do in JavaA very brief history of JavaSpeed and memory usageCode structure in JavaWhat goes in a source file?What goes in a class?What goes in a method?Anatomy of a classWriting a class with a main()What can you say in the main method?Looping and looping and...Simple boolean testsExample of a while loopConditional branchingCoding a serious business applicationMonday morning at Bobs Java-enabled housePhrase-O-MaticHow it worksExerciseCode MagnetsBE the CompilerJavaCrossMixed MessagesPool PuzzleExercise SolutionsSharpen your pencilCode MagnetsBE the CompilerPool PuzzleJavaCrossMixed Messages2. A Trip to Objectville: Classes and ObjectsChair Wars(or How Objects Can Change Your Life)At Lauras deskAt Brads laptop at the cafeLaura thought shed nailed it. She could almost feel the rolled steel of the Aeron beneath her...But wait! Theres been a spec change.Back at Lauras deskAt Brads laptop at the beachLaura delivered just moments ahead of BradBack at Lauras deskAt Brads laptop on his lawn chair at the Telluride Bluegrass FestivalSo, Brad the OO guy got the chair and desk, right?What about the Amoeba rotate()?The suspense is killing me. Who got the chair and desk?When you design a class, think about the objects that will be created from that class type. Think about:Things an object knows about itself are calledThings an object can do are calledWhats the difference between a class and an object?A class is not an object (but its used to construct them)Making your first objectMaking and testing Movie objectsQuick! Get out of main!The two uses of main:The Guessing GameRunning the Guessing GameExerciseBE the CompilerCode MagnetsPool PuzzleWho Am I?Exercise SolutionsCode MagnetsBE the CompilerPuzzle SolutionsPool PuzzleWho Am I?3. Know Your Variables: Primitives and ReferencesDeclaring a variableId like a double mocha, no, make it an int.Primitive TypesYou really dont want to spill that...Back away from that keyword!This table reservedControlling your Dog objectAn object reference is just another variable valueJava ExposedLife on the garbage-collectible heapLife and death on the heapAn array is like a tray of cupsArrays are objects tooMake an array of DogsControl your Dog (with a reference variable)What happens if the Dog is in a Dog array?A Dog exampleExerciseBE the CompilerCode MagnetsPool PuzzleA Heap o TroubleThe case of the pilfered referencesFive-Minute MysteryExercise SolutionsSharpen your pencilCode MagnetsBE the CompilerPuzzle SolutionsPool PuzzleFive-Minute MysteryA Heap o Trouble4. How Objects Behave: Methods Use Instance VariablesRemember: a class describes what an object knows and what an object doesCan every object of that type have different method behavior?The size affects the barkYou can send things to a methodYou can get things back from a methodYou can send more than one thing to a methodCalling a two-parameter method and sending it two argumentsYou can pass variables into a method, as long as the variable type matches the parameter typeJava is pass-by-value. That means pass-by-copy.Reminder: Java cares about type!Cool things you can do with parameters and return typesEncapsulationDo it or risk humiliation and ridicule.Hide the dataJava ExposedEncapsulating the GoodDog classHow do objects in an array behave?Declaring and initializing instance variablesThe difference between instance and local variablesComparing variables (primitives or references)ExerciseBE the CompilerWho Am I?Mixed MessagesPool PuzzleFive-Minute MysteryExercise SolutionsSharpen your pencilBE the CompilerWho Am I?Puzzle SolutionsPool PuzzleFive-Minute MysteryMixed Messages5. Extra-Strength Methods: Writing A ProgramLets build a Battleship-style game: Sink a StartupFirst, a high-level designThe Simple Startup Game a gentler introductionDeveloping a ClassThe three things well write for each class:Writing the method implementationsWriting test code for the SimpleStartup classBased on this prep code:Heres what we should test:Test code for the SimpleStartup classThe checkYourself() methodJust the new stuffFinal code for SimpleStartup and SimpleStartupTestDrivePrep code for the SimpleStartupGame class Everything happens in main()The games main() methodrandom() and getUserInput()One last class: GameHelperLets playWhats this? A bug ?Gasp!More about for loopsRegular (non-enhanced) for loopsTrips through a loopDifference between for and whileThe enhanced for loopCasting primitivesExerciseBE the JVMCode MagnetsJavaCrossMixed MessagesExercise SolutionsBe the JVMCode MagnetsPuzzle SolutionsJavaCrossMixed Messages6. Using the Java Library: Get to Know the Java APIIn our last chapter, we left you with the cliff-hanger: a bugHow its supposed to lookHow the bug looksSo what happened?How do we fix it?Option one is too clunkyOption two is a little better, but still pretty clunkyWake up and smell the librarySome things you can do with ArrayListJava ExposedSolutionSharpen your pencilComparing ArrayList to a regular arrayLets fix the Startup codeNew and improved Startup classLets build the REAL game: Sink a StartupWhat needs to change?Who does what in the StartupBust game (and when)Prep code for the real StartupBust classThe final version of the Startup classSuper powerful Boolean expressionsReady-Bake CodeUsing the Library (the Java API)You have to know the full name* of the class you want to use in your code.How to discover the API Browse a book Use the HTML API docsUsing the class documentationExerciseCode MagnetsJavaCrossExercise SolutionsCode MagnetsJavaCross7. Better Living in Objectville: Inheritance and PolymorphismChair Wars Revisited...What about the Amoeba rotate()?Understanding InheritanceAn inheritance example:Lets design the inheritance tree for an Animal simulation programUsing inheritance to avoid duplicating code in subclassesDo all animals eat the same way?Which methods should we override?Looking for more inheritance opportunitiesWhich method is called?Designing an Inheritance TreeUsing IS-A and HAS-ABut wait! Theres more!How do you know if youve got your inheritance right?When designing with inheritance, are you using or abusing?So what does all this inheritance really buy you?Inheritance lets you guarantee that all classes grouped under a certain supertype have all the methods that the supertype has*Keeping the contract: rules for overridingOverloading a methodExerciseMixed MessagesBE the CompilerExercise SolutionsBE the CompilerMixed MessagesPool Puzzle8. Serious Polymorphism: Interfaces and Abstract ClassesDid we forget about something when we designed this?The compiler wont let you instantiate an abstract classAbstract vs. ConcreteAbstract methodsYou MUST implement all abstract methodsPolymorphism in actionUh-oh, now we need to keep Cats, tooWhat about non-Animals? Why not make a class generic enough to take anything?So whats in this ultra-super-megaclass Object?Using polymorphic references of type Object has a price...When a Dog wont act like a DogObjects dont barkGet in touch with your inner ObjectPolymorphism means many forms.Casting an object reference back to its real type.What if you need to change the contract?Lets explore some design options for reusing some of our existing classes in a PetShop programInterface to the rescue!Making and implementing the Pet interfaceInvoking the superclass version of a methodExercisePool PuzzleExercise SolutionsWhats the Picture ?Whats the Declaration?Pool Puzzle9. Life and Death of an Object: Constructors and Garbage CollectionThe Stack and the Heap: where things liveMethods are stackedA stack scenarioWhat about local variables that are objects?If local variables live on the stack, where do instance variables live?The miracle of object creationConstruct a DuckInitializing the state of a new DuckUsing the constructor to initialize important Duck state*Make it easy to make a DuckBe sure you have a no-arg constructorDoesnt the compiler always make a no-arg constructor for you? No!Nanoreview: four things to remember about constructorsWait a minute...we never DID talk about superclasses and inheritance and how that all fits in with constructorsThe role of superclass constructors in an objects lifeMaking a Hippo means making the Animal and Object parts too...How do you invoke a superclass constructor?Can the child exist before the parents?Superclass constructors with argumentsInvoking one overloaded constructor from anotherNow we know how an object is born, but how long does an object live?What about reference variables?ExerciseBE the Garbage CollectorPopular ObjectsFive-Minute MysteryExercise SolutionsBe the Garbage CollectorPopular ObjectsFive-Minute Mystery10. Numbers Matter: Numbers and StaticsMATH methods: as close as youll ever get to a global methodThe difference between regular (non-static) and static methodsWhat it means to have a class with static methodsStatic methods cant use non-static (instance) variables!Static methods cant use non-static methods, either!Static variable: value is the same for ALL instances of the classInitializing a static variablestatic final variables are constantsfinal isnt just for static variables...Math methodsWrapping a primitiveJava will Autobox primitives for youAutoboxing works almost everywhereBut wait! Theres more! Wrappers have static utility methods too!And now in reverse...turning a primitive number into a StringNumber formattingFormatting deconstructed...The percent (%) says, insert argument here (and format it using these instructions)The format String uses its own little language syntaxThe format specifierThe only required specifier is for TYPEWhat happens if I have more than one argument?Just one more thing...static importsFireside ChatsExerciseBE the compilerTrue or FalseExercise SolutionSharpen your pencilBE the compilerTrue or False11. Data Structures: Collections and GenericsTracking song popularity on your jukeboxYour first job, sort the songs in alphabetical orderGreat question! You spotted the diamond operatorExploring the java.util API, List and CollectionsIn the Real-World there are lots of ways to sortNatural Ordering, what Java means by alphabeticalBut now you need Song objects, not just simple StringsChanging the Jukebox code to use Songs instead of StringsIt wont compile!The sort() method declarationGenerics means more type-safetyLearning genericsUsing generic CLASSESUsing type parameters with ArrayListUsing generic METHODSHeres where it gets weird...Revisiting the sort() methodIn generics, extends means extends or implementsFinally we know whats wrong...The Song class needs to implement ComparableThe new, improved, comparable Song classWe can sort the list, but...Using a custom ComparatorUpdating the Jukebox to use a ComparatorFill-in-the-blanksBut wait! Were sorting in two different ways!Sorting using only ComparatorsJust the code that mattersWhat do we REALLY need in order to sort?Enter lambdas! Leveraging what the compiler can inferWhere did all that code go?Some interfaces have only ONE method to implementUpdating the Jukebox code with lambdasReverse EngineerUh-oh. The sorting all works, but now we have duplicates...We need a Set instead of a ListThe Collection API (part of it)Using a HashSet instead of ArrayListWhat makes two objects equal?How a HashSet checks for duplicates: hashCode() and equals()The Song class with overridden hashCode() and equals()If we want the set to stay sorted, weve got TreeSetWhat you MUST know about TreeSet...TreeSet elements MUST be comparableWeve seen Lists and Sets, now well use a MapCreating and filling collectionsConvenience Factory Methods for CollectionsFinally, back to genericsUsing polymorphic arguments and genericsBut will it work with List?What could happen if it were allowed...?We can do this with wildcardsUsing the methods generic type parameterExerciseBE the Compiler, advancedExercise SolutionFill-in-the-blanksReverse Engineer lambdas exerciseSorting with lambdasTreeSet exerciseBE the Compiler solution12. Lambdas and Streams: What, Not How: Lambdas and StreamsTell the computer WHAT you wantFireside ChatsWhen for loops go wrongMixed MessagesSmall errors in common code can be hard to spotBuilding blocks of common operationsIntroducing the Streams APIGetting started with StreamsStreams are like recipes: nothings going to happen until someone actually cooks themGetting a result from a StreamStream operations are building blocksBuilding blocks can be stacked and combinedCustomizing the building blocksCreate complex pipelines block by blockYes, because Streams are lazyTerminal operations do all the workCollecting to a ListGuidelines for working with streamsCorrect! Stream operations dont change the original collection.ExerciseCode MagnetsHello Lambda, my (not so) old friendPassing behavior aroundLambda expressions are objects, and you run them by calling their Single Abstract MethodThe shape of lambda expressionsAnatomy of a lambda expressionVariety is the spice of lifeA lambda might have more than one lineSingle-line lambdas dont need ceremonyA lambda might not return anythingA lambda might have zero, one, or many parametersHow can I tell if a method takes a lambda?ExerciseBE the Compiler, advancedSpotting Functional InterfacesFunctional interfaces in the wildLous back!ExerciseReady-Bake CodeLous Challenge #1: Find all the rock songsFilter a stream to keep certain elementsLets Rock!Getting clever with filtersLous Challenge #2: List all the genresMapping from one type to anotherRemoving duplicatesOnly one of every genreJust keep building!Sometimes you dont even need a lambda expressionCollecting results in different waysBut wait, theres more!Checking if something existsFind a specific thingCount the itemsWell, some operations may return something, or may not return anything at allOptional is a wrapperYes, but now we have a way to ask if we have a resultDont forget to talk to the Optional wrapperThe Unexpected CoffeeFive-Minute MysteryPool PuzzleMixed MessagesWho Does What?Exercise SolutionsCode MagnetsBE the CompilerSharpen your pencilFive-Minute MysteryPool Puzzle13. Risky Behavior: Exception HandlingLets make a Music MachineThe finished BeatBox looks something like this:Well start with the basicsThe JavaSound APIFirst we need a SequencerSomethings wrong!What happens when a method you want to call (probably in a class you didnt write) is risky?Methods in Java use exceptions to tell the calling code, Something Bad Happened. I failed.The compiler needs to know that YOU know youre calling a risky methodAn exception is an object... of type ExceptionIf its your code that catches the exception, then whose code throws it?Flow control in try/catch blocksFinally: for the things you want to do no matter whatFlow ControlDid we mention that a method can throw more than one exception?Catching multiple exceptionsExceptions are polymorphicMultiple catch blocks must be ordered from smallest to biggestYou cant put bigger baskets above smaller basketsWhen you dont want to handle an exception...Ducking (by declaring) only delays the inevitableGetting back to our music code...Exception RulesCode KitchenMaking actual soundVersion 1: Your very first sound player appMaking a MidiEvent (song data)MIDI message: the heart of a MidiEventAnatomy of a messageChange a messageVersion 2: Using command-line args to experiment with soundsWhere were headed with the rest of the CodeKitchensExerciseTrue or FalseCode MagnetsJavaCrossSharpen your pencilExercise SolutionTrue or FalseCode MagnetsJavaCross14. A Very Graphic Story: Getting GuiIt all starts with a windowPut widgets in the windowYour first GUI: a button on a frameBut nothing happens when I click it...Getting a user eventListeners, Sources, and EventsGetting back to graphics...Make your own drawing widgetFun things to do in paintComponent()Behind every good Graphics reference is a Graphics2D objectBecause lifes too short to paint the circle a solid color when theres a gradient blend waiting for youWe can get an event. We can paint graphics. But can we paint graphics when we get an event?GUI layouts: putting more than one widget on a frameLets try it with TWO buttonsSo now we need FOUR widgetsAnd we need to get TWO eventsHow do you get action events for two different buttons when each button needs to do something different?Inner class to the rescue!An inner class instance must be tied to an outer class instance*How to make an instance of an inner classJava ExposedLambdas to the rescue! (again)ActionListener is a Functional InterfaceLambdas, clearer and more conciseUsing an inner class for animationCode KitchenListening for a non-GUI eventAn easier way to make messages/eventsVersion One: using the new static makeEvent() methodVersion Two: registering and getting ControllerEventsVersion Three: drawing graphics in time with the musicExerciseWho Am I?BE the CompilerPool PuzzleExercise SolutionsWho am I?BE the CompilerPool Puzzle15. Work on Your Swing: Using SwingSwing componentsComponents can be nestedLayout ManagersHow does the layout manager decide?Different layout managers have different policiesThe Big Three layout managers: border, flow, and boxPlaying with Swing componentsCode KitchenMaking the BeatBoxExerciseWhich code goes with which layout?Code FragmentsGUI-CrossExercise SolutionsWhich code goes with which layout?GUI-Cross16. Saving Objects (and Text): Serialization and File I/OCapture the beatSaving stateWriting a serialized object to a fileData moves in streams from one place to anotherWhat really happens to an object when its serialized?But what exactly IS an objects state? What needs to be saved?If you want your class to be serializable, implement SerializableDeserialization: restoring an objectWhat happens during deserialization?Saving and restoring the game charactersThe GameCharacter classVersion ID: A big serialization gotchaUsing the serialVersionUIDObject SerializationWriting a String to a Text FileText file example: e-FlashcardsQuiz Card Builder (code outline)The java.io.File classReading from a text fileQuiz Card Player (code outline)Parsing with String split()NIO.2 and the java.nio.file packagePath, Paths, and Files (messing with directories)Finally, a closer look at finallyRemember, finally ALWAYS runs!!Finally, a closer look at finally, cont.There IS a better way!The try-with-resources (TWR), statementAutocloseable, the very small catchAutocloseable, its everywhere you do I/OCode KitchenSaving a BeatBox patternRestoring a BeatBox patternCan they be saved?ExerciseTrue or FalseCode MagnetsExercise SolutionsTrue or FalseCode Magnets17. Make a Connection: Networking and ThreadsReal-time BeatBox chatConnecting, sending, and receiving1. Connect2. ReceiveReading from the network with BufferedReader3. SendWriting to the network with PrintWriterTheres more than one way to make a connectionUsing a SocketThe DailyAdviceClientDailyAdviceClient codeWriting a simple server applicationDailyAdviceServer codeWriting a Chat ClientThe really, really simple Chat ServerJava has multiple threads but only one Thread classWhat does it mean to have more than one call stack?To create a new call stack you need a job to runTo make a job for your thread, implement the Runnable interfaceHow NOT to run the RunnableHow we used to launch a new threadA better alternative: dont manage the Threads at allRunning one jobThe three states of a new threadThe thread schedulerHow did we end up with different results?Putting a thread to sleepUsing sleep to make our program more predictableThere are downsides to forcing the thread to sleepCounting down until readyMaking and starting two threads (or more!)Pooling ThreadsRunning multiple threadsWhat will happen?Closing time at the thread poolUm, yes. There IS a dark side. Multithreading can lead to concurrency issues.ExerciseWho Am I?New and improved SimpleChatClientExerciseCode MagnetsExercise SolutionsWho Am I?Code MagnetsCode Kitchen18. Dealing with Concurrency Issues: Race Conditions and Immutable DataWhat could possibly go wrong?The Ryan and Monica problem, in codeThe Ryan and Monica exampleWe need to check the balance and spend the money as one atomic thingUsing an objects lockUsing synchronized methodsIts important to lock the correct objectThe dreaded Lost Update problemLets run this code...Make the increment() method atomic. Synchronize it!Deadlock, a deadly side of synchronizationYou dont always have to use synchronizedAtomic variablesCompare-and-swap with atomic variablesRyan and Monica, going atomicWriting a class for immutable dataUsing immutable objectsChanging immutable dataMore problems with shared dataReading from a changing data structure causes an ExceptionUse a thread-safe data structureCopyOnWriteArrayListExerciseBE the JVMNear-miss at the airlockFive-Minute MysteryExercise SolutionBE the JVMFive-Minute MysteryA. Final Code KitchenFinal BeatBox client programFinal BeatBox server programB. The top ten-ish topics that didnt make it into the rest of the book...#11 JShell (Java REPL)Why do you care?Starting the REPLRun Java code without a classMore than just lines of codeCode suggestionsCommands#10 PackagesPackages prevent class name conflictsPreventing package name conflictsTo put your class in a package:A note on directoriesCompiling and running with packagesCompiling with the -d (directory) flagRunning your code#9 Immutability in Strings and WrappersWhy do you care that Strings are immutable?How does this save memory?Immutability makes reuse possibleWhat happens to unused Strings?Why do you care that Wrappers are immutable?#8 Access levels and access modifiers (who sees what)#7 VarargsWhy do you care?How can I tell if a method takes varargs?Creating a method that takes varargsRules#6 AnnotationsWhy do you care?Where will you see annotations?Annotations can have elementsWhat do they do?#5 Lambdas and MapsWhy do you care?Create a new value if there isnt one for the keyUpdate the value only if it already existsOther methods#4 Parallel StreamsGoing parallelOK now what?Multithreading is taken care ofDo not use parallel everywhere!#3 Enumerations (also called enumerated types or enums)Whos in the band?The old way to fake an enum:An official enumYour enum extends java.lang.EnumUsing if and switch with enums#2 Local Variable Type Inference (var)Type inference, NOT dynamic typesSomeone has to read your codeTip: Better with useful variable namesTip: Variable will be the concrete typeTip: Dont use var with the diamond operator#1 RecordsWhy do you care?A Java data class, before Java 16What if there was a special syntax for data classes?Using a recordGoodbye getYou can override constructorsYou can override or add methodsRecords are immutableIndex mniejHead First Java. 3rd Edition (E-book) - Opinie i recenzje
Na liście znajdują się opinie, które zostały zweryfikowane (potwierdzone zakupem) i oznaczone są one zielonym znakiem Zaufanych Opinii. Opinie niezweryfikowane nie posiadają wskazanego oznaczenia.