Java Training

C++string object is the sameraises exceptiongenerate exception if queue is emptyObjectJava TrainingtrainerIhar Blinouschedule9:00 - 16:00dinner14:00 - 15:00contentsmain conceptsexceptionsjdbcxmlcollectionsmultithreadingnetworkingbooksjava code conventionscore javahorstmanполный справочникcode completejava philosophyeckeljava - промышленное программированиеrefactoring to patternsresourceshttp://tutorials.jenkov.comhttp://java2s.comfeaturesno functions, only methodsall functions are inlineeverything is a classevery language construct in a separate filethere should be no two public classes in one filestatic method cannot be virtualall classes are in packagethere is default packageevery object is passed via reference== vs equalsoop principle obtrusionserialization/deserializationdeep cloning horstmancase sensitivestr to numInteger.parseIntInteger.valueOfInteger.decodenew Integerquestions@override and other annotationscode inspectionsjlintpmdcheckstylecopying objectswhy do we need static import?casting/conversionclassesinterfacesarraysconstructors are not inherited??are arrays serializable?instanceof vs getClasscode conventionsmethodsclassesconstantspackagesdesign patternsGOFtypescreationalsingletonassumes only one (or limited) instance(s) of specific classfactoryfactory creates objects of different subclasses using similar approachabstract factoryfactory methodbuilderbuilder creates one large objectprototypestructuralcompositeused for hierarchical data representation (fs tree, xml, categories, syntax parser, matryoshka doll etc)featuresrecursive compositionallows treat both individual objects and their clusters uniformlyexamplesfs treexmlcategoriessyntax parserASTmatryoshka dollhierarchieschurchmilitaryaristocraticadministrativegenresartmusiccompexity classesdecoratorwrapper is the synonym of decoratorfacadeprovides interface for the more complex architectureflyweightproxybridgefeaturesrun-time binding implementationhierarchies are being implemented independentlydecoupling abstraction from implementationexampledifferent implementations for different platformsadaptermatches interfaces of different classesfeatureslegacy classes have replacementsdecorator provides enhanced interfacefacade defines new interface while adapter reuses the old onebehavioralcommandobserver/listenerchain of responsibilityiteratormediatormementoimitates ctrl+z behavioroften used in a tandem with a command patternstatestrategytemplate methodvisitorGRASPknowledge classesaction classespatternsexperthigh cohesionglaukap ??exampleshttp://fluffycat.comlanguageerrors handlingexceptionstry-catch-finallyfinallyused for db connection closeclose filesrelease other allocated resourcesthrowthrowstypescheckedthrowsExceptionuncheckedRuntimeExceptionmultiple catch blockstwo catches cannot handle exceptioncatch(Exception e)deprecated!redefine constructor in order to be able passing error messageall exceptions implement interface ThrowableclassesIOExceptionNullPointerExceptionArithmeticExceptionCloneNotSupportedExceptioninheritancesubclass methods should throw subexceptions which overridden method throwsnarrowing approachsubclass constructor should throw all exceptions (or its parent classes) parent constructor throwswidening approacherrorsOutOfMemoryErrorStackOverflowErrorprogram is allowed to terminateassertionsassert <condition>:<expression>;JavaBeanspublic contstructorfor possibility of creation via reflectionimplements Serializableprivate fieldssetters/gettersconceptobject as a single information domaintypesbase typesbooleanBooleanbooleanValueparseBooleanbyteBytebyteValueparseBytecharCharactercharValue----shortShortshortValueparseShortintIntegerintValueparseIntlongLonglongValueparseLongfloatFloatfloatValueparseFloatdoubleDoubledoubleValueparseDoublevalueOfprimitivebyte1short2int4long8float4doubledefault8char2boolarithmetic promotion (implicit)longcharintshortbytefloatdoubleliteralsnumberint100120xAfloat/double1.00015.3e-36.89e-8fchars\u0004'a'escape sequence\n\r\t\b\f\'\"\\nullbooleantruefalseNaNvariablestypeslocalstaticinstancecommentsjavadoc@authorversionexceptionparamreturndeprecatedsincethrowssee...one line//multiline/* */operatorsrelative!=>=>other==&^*|&&||? :=arithmetic+++---*/%remainderlogicalbitwiseassignment flowswitch/casedoes not accept long ??forwhiledocontinuebreakadvanced[]? :.()castingparams listnewinstanceofreturns true forclassor its subclass'a instanceof Object' always returns trueexcept 'null instanceof Object';oopconstructorsdefault constructor is used when explicit constructor is absentoverloadingnot always default constructor is reasonableconstructor is the class method without return valueare not inheritedinheritanceall methods and fields are inherited to subclasslogical blocks are not inheriteddefault class is being Object inherited fields are not overridden even though they are being inheritedthere might be id field in both parent and subclassincapsulationaccess modifiersprivateprotecteddefault (private-package)publicpolymorphismtypesstatictemplatestemplate methodsoverloadinggenerics?dynamiclate bindingoverridingmethod visibility should be widened, not narrowedability of change reference depending on the passed object typepolymorphic substitutionstatic + dynamic = combined polymorphismsublass reference cannot be initialized with superclass objectrelationshipsis-ahas-amodifiersabstractfinalstatictransientnativesynchronizedvolatileprivatepublic protectedclassesabstractinner1 to 1 classes relationshipused for unique concept existing only in the scope of the outer classcompound data typesEnum declarationsouter class cannot see fields and methods of inner class if there is no instanceinner class sees all, even privateaccess to outer class instanceOuter.this.fieldsubclass of inner class loses access to the outer classthough subclasses of inner and outer keep accessibility rulesnestedstatic inner classcan be created without instantiation of outer classstatic keyword before inner class definition describes instantiation approach. it tells nothing about fields and methodsnew Outer.Inner()no instance of outer class requiredinner classes of interfaces are static by defaultcan imitate methods implementation inside the interfaceanonymousexampleAnonClass anon = new AnonClass { ... }inherited from the class where it is definedoften used in enumsin case of abstract method definition in enum it is required to override it with anon class in each enum valueit is not allowed to inherit from enuminterfacesnames-ableSerializable-orIteratorshould represent complex actionscan have details of implementationcan inerit from each otherextends keywordinterfaces parametrizationvs abstract classesit is useful to parametrize interface with the abstract classinterface Interface<T extends AbstractClass>commoncannot create objectsunimplemented methodsdifferenceclass hasfieldsmethodsconstructorabstractreasonable when there arecommon fieldscommon methods implementationsingle inheritancecan have default implementationinterfacejust a list of methodsmultiple inheritancesupersuper(a, b, c)super.method()each constructor of inherited class has implicit super() call without paramsthisthis(a, b, c)chain constructorthis.method()importstaticimport static java.util.Math.*java.util.* is imported by defaulttypesnumericNumberByteShortIntegerLongBigIntegerBigDecimalFloatDoubleStringimmutableif literal is the same, reference also the sameString s1 = "Java"String s2 = "Java"String s3 = "Ja" + "va"methodsconcatindividual charscharAtcomparisoncompareTocompareToIgnoreCaseequalsequalsIgnoreCasecontentsEqualsTosubstring searchstartsWithendsWithindexOflastIndexOfsubstringextract substringuppercased stringtoUpperCaselowercase stringtoLowerCaselengthreplacetrimtoStringvalueOfinternString s1 = "Java"String s2 = new String("Java")s1 == s2 -> falses2 = s1.intern()s1 == s2 -> trueisEmptyadded in java 6formatsplitbuffersStringBuffermodifiable stringsappendinsertreversesetCharAtdeleteCharAtsetLengthtoStringStringBuilderunsynchronized StringBufferhashCode and equals are not overridden for both classesLocale classgetCountrygetDisplayCountrygetLanguagegetDisplayLanguage...regexesPattern classcompilematchesmatchersplittoStringformattingnumbersdatescurrencyFormatter classcloseflushformattoString%[<argumentIndex>$][<flags>][<width>][.<precision>] <type>types%bBoolean%cCharacter%dDecimal%fFloating point%sStringparsingScanner classall related classes are finalarrayscannot convert into each otherarrays arrayreferences arraydefinition{}enumsgenerics?anonymous typeTtypecan use 'extends' keywordcan not generic constructor can not be instantiatedbe used in static methodslogical blockstypesdefaultrun on class initializationstaticrun on class loadingrun only oncemethodsvariable paramsmethod(String s, int ... k)method(String ... s)method(Object ... o)method(int ... k)method(1, 2, 3, 4)method(String[] ... arr)should be at the endworks with both params list and arraysautoboxing/unboxingInteger num = 170object creation + boxingInteger k = ++numunboxing + operation + object creation + boxingint i = kunboxingInteger i = nullint j = idynamic comparisonunboxing, comparison, boxingFloat f = new Float("7")does not workserializationimplements Serializablerequires serialVersionUIDtransientcannot be serializedas well as static fieldscollectionshierarchyMapSortedMapAbstractMapTreeMapHashMapLinkedHashMapEnumMapWeekHashMapjava6Subtopic 1IdentityHashMapallow duplicated keysSystem.identityHashCode()HashtablelegacyCollectionListAbstractCollectionAbstractListArrayListAbstractSequenceListLinkedListVectorlegacyStacklegacyAbstractQueuePriorityQueueArrayDequeAbstractSetTreeSetHashSetLinkedHashSetEnumSetSetNavigableSetSortedSetQueueDequeArrayDequethread-safetyjava 1all thread-safetyjava 2emerged non thread-safetymethodsCollectionaddaddAllclearequalsisEmptyiteratorremovesizeQueueelementremoveofferpeekpollListindexOfaddaddAllgetremovesetsubListLinkedListaddFirstaddLastgetFirstgetLastremoveFirstremoveLastremoveFirstOccurenceremoveLastOccurenceComparatorcomparesortComparablecompareToTreeSetfirstlastsubSettailSetheadSetcomparatorEnumSetnoneOfofcomplementOfrangeMapcontainsKeycontainsValueentrySetkeySetgetputputAllremovevaluesMap.EntrygetKeygetValuesetValueauxillary interfacesIterator<T>reference to the next elementmethodshasNextnextremoveComparator<T>Map.EntryEnumeration<T>legacymethodselementskeysauxillary classesCollectionslegacystatic class with static methods for actions with collectionsmethodscheckedCollectionaddAllcopydisjointemptyListfillfrequencymaxminnCopiesreplaceAllreverserotateshufflesingletonMapsortswapArrayslegacyclass for manipulation with arraysmethodsfillsortcopyOfcopyOfRangeasListforeachis applicable on classes implementing Iterable interfaceTreeSet cannot be parameterized with StringBuilder or StringBufferbecause those classes do not have compareTo implementedhow to make java 1.4 collection type-safe?checkedCollection methodmultithreadingapplication has at least one thread: mainit waits until all spawned thread will be terminatedclass Threadmethodsrunthrows InterruptedExceptioninterface Runnablemethodsrunstartthreadstatesnewready/runnablerunningnon-runnablesleepingtime waitingblockedstate becomes active on synchronizationwaitingwaitis called on non-runnable threadstops threadreleases object blockobject becomes availablenotifymakes thread readynotifyAllall waiting threads are notified to be readyit is not recommended to kill/terminate/interrupt thread from non-runnable statedead/terminatedclass StateprioritiesMINMAXNORMgroupsThreadGroup classcontrolyieldjoin?closedaemonsisDaemonsetDaemonsynchronizationthread-safety of fileobjectthreadit is not required for writing/readingexcept 64bit platformsemaphorsrestrict the number of threads than can access some (physical or logical) resourcecorejava.util.concurrent.*ConcurrentHashMapCopyOnWriteArrayListExecutorAtomicIntegerAtomicLongAtomicReferenceSynchronizedIntSemaphoreCyclicBarrierExchangercoreIOjava.io.File classstreamslow-levelFileInputStreamFileOutputStreamObjectInputStreamObjectOutputStreamhigh-levelDataInputStreamDataOutputStreamreaderslow-levelFileReaderhigh-levelBufferedReaderfilesocketreadlinewriterslow-levelFileWriterhigh-levelBufferedWriterPrintWriterRandomjava.util.RandomObjectcloneclass should implement Cloneable interfaceif interface is not implemented, then CloneNotSupportedException will be raisedapproachdeepexample is in the book by Horstmanshallowsuper.clone()immutable objects are cloned automaticallyhashCodeimplementation should try to map object and unique hash codeequalsequals assumes that two equal objects have the same hash codesEffective Java describes how to violate equivalence criteriaconsists ofnull checkobjects classes checkobject castingobject properties null checkobject properties comparisontoStringgetClasspart of the the reflection mechanizmfinalizeEffective Java describes the way how to halt the system with finalize overridingthreadingnotifynotifyAllwaitResourceBundlePropertiesconsoleSystem.console()console.readPassword()Scannerzipjarjdbcconceptsresult setsqueriesrun on the statement instanceCRUDcreatest.executeUpdate("INSERT employee VALUES(" + 13 + "," + "'Aman'" + ")");retrieveudpatedeleteexamplestatementsexampleStatement st = connection.createStatement()typespreparedPreparedStatementexecuteBatchcallableCallableStatementfor stored proceduresdriversdriver should be loaded into memoryClass.forName(driverName)new com.mysql.jdbc.Driver()metadataused to work with table and db structureinterfacesResultSetMetaDatamethodsgetColumnCountgetColumnNamegetColumnTypeDatabaseMetaDatamethodsgetDatabaseProductNamegetDatabaseProductVersiongetDriverNamegetUserNamegetURLgetTablesexampleResultSetMetaData md = resultSet.getMetaData()DatabaseMetaData md = connection.getMetaData()connectionsexampleConnection.getConnection("jdbc:mysql://localhost:3306/mydb")uses specific connection syntaxjdbc:[dbtype]://[host]:[port]/[dbname]surely should be closedconnection creation is really expensivepoolsin connection pools connections are placed into the list (pool) in order to store expensive connections and allow users to use themDAOData Access Object patternlog4jappenderconsolefilesguijmssocketsevent loggerssysloglevelsTRACEDEBUGINFOWARNERRORFATALrotationevery N hours/days/... new file is being createdlayoutscustom filtersjUnittest casesfixtures@Before@After@Test@BeforeClasssuitesassertionsexceptions handling@Test(expected=Exception.class)parameterized testtimeout testnetworkingclassesSocketexampleSocket sock = new Socket(host, port)Socket sock = new ServerSocket(port)InetAddressDatagramSocketauxillary classes usageBufferedReaderInputStreamReaderPrintStreamtaskslesson 1chapter 3,4implementation of factory and/or commandlesson 3composite + builderbridgecomposite + bridgelesson 4ResourceBundlelesson 5implement some specific domainairplanesbooksmusicshop...entity classes with code conventionsuse DBconnection pooldata sourceadd functionality of filtration/search and adding/deletion to the dbcollections + genericspatternsDAOCommandMementoView/ControllerFactorySingleton...resource bundledb propertieslog4jjunitmultithreadingcommand line interactionvirtual machinegarbage collectorSystem.gc()Runtime.getRuntime().gc()System.runFinalization()XMLxercesorg.w3c.*org.xml.*BookLibrary application0.x.1factory patternsingleton patterncommand pattern0.x.2patternsfactorysingletoncommandmementodaocompositeusagedbfiltrationby titleby idresource bundlecollectionsarraylistenum0.x.3improvementsadd some patternbridgebuilderstrategylisteneradd interactivityvim-like inputmodify factory to create instances of proper classeslogger
42