diff --git a/.classpath b/.classpath index 91e2674..4b82ec4 100644 --- a/.classpath +++ b/.classpath @@ -12,5 +12,14 @@ + + + + + + + + + diff --git a/.metadata/.lock b/.metadata/.lock new file mode 100644 index 0000000..e69de29 diff --git a/.metadata/.mylyn/.repositories.xml.zip b/.metadata/.mylyn/.repositories.xml.zip new file mode 100644 index 0000000..71892eb Binary files /dev/null and b/.metadata/.mylyn/.repositories.xml.zip differ diff --git a/.metadata/.mylyn/.taskListIndex/segments_1 b/.metadata/.mylyn/.taskListIndex/segments_1 new file mode 100644 index 0000000..4c0d6eb Binary files /dev/null and b/.metadata/.mylyn/.taskListIndex/segments_1 differ diff --git a/.metadata/.mylyn/.taskListIndex/write.lock b/.metadata/.mylyn/.taskListIndex/write.lock new file mode 100644 index 0000000..e69de29 diff --git a/.metadata/.mylyn/.tasks.xml.zip b/.metadata/.mylyn/.tasks.xml.zip new file mode 100644 index 0000000..4ceb4e5 Binary files /dev/null and b/.metadata/.mylyn/.tasks.xml.zip differ diff --git a/.metadata/.mylyn/repositories.xml.zip b/.metadata/.mylyn/repositories.xml.zip new file mode 100644 index 0000000..ef7ce3a Binary files /dev/null and b/.metadata/.mylyn/repositories.xml.zip differ diff --git a/.metadata/.mylyn/tasks.xml.zip b/.metadata/.mylyn/tasks.xml.zip new file mode 100644 index 0000000..5292b78 Binary files /dev/null and b/.metadata/.mylyn/tasks.xml.zip differ diff --git a/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/history.version b/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/history.version new file mode 100644 index 0000000..25cb955 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/history.version @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.index b/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.index new file mode 100644 index 0000000..5897676 Binary files /dev/null and b/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.index differ diff --git a/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.version b/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.version new file mode 100644 index 0000000..6b2aaa7 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.version @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.metadata/.plugins/org.eclipse.core.resources/.root/1.tree b/.metadata/.plugins/org.eclipse.core.resources/.root/1.tree new file mode 100644 index 0000000..8a1fc9e Binary files /dev/null and b/.metadata/.plugins/org.eclipse.core.resources/.root/1.tree differ diff --git a/.metadata/.plugins/org.eclipse.core.resources/.root/3.tree b/.metadata/.plugins/org.eclipse.core.resources/.root/3.tree new file mode 100644 index 0000000..8a1fc9e Binary files /dev/null and b/.metadata/.plugins/org.eclipse.core.resources/.root/3.tree differ diff --git a/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources b/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources new file mode 100644 index 0000000..e2215b3 Binary files /dev/null and b/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources differ diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..bdd6a56 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding=UTF-8 +refresh.lightweight.enabled=true +version=1 diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.e4.ui.css.swt.theme.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.e4.ui.css.swt.theme.prefs new file mode 100644 index 0000000..77840f2 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.e4.ui.css.swt.theme.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +themeid=org.eclipse.e4.ui.css.theme.e4_dark diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.e4.ui.workbench.renderers.swt.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.e4.ui.workbench.renderers.swt.prefs new file mode 100644 index 0000000..95926f8 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.e4.ui.workbench.renderers.swt.prefs @@ -0,0 +1,4 @@ +USE_ROUND_TABS=false +eclipse.preferences.version=1 +enableMRU=true +themeEnabled=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..47ba2ee --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.ui.formatterprofiles.version=21 +spelling_locale_initialized=true +useAnnotationsPrefPage=true +useQuickDiffPrefPage=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jsch.core.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jsch.core.prefs new file mode 100644 index 0000000..d56c53f --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jsch.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jsch.core.hasChangedDefaultWin32SshHome=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs new file mode 100644 index 0000000..67b1d96 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.m2e.discovery.pref.projects= diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs new file mode 100644 index 0000000..43e97e4 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +mylyn.attention.migrated=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.monitor.ui.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.monitor.ui.prefs new file mode 100644 index 0000000..8d462a6 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.monitor.ui.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.mylyn.monitor.activity.tracking.enabled.checked=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.tasks.ui.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.tasks.ui.prefs new file mode 100644 index 0000000..2b60c21 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.tasks.ui.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +migrated.task.repositories.secure.store=true +org.eclipse.mylyn.tasks.ui.filters.nonmatching=true +org.eclipse.mylyn.tasks.ui.filters.nonmatching.encouraged=true +org.eclipse.mylyn.tasks.ui.welcome.message=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs new file mode 100644 index 0000000..8d5fbc3 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +lineNumberRuler=true +spellingEnabled=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.ide.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.ide.prefs new file mode 100644 index 0000000..ad883c8 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.ide.prefs @@ -0,0 +1,5 @@ +PROBLEMS_FILTERS_MIGRATE=true +eclipse.preferences.version=1 +platformState=1593874759900 +quickStart=false +tipsAndTricks=true diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.prefs new file mode 100644 index 0000000..08076f2 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +showIntro=false diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs new file mode 100644 index 0000000..c9dfa54 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs @@ -0,0 +1,13 @@ +//org.eclipse.ui.commands/state/org.eclipse.ui.navigator.resources.nested.changeProjectPresentation/org.eclipse.ui.commands.radioState=false +PLUGINS_NOT_ACTIVATED_ON_STARTUP=;org.eclipse.m2e.discovery; +RUN_IN_BACKGROUND=true +eclipse.preferences.version=1 +org.eclipse.ui.workbench.ACTIVE_NOFOCUS_TAB_BG_END=41,41,41 +org.eclipse.ui.workbench.ACTIVE_NOFOCUS_TAB_BG_START=43,44,45 +org.eclipse.ui.workbench.ACTIVE_NOFOCUS_TAB_TEXT_COLOR=204,204,204 +org.eclipse.ui.workbench.ACTIVE_TAB_BG_END=41,41,41 +org.eclipse.ui.workbench.ACTIVE_TAB_BG_START=43,44,45 +org.eclipse.ui.workbench.ACTIVE_TAB_TEXT_COLOR=221,221,221 +org.eclipse.ui.workbench.INACTIVE_TAB_BG_END=49,53,56 +org.eclipse.ui.workbench.INACTIVE_TAB_BG_START=59,64,66 +org.eclipse.ui.workbench.INACTIVE_TAB_TEXT_COLOR=187,187,187 diff --git a/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.urischeme.prefs b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.urischeme.prefs new file mode 100644 index 0000000..855d634 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.urischeme.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +processedSchemes=,eclipse+command,eclipse+mpc diff --git a/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi b/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi new file mode 100644 index 0000000..fe15d1f --- /dev/null +++ b/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi @@ -0,0 +1,2355 @@ + + + + activeSchemeId:org.eclipse.ui.defaultAcceleratorConfiguration + + + + + + + + topLevel + shellMaximized + + + + + persp.actionSet:org.eclipse.text.quicksearch.actionSet + persp.actionSet:org.eclipse.mylyn.tasks.ui.navigation + persp.actionSet:org.eclipse.ui.cheatsheets.actionSet + persp.actionSet:org.eclipse.search.searchActionSet + persp.actionSet:org.eclipse.ui.edit.text.actionSet.annotationNavigation + persp.actionSet:org.eclipse.ui.edit.text.actionSet.navigation + persp.actionSet:org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo + persp.actionSet:org.eclipse.ui.externaltools.ExternalToolsSet + persp.actionSet:org.eclipse.ui.actionSet.keyBindings + persp.actionSet:org.eclipse.ui.actionSet.openFiles + persp.actionSet:org.eclipse.debug.ui.launchActionSet + persp.actionSet:org.eclipse.jdt.ui.JavaActionSet + persp.actionSet:org.eclipse.jdt.ui.JavaElementCreationActionSet + persp.actionSet:org.eclipse.ui.NavigateActionSet + persp.viewSC:org.eclipse.jdt.ui.PackageExplorer + persp.viewSC:org.eclipse.jdt.ui.TypeHierarchy + persp.viewSC:org.eclipse.jdt.ui.SourceView + persp.viewSC:org.eclipse.jdt.ui.JavadocView + persp.viewSC:org.eclipse.search.ui.views.SearchView + persp.viewSC:org.eclipse.ui.console.ConsoleView + persp.viewSC:org.eclipse.ui.views.ContentOutline + persp.viewSC:org.eclipse.ui.views.ProblemView + persp.viewSC:org.eclipse.ui.views.ResourceNavigator + persp.viewSC:org.eclipse.ui.views.TaskList + persp.viewSC:org.eclipse.ui.views.ProgressView + persp.viewSC:org.eclipse.ui.navigator.ProjectExplorer + persp.viewSC:org.eclipse.ui.texteditor.TemplatesView + persp.viewSC:org.eclipse.pde.runtime.LogView + persp.newWizSC:org.eclipse.jdt.ui.wizards.JavaProjectWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewPackageCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewClassCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewEnumCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewRecordCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewAnnotationCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard + persp.newWizSC:org.eclipse.jdt.ui.wizards.NewJavaWorkingSetWizard + persp.newWizSC:org.eclipse.ui.wizards.new.folder + persp.newWizSC:org.eclipse.ui.wizards.new.file + persp.newWizSC:org.eclipse.ui.editors.wizards.UntitledTextFileWizard + persp.perspSC:org.eclipse.jdt.ui.JavaBrowsingPerspective + persp.perspSC:org.eclipse.debug.ui.DebugPerspective + persp.viewSC:org.eclipse.mylyn.tasks.ui.views.tasks + persp.newWizSC:org.eclipse.mylyn.tasks.ui.wizards.new.repository.task + persp.showIn:org.eclipse.jdt.ui.PackageExplorer + persp.showIn:org.eclipse.team.ui.GenericHistoryView + persp.showIn:org.eclipse.ui.navigator.ProjectExplorer + persp.actionSet:org.eclipse.debug.ui.breakpointActionSet + persp.actionSet:org.eclipse.jdt.debug.ui.JDTDebugActionSet + persp.actionSet:org.eclipse.eclemma.ui.CoverageActionSet + persp.showIn:org.eclipse.eclemma.ui.CoverageView + persp.showIn:org.eclipse.egit.ui.RepositoriesView + persp.newWizSC:org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizard + persp.actionSet:org.eclipse.jdt.junit.JUnitActionSet + persp.viewSC:org.eclipse.ant.ui.views.AntView + persp.actionSet:org.eclipse.mylyn.doc.actionSet + + + + org.eclipse.e4.primaryNavigationStack + active + + View + categoryTag:Java + + + View + categoryTag:Java + + + View + categoryTag:General + + + View + categoryTag:Java + + + + + View + categoryTag:Git + + + + + + + + + + View + categoryTag:Mylyn + + + + org.eclipse.e4.secondaryNavigationStack + + View + categoryTag:General + + + View + categoryTag:General + + + View + categoryTag:General + + + View + categoryTag:Ant + + + + + + org.eclipse.e4.secondaryDataStack + + View + categoryTag:General + + + View + categoryTag:Java + + + View + categoryTag:Java + + + View + categoryTag:General + + + View + categoryTag:General + + + View + categoryTag:General + + + View + categoryTag:General + + + + + + + + + View + categoryTag:Help + + + View + categoryTag:General + + + View + categoryTag:Help + + + + + + + View + categoryTag:Help + + + + + + View + categoryTag:General + activeOnClose + + ViewMenu + menuContribution:menu + + + + + + + View + categoryTag:Help + + + + org.eclipse.e4.primaryDataStack + EditorStack + + + + + + + View + categoryTag:Java + active + activeOnClose + + ViewMenu + menuContribution:menu + + + + + + + View + categoryTag:Java + + + + + View + categoryTag:General + + + + + + View + categoryTag:General + + ViewMenu + menuContribution:menu + + + + + + + View + categoryTag:Java + + + + + View + categoryTag:Java + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + + View + categoryTag:General + + ViewMenu + menuContribution:menu + + + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + + View + categoryTag:Mylyn + + ViewMenu + menuContribution:menu + + + + + + + View + categoryTag:Git + + + + + View + categoryTag:Java + + + + + View + categoryTag:Ant + + + + toolbarSeparator + + + + Draggable + + + + toolbarSeparator + + + + Draggable + + + toolbarSeparator + + + + Draggable + + + Draggable + + + Draggable + + + toolbarSeparator + + + + Draggable + + + + toolbarSeparator + + + + toolbarSeparator + + + + Draggable + + + stretch + SHOW_RESTORE_MENU + + + Draggable + HIDEABLE + SHOW_RESTORE_MENU + + + + + stretch + + + Draggable + + + Draggable + + + + + Draggable + + + + + TrimStack + Draggable + + + + + + + + + + + + + + + + + + + + + + platform:win32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + platform:win32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Editor + removeOnHide + + + + + View + categoryTag:Gradle + + + + + View + categoryTag:Gradle + + + + + View + categoryTag:Java + + + View + categoryTag:Help + + + + + View + categoryTag:Ant + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Help + + + + + View + categoryTag:Debug + + + + + View + categoryTag:Java + + + + + View + categoryTag:Java + + + + + View + categoryTag:Java + + + + + View + categoryTag:Java Browsing + + + + + View + categoryTag:Java Browsing + + + + + View + categoryTag:Java Browsing + + + + + View + categoryTag:Java Browsing + + + + + View + categoryTag:Java + + + + + View + categoryTag:General + + + + + View + categoryTag:Java + + + + + View + categoryTag:Java + + + + + View + categoryTag:Maven + + + + + View + categoryTag:Maven + + + + + View + categoryTag:Mylyn + + + + + View + categoryTag:Mylyn + + + + + View + categoryTag:Mylyn + + + + + View + categoryTag:Oomph + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:Team + categoryTag:Version Control (Team) + + + + + View + categoryTag:Team + categoryTag:Version Control (Team) + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:Help + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:XML + + + + + View + categoryTag:XML + + + + + View + categoryTag:Git + + + + + View + categoryTag:Git + + + + + View + categoryTag:Git + + + + + View + categoryTag:Git + NoRestore + + + + + View + categoryTag:Git + + + + + View + categoryTag:General + + + + + View + categoryTag:General + + + + + View + categoryTag:Mylyn + + + + glue + move_after:PerspectiveSpacer + SHOW_RESTORE_MENU + + + move_after:Spacer Glue + HIDEABLE + SHOW_RESTORE_MENU + + + glue + move_after:SearchField + SHOW_RESTORE_MENU + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.metadata/.plugins/org.eclipse.jdt.core/assumedExternalFilesCache b/.metadata/.plugins/org.eclipse.jdt.core/assumedExternalFilesCache new file mode 100644 index 0000000..593f470 Binary files /dev/null and b/.metadata/.plugins/org.eclipse.jdt.core/assumedExternalFilesCache differ diff --git a/.metadata/.plugins/org.eclipse.jdt.core/externalFilesCache b/.metadata/.plugins/org.eclipse.jdt.core/externalFilesCache new file mode 100644 index 0000000..593f470 Binary files /dev/null and b/.metadata/.plugins/org.eclipse.jdt.core/externalFilesCache differ diff --git a/.metadata/.plugins/org.eclipse.jdt.core/nonChainingJarsCache b/.metadata/.plugins/org.eclipse.jdt.core/nonChainingJarsCache new file mode 100644 index 0000000..593f470 Binary files /dev/null and b/.metadata/.plugins/org.eclipse.jdt.core/nonChainingJarsCache differ diff --git a/.metadata/.plugins/org.eclipse.jdt.core/variablesAndContainers.dat b/.metadata/.plugins/org.eclipse.jdt.core/variablesAndContainers.dat new file mode 100644 index 0000000..0edae4b Binary files /dev/null and b/.metadata/.plugins/org.eclipse.jdt.core/variablesAndContainers.dat differ diff --git a/.metadata/.plugins/org.eclipse.jdt.ui/OpenTypeHistory.xml b/.metadata/.plugins/org.eclipse.jdt.ui/OpenTypeHistory.xml new file mode 100644 index 0000000..a4ee3cb --- /dev/null +++ b/.metadata/.plugins/org.eclipse.jdt.ui/OpenTypeHistory.xml @@ -0,0 +1,2 @@ + + diff --git a/.metadata/.plugins/org.eclipse.jdt.ui/QualifiedTypeNameHistory.xml b/.metadata/.plugins/org.eclipse.jdt.ui/QualifiedTypeNameHistory.xml new file mode 100644 index 0000000..9e390f5 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.jdt.ui/QualifiedTypeNameHistory.xml @@ -0,0 +1,2 @@ + + diff --git a/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml b/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml new file mode 100644 index 0000000..c69c0b2 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml @@ -0,0 +1,10 @@ + +
+
+ + + + + +
+
diff --git a/.metadata/.plugins/org.eclipse.m2e.logback.configuration/0.log b/.metadata/.plugins/org.eclipse.m2e.logback.configuration/0.log new file mode 100644 index 0000000..c1b78fc --- /dev/null +++ b/.metadata/.plugins/org.eclipse.m2e.logback.configuration/0.log @@ -0,0 +1,4 @@ +2020-12-21 11:32:09,851 [Worker-0: Loading available Gradle versions] INFO o.e.b.c.i.u.g.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. +2020-12-21 11:32:27,226 [Worker-0: Loading available Gradle versions] INFO o.e.b.c.i.u.g.PublishedGradleVersions - Updating Gradle version information cache failed. Using outdated cache. +2021-06-28 12:36:50,053 [Worker-2: Loading available Gradle versions] INFO o.e.b.c.i.u.g.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. +2021-06-28 12:41:23,776 [Worker-2: Loading available Gradle versions] INFO o.e.b.c.i.u.g.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. diff --git a/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.16.0.20200318-1040.xml b/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.16.0.20200318-1040.xml new file mode 100644 index 0000000..e33758c --- /dev/null +++ b/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.16.0.20200318-1040.xml @@ -0,0 +1,43 @@ + + + + %date [%thread] %-5level %logger{35} - %msg%n + + + OFF + + + + + ${org.eclipse.m2e.log.dir}/0.log + + ${org.eclipse.m2e.log.dir}/%i.log + 1 + 10 + + + 100MB + + + %date [%thread] %-5level %logger{35} - %msg%n + + + + + + WARN + + + + + + + + + + + + + + + diff --git a/.metadata/.plugins/org.eclipse.oomph.setup.ui/dialog_settings.xml b/.metadata/.plugins/org.eclipse.oomph.setup.ui/dialog_settings.xml new file mode 100644 index 0000000..23724b8 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.oomph.setup.ui/dialog_settings.xml @@ -0,0 +1,13 @@ + +
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.metadata/.plugins/org.eclipse.oomph.setup/workspace.setup b/.metadata/.plugins/org.eclipse.oomph.setup/workspace.setup new file mode 100644 index 0000000..1f73e14 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.oomph.setup/workspace.setup @@ -0,0 +1,6 @@ + + diff --git a/.metadata/.plugins/org.eclipse.tips.ide/dialog_settings.xml b/.metadata/.plugins/org.eclipse.tips.ide/dialog_settings.xml new file mode 100644 index 0000000..5ca0b77 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.tips.ide/dialog_settings.xml @@ -0,0 +1,3 @@ + +
+
diff --git a/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml b/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml new file mode 100644 index 0000000..3cc538e --- /dev/null +++ b/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml @@ -0,0 +1,24 @@ + +
+
+ + + + + + + + + + + +
+
+ + +
+
+ + +
+
diff --git a/.metadata/.plugins/org.eclipse.ui.intro/dialog_settings.xml b/.metadata/.plugins/org.eclipse.ui.intro/dialog_settings.xml new file mode 100644 index 0000000..4868369 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.ui.intro/dialog_settings.xml @@ -0,0 +1,4 @@ + +
+ +
diff --git a/.metadata/.plugins/org.eclipse.ui.intro/introstate b/.metadata/.plugins/org.eclipse.ui.intro/introstate new file mode 100644 index 0000000..236d56c --- /dev/null +++ b/.metadata/.plugins/org.eclipse.ui.intro/introstate @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml b/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml new file mode 100644 index 0000000..5b583c4 --- /dev/null +++ b/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml @@ -0,0 +1,5 @@ + +
+
+
+
diff --git a/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml b/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml new file mode 100644 index 0000000..1a4036f --- /dev/null +++ b/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.metadata/version.ini b/.metadata/version.ini new file mode 100644 index 0000000..57a6f44 --- /dev/null +++ b/.metadata/version.ini @@ -0,0 +1,3 @@ +#Mon Jun 28 12:40:06 CST 2021 +org.eclipse.core.runtime=2 +org.eclipse.platform=4.19.0.v20210303-1800 diff --git a/Chapter10/Reading_console_output.java b/Chapter10/Reading_console_output.java new file mode 100644 index 0000000..f6bea30 --- /dev/null +++ b/Chapter10/Reading_console_output.java @@ -0,0 +1,19 @@ +import java.io.IOException; + +public class Reading_console_output { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + + byte data[] = new byte[10]; + + System.out.println("Enter some characters:"); + System.in.read(data); + System.out.print("You entered: "); + + for (int i = 0; i < data.length; i++) + System.out.print((char) data[i]); + + } + +} diff --git a/Chapter11/Creating_a_Thread.java b/Chapter11/Creating_a_Thread.java new file mode 100644 index 0000000..adb6735 --- /dev/null +++ b/Chapter11/Creating_a_Thread.java @@ -0,0 +1,61 @@ +// Create a thread by implementing Runnable. +class MyThread2023 implements Runnable{ + // Objects of MyThread can be run in their own threads because MyThread implements Runnable. + + String thrdName; + + public MyThread2023(String name) { + thrdName = name; + } + + // Entry point of thread. + public void run() { // Threads start executing here. + + System.out.println(thrdName + " starting."); + + try { + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); + + System.out.println("In " + thrdName + ", count is " + count); + } + } catch (InterruptedException exc) { + System.out.println(thrdName + " interrupted."); + } + System.out.println(thrdName + " terminating."); + } + +} + + +public class Creating_a_Thread { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Main thread starting."); + + // First, construct a MyThread object. + MyThread2023 myThread2023 = new MyThread2023("Child #1"); // Create a runnable object. + + // Next, construct a thread from that object. + Thread newThread = new Thread(myThread2023); // Construct a thread on that object. + + // Finally, start execution of the thread. + newThread.start(); // Start running the thread. + + for (int i = 0; i < 50; i++) { + System.out.print("."); + try { + Thread.sleep(100); + } catch (InterruptedException exc) { + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/Creating_a_Thread_annotated.java b/Chapter11/Creating_a_Thread_annotated.java new file mode 100644 index 0000000..cab8c5e --- /dev/null +++ b/Chapter11/Creating_a_Thread_annotated.java @@ -0,0 +1,63 @@ +// Java defines two ways to create a runnable object: +// A class can implement the Runnable interface or extend the Thread class. +class MyThread202310 implements Runnable{ + + String thread_name; + + MyThread202310(String thread_name) { + + this.thread_name = thread_name; + + } + + // Inside run(), you can write some code that constitutes a thread. main() is a thread, too. + public void run() { + + System.out.println(thread_name + " starting."); + + + // Because Thread.sleep() can throw an InterruptedException, it must be wrapped in a try block. + try { + // a loop is established that counts from 0 to 9. + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); // causes the thread to suspend for 400 milliseconds. + System.out.println("In " + thread_name + ", count is " + count); + } + + } catch (InterruptedException e) { + + System.out.println(thread_name + " interrupted."); + + } + + // Thread will end when run() ends. + System.out.println(thread_name + " terminating."); + } + +} + + +public class Creating_a_Thread_annotated { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + System.out.println("Main thread starting."); + + // Create a runnable object. MyThread202310's object is runnable because it has run() method. + MyThread202310 myThread202310 = new MyThread202310("Child #1"); + + // You create a thread by instantiating an object of type Thread whose constructor encapsulates an object + // that is runnable. + Thread newThread = new Thread(myThread202310); + // Now, the other thread is constructed. + + // Once created, the new thread will not start running until you call its start() method. + newThread.start(); + // In essence, start() executes a call to run(). + + + System.out.println("Main thread ending."); + } + +} diff --git a/Chapter11/Creating_a_thread_annotated_2.java b/Chapter11/Creating_a_thread_annotated_2.java new file mode 100644 index 0000000..b91b810 --- /dev/null +++ b/Chapter11/Creating_a_thread_annotated_2.java @@ -0,0 +1,29 @@ +class apt implements Runnable { + + public void run() { + // TODO Auto-generated method stub + + } + +} + +public class Creating_a_thread_annotated_2 { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + + // You create a thread by instantiating an object of type Thread whose constructor encapsulates an object + // that is runnable. + + // This constructor is only useful when extending Thread to override the run() method.[1] +// Thread thread = new Thread(); [1] + + } + +} + +/* References: + * + * 1. https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Thread.html#constructor-detail + * + * */ diff --git a/Chapter11/Creating_a_thread_annotated_3.java b/Chapter11/Creating_a_thread_annotated_3.java new file mode 100644 index 0000000..2060791 --- /dev/null +++ b/Chapter11/Creating_a_thread_annotated_3.java @@ -0,0 +1,61 @@ +// Java defines two ways to create a runnable object: +// a class can either implement Runnable interface or extend Thread class. +class Aptly implements Runnable { + + String thread_name; + + Aptly(String thread_name) { + + this.thread_name = thread_name; + } + + // Inside run(), you can write some code that constitutes a thread. main() is a thread, too. + public void run() { + + System.out.println(thread_name + " starting."); + + for (int count = 0; count < 10; count++) { + + // Because Thread.sleep() can throw an InterruptedException, it must be wrapped in a try block. + try { + + Thread.sleep(400); + + System.out.println("In " + thread_name + ", count is " + count); + + } catch (InterruptedException e) { + + System.out.println(thread_name + " interrupted."); + } + + } + + // Thread will end when run() ends. + System.out.println(thread_name + " terminating."); + } + +} + + +public class Creating_a_thread_annotated_3 { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + // Aptly's objects are runnable because they implement Runnable interface. + Aptly apt = new Aptly("Child thread"); + + // You create a thread by instantiating an object of type Thread whose constructor encapsulates an object + // that is runnable. + Thread thread = new Thread(apt); + + thread.run(); + + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/Creating_a_thread_annotated_3_1.java b/Chapter11/Creating_a_thread_annotated_3_1.java new file mode 100644 index 0000000..1009946 --- /dev/null +++ b/Chapter11/Creating_a_thread_annotated_3_1.java @@ -0,0 +1,62 @@ +// Java defines two ways to create a runnable object: +// a class can either implement Runnable interface or extend Thread class. +class Aptly1 implements Runnable { + + String thread_name; + + Aptly1(String thread_name) { + + this.thread_name = thread_name; + + } + + // Inside run(), you can write some code that constitutes a thread. main() is a thread, too. + public void run() { + + System.out.println(thread_name + " starting."); + + for (int count = 0; count < 10; count++) { + + // Because Thread.sleep() can throw an InterruptedException, it must be wrapped in a try block. + try { + + Thread.sleep(400); + + System.out.println("In " + thread_name + ", count is " + count); + + } catch (InterruptedException e) { + + System.out.println(thread_name + " interrupted."); + } + + } + + // Thread will end when run() ends. + System.out.println(thread_name + " terminating."); + + } + +} + +public class Creating_a_thread_annotated_3_1 { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + // Aptly1's objects are runnable because they implement Runnable interface. + Aptly1 aptly1 = new Aptly1("Child thread"); + + // You create a thread by creating an object of type Thread whose constructor encapsulates an object + // that is runnable. + Thread thread = new Thread(aptly1); + + thread.start(); + + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/Creating_a_thread_annotated_3_2.java b/Chapter11/Creating_a_thread_annotated_3_2.java new file mode 100644 index 0000000..a38b294 --- /dev/null +++ b/Chapter11/Creating_a_thread_annotated_3_2.java @@ -0,0 +1,55 @@ +// Java defines two ways to create a runnable object: +// a class can either implement Runnable interface or extend Thread class. +class Aptness implements Runnable{ + + Aptness() { + + } + + // Inside run(), you can write some code that constitutes a thread. main() is a thread, too! + public void run() { + + for (int count = 0; count < 10; count++) { + + + // Because sleep() can throw up an InterruptedException, it must be wrapped in try/catch block. + try { + + Thread.sleep(400); + + System.out.println("In Child thread, count is " + count); + + } catch (InterruptedException e) { + + System.out.println("Thread interrupted."); + + } + + } + + // thread ends as it reaches its end. + System.out.println("Child thread will terminate as run() reaches its bottom."); + + } + +} + +public class Creating_a_thread_annotated_3_2 { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + + System.out.println("Main thread starts."); + + Aptness aptness = new Aptness(); + + // You create another thread by creating an object of class Thread whose constructor encapsulates an object + // that is runnable. + Thread thread = new Thread(aptness, "Child thread #1"); + + thread.start(); + + System.out.println("Main thread ends"); + } + +} diff --git a/Chapter11/Creating_a_thread_annotated_3_3.java b/Chapter11/Creating_a_thread_annotated_3_3.java new file mode 100644 index 0000000..9116fd6 --- /dev/null +++ b/Chapter11/Creating_a_thread_annotated_3_3.java @@ -0,0 +1,55 @@ +// Java defines two ways to create a runnable object: +// a class can either implement Runnable interface or extend Thread class. +class Aptness2 implements Runnable{ + + public Aptness2() { + + } + + // Inside run(), you can write some code that constitutes a thread. main() is a thread, too! + public void run() { + + for (int count = 0; count < 10; count++) { + + + // Because sleep() can throw up an InterruptedException, it must be wrapped in try/catch block. + try { + + Thread.sleep(400); + + System.out.println("In Child thread, count is " + count); + + } catch (InterruptedException e) { + + System.out.println("Thread interrupted."); + + } + } + + // thread ends as it reaches its end. + System.out.println("Child thread will terminate as run() reaches its bottom."); + + } +} + + +public class Creating_a_thread_annotated_3_3 { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + + System.out.println("Main thread starts."); + + Aptness2 aptness2 = new Aptness2(); + + // You create another thread by creating an object of class Thread whose constructor encapsulates an object + // that is runnable. + Thread thread = new Thread(aptness2, "Child thread #1"); + + thread.run(); + + System.out.println("Main thread ends"); + + } + +} diff --git a/Chapter11/Creating_multiple_threads.java b/Chapter11/Creating_multiple_threads.java new file mode 100644 index 0000000..ed1f822 --- /dev/null +++ b/Chapter11/Creating_multiple_threads.java @@ -0,0 +1,71 @@ +// Create multiple threads. + +class MyThreads implements Runnable{ + + Thread thread; + + public MyThreads(String name) { + + thread = new Thread(this, name); + + } + + + static MyThreads createAndStart(String name) { + + MyThreads myThreads = new MyThreads(name); + + myThreads.thread.start(); + + return myThreads; + + } + + + public void run() { + + System.out.println(thread.getName() + " starting."); + + try { + + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); + System.out.println("In " + thread.getName() + ", count is " + count); + } + + } catch (InterruptedException e) { + System.out.println(thread.getName() + " interrupted."); + } + System.out.println(thread.getName() + " terminating."); + } +} + + +public class Creating_multiple_threads { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + MyThreads mt1 = MyThreads.createAndStart("Child #1"); + MyThreads mt2 = MyThreads.createAndStart("Child #2"); + MyThreads mt3 = MyThreads.createAndStart("Child #3"); + + for (int i = 0; i < 50; i++) { + + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + + System.out.println("Main thread interrupted."); + } + + } + + System.out.println("Main thread ending"); + } + +} diff --git a/Chapter11/Creating_multiple_threads_2.java b/Chapter11/Creating_multiple_threads_2.java new file mode 100644 index 0000000..1c7f6a6 --- /dev/null +++ b/Chapter11/Creating_multiple_threads_2.java @@ -0,0 +1,75 @@ +class OurThread implements Runnable { + + Thread thread; + + public OurThread() { + + } + + public OurThread(String name) { + + thread = new Thread(this, name); + + } + + public void run() { + + System.out.println(thread.getName() + " starting."); + + try { + + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); + System.out.println("In " + thread.getName() + ", count is " + count); + } + + } catch (InterruptedException e) { + System.out.println(thread.getName() + " interrupted."); + } + + System.out.println(thread.getName() + " terminating."); + + } + + +} + + +public class Creating_multiple_threads_2 { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + OurThread ot1 = new OurThread(); + OurThread ot2 = new OurThread("Child #2"); + OurThread ot3 = new OurThread("Child #3"); + + // OurThread ot4 = new OurThread("Child #4").thread.start(); + + new OurThread("Child #5").thread.start(); + new OurThread("Child #6").thread.start(); + + OurThread ot7 = new OurThread("Child #7"); + + ot7.thread.start(); + + for (int i = 0; i < 50; i++) { + + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + + System.out.println("Main thread interrupted."); + } + + } + + System.out.println("Main thread ending"); + + } + +} diff --git a/Chapter11/Determining_When_a_thread_ends.java b/Chapter11/Determining_When_a_thread_ends.java new file mode 100644 index 0000000..7e0fb87 --- /dev/null +++ b/Chapter11/Determining_When_a_thread_ends.java @@ -0,0 +1,12 @@ + +public class Determining_When_a_thread_ends { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + + + } + +} diff --git a/Chapter11/Multi_threaded_programming.java b/Chapter11/Multi_threaded_programming.java new file mode 100644 index 0000000..685d169 --- /dev/null +++ b/Chapter11/Multi_threaded_programming.java @@ -0,0 +1,62 @@ +// Create a thread by implementing Runnable. +public class Multi_threaded_programming { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Main thread starting."); + + // First, construct a MyThread object. + MyThread myThread = new MyThread("Child #1"); // Create a runnable object. + + // Next, construct a thread from that object. + Thread thread = new Thread(myThread); + + thread.start(); + + + for (int i = 0; i < 50; i++) { + System.out.println("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + } + +} + +class MyThread implements Runnable { + + String thread_nameString; + + public MyThread(String name) { + // TODO Auto-generated constructor stub + thread_nameString = name; + } + + // Entry point of thread. + public void run() { // Thread starts executing here. + System.out.println(thread_nameString + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread_nameString + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread_nameString + " interrupted."); + } + + System.out.println(thread_nameString + " terminating."); + + } + +} diff --git a/Chapter11/Multi_threaded_programming_.java b/Chapter11/Multi_threaded_programming_.java new file mode 100644 index 0000000..caefb60 --- /dev/null +++ b/Chapter11/Multi_threaded_programming_.java @@ -0,0 +1,61 @@ + +public class Multi_threaded_programming_ { + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println("Main thread starting."); + + // First, construct a MyThread object. + MyThread myThread = new MyThread("Child #1"); // Create a runnable object. + + // Next, construct a thread from that object. + Thread thread = new Thread(myThread); + + thread.start(); + + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + } + +} + +class MyThread2 implements Runnable { + + String thread_nameString; + + public MyThread2(String name) { + // TODO Auto-generated constructor stub + thread_nameString = name; + } + + // Entry point of thread. + public void run() { // Thread starts executing here. + System.out.println(thread_nameString + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread_nameString + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread_nameString + " interrupted."); + } + + System.out.println(thread_nameString + " terminating."); + + } + +} diff --git a/Chapter11/One_Improvement_Two_Simple_Variations.java b/Chapter11/One_Improvement_Two_Simple_Variations.java new file mode 100644 index 0000000..5c4ccb2 --- /dev/null +++ b/Chapter11/One_Improvement_Two_Simple_Variations.java @@ -0,0 +1,69 @@ +// MyThread variations. This version of MyThread creates a Thread when its constructor is called and stores it in +// an instance variable called thread. +// It also sets the name of thread and provides a factory method to create and start a thread. + +class MyThread20231007_2 implements Runnable{ + + Thread thread; // A reference to the thread is stored in thread. + + // Construct a new thread using this Runnable and give it a name. + public MyThread20231007_2(String name) { + thread = new Thread(thread, name); + } + + static MyThread20231007_2 createAndStart(String name) { + + MyThread20231007_2 myThread20231007_2 = new MyThread20231007_2(name); + + myThread20231007_2.thread.start(); // Start the thread. (Begin executing the thread.) + + return myThread20231007_2; + } + + public void run() { + + System.out.println(thread.getName() + " starting."); + + try { + + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + System.out.println("In " + thread.getName() + ", count is " + count); + } + + } catch (InterruptedException e) { + System.out.println(thread.getName() + " interrupted."); + } + System.out.println(thread.getName() + " terminating."); + } + +} + + +public class One_Improvement_Two_Simple_Variations { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Main thread starting."); + + // Create and start a thread. (Create and start a thread in one step.) + MyThread20231007_2 myThread20231007_2 = MyThread20231007_2.createAndStart("Child #1"); + // Now, the thread starts when it is created. + + for (int i = 0; i < 50; i++) { + + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + } + +} diff --git a/Chapter11/One_Improvement_and_Two_Simple_Variations.java b/Chapter11/One_Improvement_and_Two_Simple_Variations.java new file mode 100644 index 0000000..e7459c3 --- /dev/null +++ b/Chapter11/One_Improvement_and_Two_Simple_Variations.java @@ -0,0 +1,68 @@ +// MyThread variations. This version of MyThread creates a Thread when its constructor is called and stores it in +// an instance variable called thread. +// It also sets the name of thread and provides a factory method to create and start a thread. + +class MyThread20231007 implements Runnable{ + + Thread thread; // A reference to the thread is stored in thread. + + // Construct a new thread using this Runnable and give it a name. + public MyThread20231007(String name) { + thread = new Thread(this, name); + } + + static MyThread20231007 createAndStart(String name) { + + MyThread20231007 myThread20231007 = new MyThread20231007(name); + + myThread20231007.thread.start(); + + return myThread20231007; + + } + + public void run() { + // TODO Auto-generated method stub + System.out.println(thread.getName() + " starting."); + + try { + + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + System.out.println("In " + thread.getName() + ", count is " + count); + } + + } catch (InterruptedException e) { + System.out.println(thread.getName() + " interrupted."); + } + System.out.println(thread.getName() + " terminating."); + } + +} + + +public class One_Improvement_and_Two_Simple_Variations { + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println("Main thread starting."); + + // Create and start a new thread. (Create and start a thread in one step.) + MyThread20231007 myThread20231007 = MyThread20231007.createAndStart("Child #1"); + // Now, the thread starts when it is created. + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + } + +} diff --git a/Chapter11/ThreadVariations.java b/Chapter11/ThreadVariations.java new file mode 100644 index 0000000..3e0b2f8 --- /dev/null +++ b/Chapter11/ThreadVariations.java @@ -0,0 +1,70 @@ +// MyThread variations. This version of MyThread creates a Thread when its constructor is called and +// stores it in an instance variable called thread_name_String. +// It also sets the name of the thread and provides a factory method to create and start a thread. +public class ThreadVariations { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Main thread starting."); + + // Create and start a thread. + MyThread_improvement myThread_improvement = MyThread_improvement.createAndStart("Child #1"); + // Now the new thread starts when it is created. + + for (int i = 0; i < 50; i++) { + System.out.print('.'); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + + } + +} + +class MyThread_improvement implements Runnable{ + + Thread thread; // A reference to the thread is stored in thread. + + public MyThread_improvement(String name) { + thread = new Thread(this, name); // The thread is named when it is created. + + } + + // A factory method that creates and starts a thread. + public static MyThread_improvement createAndStart(String name) { + MyThread_improvement myThread_improvement = new MyThread_improvement(name); + + myThread_improvement.thread.start(); + + return myThread_improvement; + } + + // Entry point of thread. + public void run() { + // TODO Auto-generated method stub + System.out.println(thread.getName() + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread.getName() + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread.getName() + " interrupted."); + } + + System.out.println(thread.getName() + " terminating."); + + } + +} diff --git a/Chapter11/Try_This_11_1.java b/Chapter11/Try_This_11_1.java new file mode 100644 index 0000000..c94d488 --- /dev/null +++ b/Chapter11/Try_This_11_1.java @@ -0,0 +1,58 @@ +/* + * Try This 11-1 + * + * Extend Thread. + * + */ + +class ExtendThread extends Thread{ + + public ExtendThread(String name) { + super(name); + } + + public void run() { + // TODO Auto-generated method stub + System.out.println(getName() + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + System.out.println("In " + getName() + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(getName() + " interrupted."); + } + + System.out.println(getName() + " terminating."); + } + +} + +public class Try_This_11_1 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Main thread starting."); + + ExtendThread myExtendThread = new ExtendThread("Child #1"); + + myExtendThread.start(); + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + } + +} diff --git a/Chapter11/Try_This_11_1_1.java b/Chapter11/Try_This_11_1_1.java new file mode 100644 index 0000000..9d4a315 --- /dev/null +++ b/Chapter11/Try_This_11_1_1.java @@ -0,0 +1,49 @@ +class ExtendThread1 extends Thread{ + + public ExtendThread1(String name) { + super(name); + } + + // When a class extends Thread, it must override the run() method, which is the entry point for the new thread, + // It must also call start() to begin execution of the new thread. + public void run() { + System.out.println(getName() + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + System.out.println("In " + getName() + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(getName() + " interrupted."); + } + + System.out.println(getName() + " terminating."); + } + +} + + +public class Try_This_11_1_1 { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + new ExtendThread1("Child #1").start(); + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + + System.out.println("Main thread interrupted."); + } + } + System.out.println("Main thread ending."); + } + +} diff --git a/Chapter11/Try_This_11_1_2.java b/Chapter11/Try_This_11_1_2.java new file mode 100644 index 0000000..94b8b4d --- /dev/null +++ b/Chapter11/Try_This_11_1_2.java @@ -0,0 +1,60 @@ + +class ExtendThread2 extends Thread{ + + public ExtendThread2(String name) { + super(name); + } + + static ExtendThread2 createAndStart(String name) { + + ExtendThread2 myExtendThread2 = new ExtendThread2(name); + + myExtendThread2.start(); + + return myExtendThread2; + } + + public void run() { + // TODO Auto-generated method stub + System.out.println(getName() + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + System.out.println("In " + getName() + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(getName() + " interrupted."); + } + + System.out.println(getName() + " terminating."); + } + +} + +public class Try_This_11_1_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println("Main thread starting."); + + // Create and start a thread in one step. + ExtendThread2 myExtendThread = ExtendThread2.createAndStart("Child #1"); + + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted."); + } + } + + System.out.println("Main thread ending."); + } + +} diff --git a/Chapter11/UseThreads.java b/Chapter11/UseThreads.java new file mode 100644 index 0000000..24cff04 --- /dev/null +++ b/Chapter11/UseThreads.java @@ -0,0 +1,51 @@ + +public class UseThreads { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Main thread starting."); + + Thread myThread = new Thread(new Runnable() { + + public void run() { + // TODO Auto-generated method stub + + String thread_nameString = "Child #1"; + + System.out.println(thread_nameString + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread_nameString + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread_nameString + " interrupted."); + } + + System.out.println(thread_nameString + " terminating."); + } + }); + + myThread.start(); + + for (int i = 0; i < 50; i++) { + System.out.println("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted"); + } + } + + System.out.println("Main thread ending."); + + + } + +} diff --git a/Chapter11/UseThreads2.java b/Chapter11/UseThreads2.java new file mode 100644 index 0000000..dd1fb43 --- /dev/null +++ b/Chapter11/UseThreads2.java @@ -0,0 +1,47 @@ + +public class UseThreads2 { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + new Thread(new Runnable() { + + public void run() { + + String thread_nameString = "Child #1"; + + System.out.println(thread_nameString + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread_nameString + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread_nameString + " interrupted."); + } + + System.out.println(thread_nameString + " terminating."); + + } + }).start(); + + for (int i = 0; i < 50; i++) { + System.out.println("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted"); + } + } + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/UseThreads3.java b/Chapter11/UseThreads3.java new file mode 100644 index 0000000..c0cd496 --- /dev/null +++ b/Chapter11/UseThreads3.java @@ -0,0 +1,46 @@ + +public class UseThreads3 { + + public static void main(String[] args) { + System.out.println("Main thread starting."); + + new Thread(new Runnable() { + + public void run() { + + String thread_nameString = "Child #1"; + + System.out.println(thread_nameString + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread_nameString + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread_nameString + " interrupted."); + } + + System.out.println(thread_nameString + " terminating."); + + } + }).start(); + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted"); + } + } + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/UseThreads_.java b/Chapter11/UseThreads_.java new file mode 100644 index 0000000..42460e1 --- /dev/null +++ b/Chapter11/UseThreads_.java @@ -0,0 +1,49 @@ + +public class UseThreads_ { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + Thread myThread = new Thread(new Runnable() { + + public void run() { + // TODO Auto-generated method stub + + String thread_nameString = "Child #1"; + + System.out.println(thread_nameString + " starting."); + + try { + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + + System.out.println("In " + thread_nameString + ", count is " + count); + } + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println(thread_nameString + " interrupted."); + } + + System.out.println(thread_nameString + " terminating."); + } + }); + + myThread.start(); + + for (int i = 0; i < 50; i++) { + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO: handle exception + System.out.println("Main thread interrupted"); + } + } + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/evade_repetitive_class_name/Creating_a_Thread.java b/Chapter11/evade_repetitive_class_name/Creating_a_Thread.java new file mode 100644 index 0000000..2edc67a --- /dev/null +++ b/Chapter11/evade_repetitive_class_name/Creating_a_Thread.java @@ -0,0 +1,60 @@ +// Adapting Create_a_Thread.java to creating a runnable object by extending Thread class. +package evade_repetitive_class_name; + +// Java defines two ways to create a runnable object: +// a class can either implement Runnable interface or extend Thread class. +class MyThread2023 extends Thread{ + + int n; + + MyThread2023(int thread_number) { + + n = thread_number; + + } + + // Entry point of the thread. + public void run() { + + System.out.println(getName() + " #" + n + " starting."); + + // Because Thread.sleep() can throw up an InterruptedException, it must be wrapped in try/catch block. + try { + + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); + + System.out.println("In " + getName() + ", count is " + count); + } + + } catch (InterruptedException e) { + + System.out.println(getName() + " #" + n + " interrupted."); + } + + System.out.println(getName() + " terminating."); + } + +} + +public class Creating_a_Thread { + + // From the main thread, you can create other threads. + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + // MyThread2023's object is runnable because it inherits run() from Thread class. + MyThread2023 myThread2023 = new MyThread2023(1); + + // Creating a thread by instantiating Thread class. Its constructor encapsulates a runnable object. + Thread thread = new Thread(myThread2023, "Child thread"); + + thread.start(); + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/evade_repetitive_class_name/Creating_a_Thread_2.java b/Chapter11/evade_repetitive_class_name/Creating_a_Thread_2.java new file mode 100644 index 0000000..1fa1ea0 --- /dev/null +++ b/Chapter11/evade_repetitive_class_name/Creating_a_Thread_2.java @@ -0,0 +1,62 @@ +package evade_repetitive_class_name; + +class MyThread2023_2 extends Thread{ + + int n; + + MyThread2023_2(int thread_number) { + + n = thread_number; + + } + + // Entry point of the thread. + public void run() { + + System.out.println(getName() + " #" + n + " starting."); + + // Because Thread.sleep() can throw up an InterruptedException, it must be wrapped in try/catch block. + try { + + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); + + System.out.println("In " + getName() + ", count is " + count); + } + + } catch (InterruptedException e) { + + System.out.println(getName() + " #" + n + " interrupted."); + } + + System.out.println(getName() + " terminating."); + } + +} + +public class Creating_a_Thread_2 { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + // MyThread2023's object is runnable because it inherits run() from Thread class. + MyThread2023_2 myThread2023_2 = new MyThread2023_2(1); + + myThread2023_2.start(); + + myThread2023_2.run(); + + // Creating a thread by instantiating Thread class. Its constructor encapsulates a runnable object. + Thread thread = new Thread(myThread2023_2, "Child thread"); + + thread.start(); + + thread.run(); + + System.out.println("Main thread ending."); + + } + +} diff --git a/Chapter11/evade_repetitive_class_name/Interrupts.java b/Chapter11/evade_repetitive_class_name/Interrupts.java new file mode 100644 index 0000000..0b7a24a --- /dev/null +++ b/Chapter11/evade_repetitive_class_name/Interrupts.java @@ -0,0 +1,35 @@ +package evade_repetitive_class_name; + +public class Interrupts implements Runnable { + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + } + + @Override + public void run() { + + int inputs[] = new int[50000]; + + for (int i = 0; i < inputs.length; i++) { + i = inputs[i]; + + heavyCrunch(inputs[i]); + + if (Thread.interrupted()) { + + System.out.println("We have been interrupted; no more crunching."); + } + + + } + + } + + void heavyCrunch(int element) { + + } + +} diff --git a/Chapter11/modulation/Creating_a_thread.java b/Chapter11/modulation/Creating_a_thread.java new file mode 100644 index 0000000..c55544c --- /dev/null +++ b/Chapter11/modulation/Creating_a_thread.java @@ -0,0 +1,57 @@ +package modulation; + +public class Creating_a_thread implements Runnable { + + String threadName; + + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + new Thread(new Creating_a_thread("Child #1")).start(); + + for (int i = 0; i < 50; i++) { + + System.out.print("."); + + try { + Thread.sleep(100); + } catch (InterruptedException exc) { + System.out.println("Main thread interrupted"); + } + } + + System.out.println("Main thread ending."); + } + + + public void run() { + + System.out.println(threadName + " starting."); + + try { + + for (int count = 0; count < 10; count++) { + + Thread.sleep(400); + + System.out.println("In " + threadName + ", count is " + count); + + } + + } catch (InterruptedException exc) { + + System.out.println(threadName + " interrupted."); + + } + + System.out.println(threadName + " terminating."); + } + + public Creating_a_thread(String threadName) { + + this.threadName = threadName; + } + +} diff --git a/Chapter11/modulation/Creating_a_thread_by_extending_Thread.java b/Chapter11/modulation/Creating_a_thread_by_extending_Thread.java new file mode 100644 index 0000000..b7a458f --- /dev/null +++ b/Chapter11/modulation/Creating_a_thread_by_extending_Thread.java @@ -0,0 +1,56 @@ +package modulation; + +public class Creating_a_thread_by_extending_Thread extends Thread { + + String threadName; + + public static void main(String[] args) { + + System.out.println("Main thread starting."); + + new Creating_a_thread_by_extending_Thread("Child #1").start(); + + for (int i = 0; i < 50; i++) { + + System.out.print("."); + + try { + + Thread.sleep(100); + + } catch (InterruptedException exc) { + + System.out.println("Main thread interrupted."); + } + } + System.out.println("Main thread ending."); + } + + + @Override + public void run() { + + System.out.println(threadName + " starting."); + + try { + + for (int count = 0; count < 10; count++) { + Thread.sleep(400); + System.out.println("In " + threadName + ", count is " + count); + } + + } catch (InterruptedException exc) { + System.out.println(threadName + " interrupted."); + } + + System.out.println(threadName + " terminating."); + + } + + public Creating_a_thread_by_extending_Thread(String threadName) { + + this.threadName = threadName; + + } + +} diff --git a/Chapter11/oracle_tutorial/HelloRunnable.java b/Chapter11/oracle_tutorial/HelloRunnable.java new file mode 100644 index 0000000..58e08e3 --- /dev/null +++ b/Chapter11/oracle_tutorial/HelloRunnable.java @@ -0,0 +1,20 @@ +package oracle_tutorial; + +public class HelloRunnable implements Runnable { + + public static void main(String[] args) { + + (new Thread(new HelloRunnable())).start(); + + } + + @Override + public void run() { + System.out.println("Hello from a thread!"); + + } + +} + +// Reference: +// https://web.archive.org/web/20230702090555/https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html \ No newline at end of file diff --git a/Chapter11/oracle_tutorial/HelloRunnable2.java b/Chapter11/oracle_tutorial/HelloRunnable2.java new file mode 100644 index 0000000..c7d8a50 --- /dev/null +++ b/Chapter11/oracle_tutorial/HelloRunnable2.java @@ -0,0 +1,23 @@ +package oracle_tutorial; + +public class HelloRunnable2 implements Runnable { + + public static void main(String[] args) { + + new Thread(new HelloRunnable2()).start(); + + } + + + public void run() { + + System.out.println("Hello from a thread"); + + } + + + +} + +//Reference: +//https://web.archive.org/web/20230702090555/https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html diff --git a/Chapter11/oracle_tutorial/HelloThread.java b/Chapter11/oracle_tutorial/HelloThread.java new file mode 100644 index 0000000..dd50dbf --- /dev/null +++ b/Chapter11/oracle_tutorial/HelloThread.java @@ -0,0 +1,21 @@ +package oracle_tutorial; + +public class HelloThread extends Thread { + + public static void main(String[] args) { + + new HelloThread().start(); + + } + + @Override + public void run() { + + System.out.println("Hello from a thread!"); + + } + +} + +//Reference: +//https://web.archive.org/web/20230702090555/https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html diff --git a/Chapter11/oracle_tutorial/Pausing_Execution_with_Sleep.java b/Chapter11/oracle_tutorial/Pausing_Execution_with_Sleep.java new file mode 100644 index 0000000..eb288dd --- /dev/null +++ b/Chapter11/oracle_tutorial/Pausing_Execution_with_Sleep.java @@ -0,0 +1,25 @@ +package oracle_tutorial; + +public class Pausing_Execution_with_Sleep { + + public static void main(String[] args) throws InterruptedException { + + String importantInfo[] = { + "Mares eat oats", + "Does eat oats", + "Little lambs eat ivy", + "A kid will eat ivy too" + }; + + for (int i = 0; i < importantInfo.length; i++) { + + //Pause for 4 seconds + Thread.sleep(4000); + + //Print a message + System.out.println(importantInfo[i]); + } + } +} + +// Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html diff --git a/Chapter11/oracle_tutorial/The_Simple_Threads_Example.java b/Chapter11/oracle_tutorial/The_Simple_Threads_Example.java new file mode 100644 index 0000000..31a80cf --- /dev/null +++ b/Chapter11/oracle_tutorial/The_Simple_Threads_Example.java @@ -0,0 +1,69 @@ +package oracle_tutorial; + +public class The_Simple_Threads_Example { + + // Display a message, preceded by the name of the current thread + static void threadMessage(String message) { + String threadName = Thread.currentThread().getName(); + System.out.format("%s: %s%n", threadName, message); + } + + private static class MessageLoop implements Runnable { + public void run() { + String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", + "A kid will eat ivy too" }; + try { + for (int i = 0; i < importantInfo.length; i++) { + // Pause for 4 seconds + Thread.sleep(4000); + // Print a message + threadMessage(importantInfo[i]); + } + } catch (InterruptedException e) { + threadMessage("I wasn't done!"); + } + } + } + + public static void main(String[] args) throws InterruptedException { + + // Delay, in milliseconds before we interrupt MessageLoop thread (default one hour). + long patience = 1000 * 60 * 60; + + // If command line argument present, gives patience in seconds. + if (args.length > 0) { + try { + patience = Long.parseLong(args[0]) * 1000; + } catch (NumberFormatException e) { + System.err.println("Argument must be an integer."); + System.exit(1); + } + } + + threadMessage("Starting MessageLoop thread"); + long startTime = System.currentTimeMillis(); + Thread t = new Thread(new MessageLoop()); + t.start(); + + threadMessage("Waiting for MessageLoop thread to finish"); + + // loop until MessageLoop thread exits + while (t.isAlive()) { + threadMessage("Still waiting..."); + + // Wait maximum of 1 second for MessageLoop thread to finish. + t.join(1000); + if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { + threadMessage("Tired of waiting!"); + t.interrupt(); + // Shouldn't be long now -- wait indefinitely + t.join(); + } + } + + threadMessage("Finally!"); + } + +} + +// Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html diff --git a/Chapter12/Coins_used_in_the_US.java b/Chapter12/Coins_used_in_the_US.java new file mode 100644 index 0000000..0bc4c96 --- /dev/null +++ b/Chapter12/Coins_used_in_the_US.java @@ -0,0 +1,5 @@ +// An enumeration is a list of named constants that define a new data type. +public enum Coins_used_in_the_US { + penny, nickel, dime, quater, half_dollar, dollar + +} diff --git a/Chapter12/Days_in_a_week.java b/Chapter12/Days_in_a_week.java new file mode 100644 index 0000000..b156571 --- /dev/null +++ b/Chapter12/Days_in_a_week.java @@ -0,0 +1,11 @@ + // An enumeration is a list of named constants that define a new data type. +public enum Days_in_a_week { + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday + +} diff --git a/Chapter12/Enum.java b/Chapter12/Enum.java new file mode 100644 index 0000000..1a9cab0 --- /dev/null +++ b/Chapter12/Enum.java @@ -0,0 +1,41 @@ +// Demonstrate ordinal() and compareTo() +// An enumeration of Transport varieties. + +enum Transport_{ + CAR, TRUCK, AIRPLANE, TRAIN, BOAT; +} + +public class Enum { + + public static void main(String[] args) { + Transport_ tp, tp2, tp3; + + // Obtain all ordinal values using ordinal() + System.out.println("Here are all Transport_ constants " + "and their ordinal values: "); + + for (Transport_ defuse : Transport_.values()) { + System.out.println(defuse + " " + defuse.ordinal()); // Obtain ordinal values. + } + + tp = Transport_.AIRPLANE; + tp2 = Transport_.TRAIN; + tp3 = Transport_.AIRPLANE; + + System.out.println(); + + // Demonstrate compareTo() + if (tp.compareTo(tp2) < 0) { + System.out.println(tp + " comes before " + tp2); + } + + if (tp.compareTo(tp2) > 0) { + System.out.println(tp2 + " comes before " + tp); + } + + if (tp.compareTo(tp3) == 0) { + System.out.println(tp + " equals " + tp3); + } + + } + +} diff --git a/Chapter12/EnumDemo.java b/Chapter12/EnumDemo.java new file mode 100644 index 0000000..84b7e3f --- /dev/null +++ b/Chapter12/EnumDemo.java @@ -0,0 +1,50 @@ + +public class EnumDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport tpTransport; + + tpTransport = Transport.AIRPLANE; + + // Output an enumeration value. + System.out.println("Value of tpTransport: " + tpTransport); + + System.out.println(); + + tpTransport = Transport.TRAIN; + + // Compare two enum values. + if (tpTransport == Transport.TRAIN) + System.out.println("tpTransport contains TRAIN.\n"); + + switch (tpTransport) { + + case CAR: + System.out.println("A car carries people."); + break; + + case TRUCK: + System.out.println("A truck carries freight."); + break; + + case AIRPLANE: + System.out.println("An airplane flies."); + break; + + case TRAIN: + System.out.println("A train runs on rails."); + break; + + case BOAT: + System.out.println("A boat sails on water."); + break; + + default: + throw new IllegalArgumentException("Unexpected value: "); + } + + } + +} diff --git a/Chapter12/EnumDemo2.java b/Chapter12/EnumDemo2.java new file mode 100644 index 0000000..7fb8b0d --- /dev/null +++ b/Chapter12/EnumDemo2.java @@ -0,0 +1,20 @@ +// Use the built-in enumeration methods. +public class EnumDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport tp; + + System.out.println("Here are all Transport constants: "); + + // Use values() + Transport allTransport[] = Transport.values(); // Obtain an array of Transport constants. + + for (Transport transport : allTransport) { + System.out.println(transport); + } + + } + +} diff --git a/Chapter12/EnumDemo3.java b/Chapter12/EnumDemo3.java new file mode 100644 index 0000000..51fa946 --- /dev/null +++ b/Chapter12/EnumDemo3.java @@ -0,0 +1,19 @@ +// All enumerations automatically have two pre-defined methods: values() and valueOf() +// values() returns an array that contains a list of the enumeration constants. +public class EnumDemo3 { + + public static void main(String[] args) { + Transport tpTransport; + + System.out.println("Here are all Transport constants: "); + + // Use values() + Transport allTransport[] = Transport.values(); // Obtain an array of Transport constants. + + for (Transport transport : allTransport) { + System.out.println(transport); + } + + } + +} diff --git a/Chapter12/EnumDemo3_.java b/Chapter12/EnumDemo3_.java new file mode 100644 index 0000000..553343d --- /dev/null +++ b/Chapter12/EnumDemo3_.java @@ -0,0 +1,39 @@ +// Use an enumeration constructor, instance variable, and method. +enum Transportation{ + + CAR(65), TRUCK(55), AIRPLANE(600), TRAIN(70), BOAT(22); // Notice the initialization values. + + private int typical_speed_of_each_transportation; // add an instance variable. + + // Constructor + Transportation(int s) { + // TODO Auto-generated constructor stub + typical_speed_of_each_transportation = s; + } + + int get_speed() { + return typical_speed_of_each_transportation; + } +} + + +public class EnumDemo3_ { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transportation tpTransportation; + + // Display speed of an airplane. + System.out.println("Typical speed for an airplane is " + Transportation.AIRPLANE.get_speed() + " miles per hour."); + + // Display all transportations and speeds. + System.out.println("All Transportation speeds: "); + + for (Transportation t : Transportation.values()) { + System.out.println(t + " typical speed is " + t.get_speed() + " miles per hour."); + } + + } + +} diff --git a/Chapter12/EnumDemo4.java b/Chapter12/EnumDemo4.java new file mode 100644 index 0000000..a271f79 --- /dev/null +++ b/Chapter12/EnumDemo4.java @@ -0,0 +1,18 @@ + +public class EnumDemo4 { + + public static void main(String[] args) { + Transport tp = Transport.AIRPLANE; + + System.out.println("Here are all Transport constants: "); + + // Use values() + Transport allTransport[] = tp.values(); // Obtain an array of Transport constants. + + for (Transport transport : allTransport) { + System.out.println(transport); + } + + } + +} diff --git a/Chapter12/EnumDemo5.java b/Chapter12/EnumDemo5.java new file mode 100644 index 0000000..6cf0923 --- /dev/null +++ b/Chapter12/EnumDemo5.java @@ -0,0 +1,26 @@ +// Use the built-in enumeration static methods. +public class EnumDemo5 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport tpTransport; + + System.out.println("Here are all Transport constants."); + + // use values() + Transport allTransport[] = Transport.values(); + + for (Transport transport : allTransport) { + System.out.println(transport); + } + + System.out.println(); + + // use valueOf() + tpTransport = Transport.valueOf("CAR"); + System.out.println("tpTransport contains " + tpTransport); + + } + +} diff --git a/Chapter12/EnumDemo6.java b/Chapter12/EnumDemo6.java new file mode 100644 index 0000000..68d541c --- /dev/null +++ b/Chapter12/EnumDemo6.java @@ -0,0 +1,13 @@ + +public class EnumDemo6 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + for (Transport transport : Transport.values()) { + System.out.println(transport); + } + + } + +} diff --git a/Chapter12/EnumDemo7.java b/Chapter12/EnumDemo7.java new file mode 100644 index 0000000..b5d7a25 --- /dev/null +++ b/Chapter12/EnumDemo7.java @@ -0,0 +1,13 @@ + +public class EnumDemo7 { + + public static void main(String[] args) { + + // System can directly print out either numeric constants or named constants. + for (Transport transport : Transport.values()) { + System.out.println(transport); + } + + } + +} diff --git a/Chapter12/EnumDemo_.java b/Chapter12/EnumDemo_.java new file mode 100644 index 0000000..53f883d --- /dev/null +++ b/Chapter12/EnumDemo_.java @@ -0,0 +1,39 @@ + +public class EnumDemo_ { + public static void main(String[] args) { + + int i; + + i = 10; + + System.out.println("Value of i: " + i); + + System.out.println(); + + i = 2; + + if (i == 2) + System.out.println("i contains 2.\n"); + + switch (i) { + case 2: + System.out.println("A boat sails on water."); + break; + case 4: + System.out.println("A truck carries freight."); + break; + case 6: + System.out.println("An airplane flies."); + break; + case 8: + System.out.println("Smooth sailing."); + break; + case 10: + System.out.println("Freight trains."); + break; + default: + break; + } + + } +} diff --git a/Chapter12/EnuumDemo2.java b/Chapter12/EnuumDemo2.java new file mode 100644 index 0000000..9097a27 --- /dev/null +++ b/Chapter12/EnuumDemo2.java @@ -0,0 +1,39 @@ + +public class EnuumDemo2 { + public static void main(String[] args) { + + int i; + + i = 10; + + System.out.println("Value of i: " + i); + + System.out.println(); + + i = 2; + + if (i == 2) + System.out.println("i contains 2.\n"); + + switch (i) { + case 2: + System.out.println("A boat sails on water."); + break; + case 4: + System.out.println("A truck carries freight."); + break; + case 6: + System.out.println("An airplane flies."); + break; + case 8: + System.out.println("Smooth sailing."); + break; + case 10: + System.out.println("Freight trains."); + break; + default: + break; + } + + } +} diff --git a/Chapter12/Exercise3.java b/Chapter12/Exercise3.java new file mode 100644 index 0000000..f40cbc8 --- /dev/null +++ b/Chapter12/Exercise3.java @@ -0,0 +1,23 @@ + +enum Tools{ + SCREWDRIVER(1), WRENCH(2), HAMMER(3), PLIERS(4); + + int catcher; + + Tools(int i) { + catcher = i; + } +} + +public class Exercise3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + for (Tools item : Tools.values()) { + System.out.println("The No." + item.catcher + " tool is " + item); + } + + } + +} diff --git a/Chapter12/Experimental/Enum.java b/Chapter12/Experimental/Enum.java new file mode 100644 index 0000000..30ddb2a --- /dev/null +++ b/Chapter12/Experimental/Enum.java @@ -0,0 +1,35 @@ +package Experimental; + +enum Transport_{ + CAR, TRUCK, AIRPLANE, TRAIN, BOAT; +} + +public class Enum { + + public static void main(String[] args) { + Transport_ tp, tp2, tp3; + + // Obtain all ordinal values using ordinal() + System.out.println("Here are all Transport_ constants " + "and their ordinal values: "); + + for (Transport_ defuse : Transport_.values()) { + System.out.println(defuse + " " + defuse.ordinal()); // Obtain ordinal values. + } + + tp = Transport_.AIRPLANE; + tp2 = Transport_.TRAIN; + tp3 = Transport_.AIRPLANE; + + System.out.println(); + + if (tp.compareTo(tp2) > 0) { + System.out.println(tp2 + " comes before " + tp); + } else if (tp.compareTo(tp2) == 0) { + System.out.println(tp + " equals " + tp2); + } else if (tp.compareTo(tp2) < 0) { + System.out.println(tp + " comes before " + tp2); + } + + } + +} diff --git a/Chapter12/Experimental/EnumDemo3_2.java b/Chapter12/Experimental/EnumDemo3_2.java new file mode 100644 index 0000000..a8d1b0e --- /dev/null +++ b/Chapter12/Experimental/EnumDemo3_2.java @@ -0,0 +1,32 @@ +package Experimental; + +enum Transportation{ + CAR(65), TRUCK(55), AIRPLANE(600), TRAIN(70), BOAT(22); + + int typical_speed; + + Transportation(int i) { + typical_speed = i; + } + + void show() { + System.out.println("Typical speed is at " + typical_speed); + } +} + +public class EnumDemo3_2 { + + public static void main(String[] args) { + + // Similar to int a = 1; + Transportation a = Transportation.TRUCK; + + // Transportation's method. + System.out.println(a.typical_speed); + + a.show(); + + System.out.println("Typical speed of boat is at " + Transportation.BOAT.typical_speed); + } + +} diff --git a/Chapter12/Experimental/Enum_.java b/Chapter12/Experimental/Enum_.java new file mode 100644 index 0000000..fc26ac4 --- /dev/null +++ b/Chapter12/Experimental/Enum_.java @@ -0,0 +1,26 @@ +package Experimental; + +enum Transport{ + AIRPLANE, BOAT, TRAIN, CAR, TRUCK +} + +public class Enum_ { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport tpTransport = Transport.TRUCK; + int defuse = 1; + + System.out.println(tpTransport.ordinal()); + System.out.println(defuse); + + System.out.println(Transport.AIRPLANE.ordinal()); +// System.out.println(Transport.AIRPLANE.ordinal();); +// System.out.println(int defusion = 3;); + + System.out.println(); + + } + +} diff --git a/Chapter12/Months_in_a_year_Western_calender.java b/Chapter12/Months_in_a_year_Western_calender.java new file mode 100644 index 0000000..200e0fe --- /dev/null +++ b/Chapter12/Months_in_a_year_Western_calender.java @@ -0,0 +1,4 @@ +// An enumeration is a list of named constants that define a new data type. +public enum Months_in_a_year_Western_calender { + January, February, March, April, May, June, July, August, September, October, November, December +} diff --git a/Chapter12/TrafficLightDemo.java b/Chapter12/TrafficLightDemo.java new file mode 100644 index 0000000..b89c0f2 --- /dev/null +++ b/Chapter12/TrafficLightDemo.java @@ -0,0 +1,105 @@ + +enum TrafficLightColor{ + RED, YELLOW, GREEN +} + +class TrafficLightSimulator implements Runnable { + private TrafficLightColor trafficLightColor; // holds the traffic light color. + private boolean stop = false; // set to true to stop the simulation. + private boolean changed = false; // true when the light has changed. + + public TrafficLightSimulator(TrafficLightColor initiaLightColor) { + trafficLightColor = initiaLightColor; + } + + public TrafficLightSimulator() { + trafficLightColor = TrafficLightColor.RED; + } + + public void run() { + while (!stop) { + try { + switch (trafficLightColor) { + case GREEN: + Thread.sleep(10000); // green for 10 seconds. + break; + case YELLOW: + Thread.sleep(2000); // yellow for 2 seconds. + break; + case RED: + Thread.sleep(12000); // red for 12 seconds. + break; + default: + break; + } + } catch (InterruptedException exc) { + System.out.println(exc); + } + changeColor(); + } + } + + // change color. + synchronized void changeColor() { + switch (trafficLightColor) { + case RED: + trafficLightColor = TrafficLightColor.GREEN; + break; + case YELLOW: + trafficLightColor = TrafficLightColor.RED; + break; + case GREEN: + trafficLightColor = TrafficLightColor.YELLOW; + + default: + break; + } + + changed = true; + notify(); // signal that the light has changed. + + } + + // Wait until a light change occurs. + synchronized void waitForChange() { + try { + while (!changed) { + wait(); // wait for light to change. + changed = false; + } + } catch (InterruptedException exc) { + System.out.println(exc); + } + } + + // Return current color. + synchronized TrafficLightColor getTrafficLightColor() { + return trafficLightColor; + } + + // Stop the traffic light. + synchronized void cancel() { + stop = true; + } +} + +public class TrafficLightDemo { + + public static void main(String[] args) { + + TrafficLightSimulator t1 = new TrafficLightSimulator(TrafficLightColor.GREEN); + + Thread thrdThread = new Thread(t1); + + thrdThread.start(); + + for (int i = 0; i < 9; i++) { + System.out.println(t1.getTrafficLightColor()); + t1.waitForChange(); + } + + t1.cancel(); + + } + +} diff --git a/Chapter12/Transport.java b/Chapter12/Transport.java new file mode 100644 index 0000000..6acfa53 --- /dev/null +++ b/Chapter12/Transport.java @@ -0,0 +1,4 @@ +// An enumeration is a list of named constants that define a new data type. +public enum Transport { + CAR, TRUCK, AIRPLANE, TRAIN, BOAT +} diff --git a/Chapter12/primitive_type_equivaluet_of_valueOf.java b/Chapter12/primitive_type_equivaluet_of_valueOf.java new file mode 100644 index 0000000..ac3ddc3 --- /dev/null +++ b/Chapter12/primitive_type_equivaluet_of_valueOf.java @@ -0,0 +1,13 @@ + +public class primitive_type_equivaluet_of_valueOf { + + public static void main(String[] args) { + + // System can directly print out either numeric constants or named constants. + System.out.println(200); + System.out.println(Transport.valueOf("BOAT")); + System.out.println(Transport.TRUCK); + + } + +} diff --git a/Chapter12/value_of.java b/Chapter12/value_of.java new file mode 100644 index 0000000..119a744 --- /dev/null +++ b/Chapter12/value_of.java @@ -0,0 +1,12 @@ + +public class value_of { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport tpTransport = Transport.valueOf("AIRPLANE"); + System.out.println("tpTransport contains " + tpTransport); + + } + +} diff --git a/Chapter12/value_of_2.java b/Chapter12/value_of_2.java new file mode 100644 index 0000000..942af51 --- /dev/null +++ b/Chapter12/value_of_2.java @@ -0,0 +1,17 @@ + +public class value_of_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport tpTransport[] = Transport.values(); + + for (Transport transport : tpTransport) { + System.out.println(transport); + } + + System.out.println(Transport.valueOf("BOAT")); + + } + +} diff --git a/Chapter12/value_of_3.java b/Chapter12/value_of_3.java new file mode 100644 index 0000000..c4fef3b --- /dev/null +++ b/Chapter12/value_of_3.java @@ -0,0 +1,18 @@ + +public class value_of_3 { + + public static void main(String[] args) { + + // values() returns an array of the enumeration constants. + Transport tpTransport[] = Transport.values(); + + for (Transport transport : tpTransport) { + System.out.println(transport); + } + + // valueOf() returns the enumeration constant whose value corresponds to the string passed to the argument. + System.out.println(Transport.valueOf("BOAT")); + + } + +} diff --git a/Chapter12/values_method.java b/Chapter12/values_method.java new file mode 100644 index 0000000..5e59141 --- /dev/null +++ b/Chapter12/values_method.java @@ -0,0 +1,15 @@ +// values() is a pre-defined static method of enumeration. +public class values_method { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Transport allTransport[] = Transport.values(); + + for (Transport transport : allTransport) { + System.out.println(transport); + } + + } + +} diff --git a/Chapter12/values_method2.java b/Chapter12/values_method2.java new file mode 100644 index 0000000..df34769 --- /dev/null +++ b/Chapter12/values_method2.java @@ -0,0 +1,11 @@ + +public class values_method2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println(Transport.values()); + + } + +} diff --git a/Chapter14/A_lambda_expression_is_an_anonymous_method.java b/Chapter14/A_lambda_expression_is_an_anonymous_method.java new file mode 100644 index 0000000..a5f4c4b --- /dev/null +++ b/Chapter14/A_lambda_expression_is_an_anonymous_method.java @@ -0,0 +1,22 @@ + +public class A_lambda_expression_is_an_anonymous_method { + + static double myMeth() { + return 98.6; + } + +// Lambda form: () - > 98.6; + + + public static void main(String[] args) { + + var x = myMeth(); + + System.out.println(x); + + var y = () -> 98.6; + + System.out.println(y); + + } +} diff --git a/Chapter3/Self_Test_Chapter3_No1.java b/Chapter3/Self_Test_Chapter3_No1.java new file mode 100644 index 0000000..af6ecee --- /dev/null +++ b/Chapter3/Self_Test_Chapter3_No1.java @@ -0,0 +1,35 @@ +import java.io.IOException; + +/* + * Write a program that reads characters from the keyboard until a period is received. + * + * Have the program count the number of spaces. Report the total at the end of the program. + * + * */ +public class Self_Test_Chapter3_No1 { + + public static void main(String[] args) throws IOException { + + int number_of_space = 0; + + System.out.println("The program will read characters until a period is received. \nPlease input: "); + + byte[] b = new byte[50]; + + System.in.read(b); + + System.out.println("Your input were: "); + + for (int i = 0; i < b.length; i++) { + System.out.print( (char) b[i]); + + if(b[i] == 32) number_of_space++; + + if(b[i] == 46) break; + } + + System.out.println(); + + System.out.println("The number of space is: " + number_of_space); + } +} diff --git a/Chapter3/Self_Test_Chapter3_No10.java b/Chapter3/Self_Test_Chapter3_No10.java index 8a7b610..9f12516 100644 --- a/Chapter3/Self_Test_Chapter3_No10.java +++ b/Chapter3/Self_Test_Chapter3_No10.java @@ -3,15 +3,50 @@ /* * To convert a lowercase letter to uppercase, subtract 32 from it. * + * Write a program that reads characters from the keyboard. Have it convert all lowercase letters to uppercase, and all + * uppercase letters to lowercase, displaying the result. Make no changes to any other character. Have the program stop + * when the user enters a period. At the end, have the program display the number of case changes that have taken place. + * * */ public class Self_Test_Chapter3_No10 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub - char ch; + int number_of_changes = 0; + byte[] b = new byte[100]; + + System.out.print("Input a roll of characters and the program will convert all lowercase letters to uppercase"); + System.out.print(", and vice versa. \nPlease input: "); + + System.in.read(b); + + for (int i = 0; i < b.length; i++) { + + if(b[i] >= 65 && b[i] <= 90) { + + b[i] = (byte) (b[i] + 32); + + number_of_changes++; + } + else if(b[i] >= 97 && b[i] <= 122) { + + b[i] = (byte) (b[i] - 32); + + number_of_changes++; + } + } + + System.out.print("The roll of characters are: \n"); + + for (int i = 0; i < b.length; i++) { + System.out.print( (char) b[i] + " "); + + if(b[i] == 46) break; + } - ch = (char) System.in.read(); + System.out.println(); + System.out.println("The number of case changes that have taken place: " + number_of_changes); } diff --git a/Chapter3/Self_Test_Chapter3_No9-ted10014-PC.java b/Chapter3/package2/Help3.java similarity index 69% rename from Chapter3/Self_Test_Chapter3_No9-ted10014-PC.java rename to Chapter3/package2/Help3.java index 38898c9..bb4231a 100644 --- a/Chapter3/Self_Test_Chapter3_No9-ted10014-PC.java +++ b/Chapter3/package2/Help3.java @@ -1,5 +1,6 @@ +package package2; -public class Self_Test_Chapter3_No9 { +public class Help3 { public static void main(String[] args) { // TODO Auto-generated method stub diff --git a/Chapter4b/Functions.java b/Chapter4b/Functions.java new file mode 100644 index 0000000..4a67286 --- /dev/null +++ b/Chapter4b/Functions.java @@ -0,0 +1,15 @@ +// Implement it in Java for Python > Python machine learning for beginners > Chapter2 > Functions.py +public class Functions { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + myfunc(); + + } + + static void myfunc() { + System.out.println("This is a simple function."); + } + +} diff --git a/Chapter4b/Functions2.java b/Chapter4b/Functions2.java new file mode 100644 index 0000000..4feee8b --- /dev/null +++ b/Chapter4b/Functions2.java @@ -0,0 +1,15 @@ +// Implement it in Java for Python > Python machine learning for beginners > Chapter2 > Functions2.py +public class Functions2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + myfuncparam("Paramter 1"); + + } + + static void myfuncparam (String num) { + System.out.println("This is a function with parameter value: " + num); + } + +} diff --git a/Chapter4b/Functions3.java b/Chapter4b/Functions3.java new file mode 100644 index 0000000..31cb458 --- /dev/null +++ b/Chapter4b/Functions3.java @@ -0,0 +1,20 @@ +// // Implement it in Java for Python > Python machine learning for beginners > Chapter2 > Functions3.py +public class Functions3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + myreturnfunc(); + + var val = myreturnfunc(); + + System.out.println(val); + + } + + static String myreturnfunc() { + + return "This function returns a value."; + } + +} diff --git a/Chapter4b/Functions4.java b/Chapter4b/Functions4.java new file mode 100644 index 0000000..5d5a1cb --- /dev/null +++ b/Chapter4b/Functions4.java @@ -0,0 +1,16 @@ +// Implement it in Java for Python > Python machine learning for beginners > Chapter2 > Functions4.py +public class Functions4 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + myreturnfunc(); + + } + + static String myreturnfunc() { + + return "This function returns a value."; // Note that to return a value does not mean to print a value onto the screen. + } + +} diff --git a/Chapter4b/Shark.java b/Chapter4b/Shark.java new file mode 100644 index 0000000..982080c --- /dev/null +++ b/Chapter4b/Shark.java @@ -0,0 +1,26 @@ +// Coding the Python project in Java. + +public class Shark { + + String name; + int age; + + Shark(String name, int age){ + + this.name = name; + this.age = age; + + System.out.println("This is the constructor method."); + + } + + void swim(){ + + System.out.println(name + " is swimming."); + + } + + void be_awesome(){ + System.out.println(name + " is being awesome."); + } +} diff --git a/Chapter4b/Shark_objects.java b/Chapter4b/Shark_objects.java new file mode 100644 index 0000000..d6ae901 --- /dev/null +++ b/Chapter4b/Shark_objects.java @@ -0,0 +1,19 @@ + +public class Shark_objects { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Shark sammy = new Shark("Sammy", 5); + sammy.swim(); + sammy.be_awesome(); + + System.out.println(sammy.name); + System.out.println(sammy.age); + + Shark stevie = new Shark("Stevie", 80); + stevie.swim(); + + } + +} diff --git a/Chapter4c/AddMeth.java b/Chapter4c/AddMeth.java new file mode 100644 index 0000000..f9acb6b --- /dev/null +++ b/Chapter4c/AddMeth.java @@ -0,0 +1,34 @@ + +// Add range to Vehicle. + +public class AddMeth { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Vehicle minivan = new Vehicle(); + Vehicle sportscar = new Vehicle(); + + int range1, range2; + + // assign values to fields in minivan + minivan.passengers = 7; + minivan.fuelcap = 16; + minivan.mpg = 21; + + // assign values to fields in sportscar + sportscar.passengers = 2; + sportscar.fuelcap = 14; + sportscar.mpg = 12; + + System.out.print("Minivan can carry " + minivan.passengers + ". "); + + minivan.range(); // display range of minivan + + System.out.print("Sportscar can carry " + sportscar.passengers + ". "); + + sportscar.range(); // display range of sportscar. + + } + +} diff --git a/Chapter4c/ChkNum.java b/Chapter4c/ChkNum.java new file mode 100644 index 0000000..67d54d1 --- /dev/null +++ b/Chapter4c/ChkNum.java @@ -0,0 +1,10 @@ +// A simple example that uses a parameter. + +public class ChkNum { + // return true if x is even + boolean isEven(int x) { // Here, x is an integer parameter of isEven(). + if ( (x % 2) == 0 ) return true; + else return false; + } + +} diff --git a/Chapter4c/CompFuel.java b/Chapter4c/CompFuel.java new file mode 100644 index 0000000..42e5a6a --- /dev/null +++ b/Chapter4c/CompFuel.java @@ -0,0 +1,31 @@ + +public class CompFuel { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Vehicle minivanVehicle = new Vehicle(); + Vehicle sportscarVehicle = new Vehicle(); + double gallons; + int dist = 252; + + // assign values to fields in minivan + minivanVehicle.passengers = 7; + minivanVehicle.fuelcap = 16; + minivanVehicle.mpg = 21; + + // assign values to fields in sportscar + sportscarVehicle.passengers = 2; + sportscarVehicle.fuelcap = 16; + sportscarVehicle.mpg =12; + + gallons = minivanVehicle.fuelneeded(dist); + + System.out.println("To go " + dist + " miles, minivan needs " + gallons + " gallons of fuel."); + + gallons = sportscarVehicle.fuelneeded(dist); + System.out.println("To go " + dist + " miles, sportscar needs " + gallons + " gallons of fuel."); + + } + +} diff --git a/Chapter4c/ConsDemo.java b/Chapter4c/ConsDemo.java new file mode 100644 index 0000000..b75cf6c --- /dev/null +++ b/Chapter4c/ConsDemo.java @@ -0,0 +1,14 @@ + +public class ConsDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + MyClass t1 = new MyClass(); + MyClass t2 = new MyClass(); + + System.out.println(t1.x + " " + t2.x); + + } + +} diff --git a/Chapter4c/DemoPwr.java b/Chapter4c/DemoPwr.java new file mode 100644 index 0000000..96b315a --- /dev/null +++ b/Chapter4c/DemoPwr.java @@ -0,0 +1,17 @@ + +public class DemoPwr { + + public static void main(String[] args) { + Pwr xPwr = new Pwr(4.0, 2); + Pwr yPwr = new Pwr(2.5, 1); + Pwr zPwr = new Pwr(5.7, 0); + + System.out.println(xPwr.b + " raised to the " + xPwr.e + " power is " + xPwr.get_pwr() ); + + System.out.println(yPwr.b + " raised to the " + yPwr.e + " power is " + yPwr.get_pwr() ); + + System.out.println(zPwr.b + " raised to the " + zPwr.e + " power is " + zPwr.get_pwr()); + + } + +} diff --git a/Chapter4c/DemoPwr2.java b/Chapter4c/DemoPwr2.java new file mode 100644 index 0000000..7a603df --- /dev/null +++ b/Chapter4c/DemoPwr2.java @@ -0,0 +1,17 @@ + +public class DemoPwr2 { + + public static void main(String[] args) { + Pwr2 xPwr2 = new Pwr2(4.0, 2); + Pwr2 yPwr2 = new Pwr2(2.5, 1); + Pwr2 zPwr2 = new Pwr2(5.7, 0); + + System.out.println(xPwr2.b + " raised to the " + xPwr2.e + " power is " + xPwr2.get_pwr() ); + + System.out.println(yPwr2.b + " raised to the " + yPwr2.e + " power is " + yPwr2.get_pwr() ); + + System.out.println(zPwr2.b + " raised to the " + zPwr2.e + " power is " + zPwr2.get_pwr() ); + + } + +} diff --git a/Chapter4c/Factor.java b/Chapter4c/Factor.java new file mode 100644 index 0000000..5caab01 --- /dev/null +++ b/Chapter4c/Factor.java @@ -0,0 +1,8 @@ + +public class Factor { + boolean isFactor(int a, int b) { + if ( (b % a) ==0 ) return true; + else return false; + } + +} diff --git a/Chapter4c/Help.java b/Chapter4c/Help.java new file mode 100644 index 0000000..e8d11de --- /dev/null +++ b/Chapter4c/Help.java @@ -0,0 +1,73 @@ +/* + * Try This 4-1 + * + * Convert the help system from Try This 3-3 into a Help class. * + * + * */ + +public class Help { + + void helpOn(int what) { + + switch (what) { + case '1': + System.out.println("The if:\n"); + System.out.println("if(condition) statement;"); + System.out.println("else statement;"); + break; + case '2': + System.out.println("The switch:\n"); + System.out.println("switch(expression) {"); + System.out.println(" case constant:"); + System.out.println(" statement sequence"); + System.out.println(" break;"); + System.out.println(" // ..."); + System.out.println("}"); + break; + case '3': + System.out.println("The for:\n"); + System.out.print("for(init; condition; iteration)"); + System.out.println(" statement;"); + break; + case '4': + System.out.println("The while:\n"); + System.out.println("while(condition) statement;"); + break; + case '5': + System.out.println("The do-while:\n"); + System.out.println("do {"); + System.out.println(" statement;"); + System.out.println("} while (condition);"); + break; + case '6': + System.out.println("The break:\n"); + System.out.println("break; or break label;"); + break; + case '7': + System.out.println("The continue:\n"); + System.out.println("continue; or continue label;"); + break; + } + + System.out.println(); + + } + + void showMenu() { + + System.out.println("Help on:"); + System.out.println(" 1. if"); + System.out.println(" 2. switch"); + System.out.println(" 3. for"); + System.out.println(" 4. while"); + System.out.println(" 5. do-while"); + System.out.println(" 6. break"); + System.out.println(" 7. continue\n"); + System.out.print("Choose one (q to quit): "); + } + + boolean isValid(int ch) { + if(ch < '1' | ch > '7' & ch != 'q') return false; + else return true; + } +} diff --git a/Chapter4c/HelpClassDemo.java b/Chapter4c/HelpClassDemo.java new file mode 100644 index 0000000..abf3d9d --- /dev/null +++ b/Chapter4c/HelpClassDemo.java @@ -0,0 +1,35 @@ +import java.io.IOException; + +public class HelpClassDemo { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + + char choice, ignore; + Help hlpobj = new Help(); + + for (;;) { + + do { + + hlpobj.showMenu(); + + choice = (char) System.in.read(); + + do { + ignore = (char) System.in.read(); + } while (ignore != '\n'); + + } while (!hlpobj.isValid(choice)); + + if (choice == 'q') + break; + + System.out.println("\n"); + + hlpobj.helpOn(choice); + + } + } + +} diff --git a/Chapter4c/IsFact.java b/Chapter4c/IsFact.java new file mode 100644 index 0000000..0b6f816 --- /dev/null +++ b/Chapter4c/IsFact.java @@ -0,0 +1,17 @@ + +public class IsFact { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Factor xFactor = new Factor(); + + if (xFactor.isFactor(2, 20)) // Pass two arguments to isFactor(). + System.out.println("2 is factor"); + + if (xFactor.isFactor(3, 20)) + System.out.println("this won't be displayed."); + + } + +} diff --git a/Chapter4c/MyClass.java b/Chapter4c/MyClass.java new file mode 100644 index 0000000..c85a7dd --- /dev/null +++ b/Chapter4c/MyClass.java @@ -0,0 +1,10 @@ +// A simple constructor. +public class MyClass { + + int x; + + MyClass() { + x = 10; + } + +} diff --git a/Chapter4c/MyClass2.java b/Chapter4c/MyClass2.java new file mode 100644 index 0000000..1dda539 --- /dev/null +++ b/Chapter4c/MyClass2.java @@ -0,0 +1,12 @@ +// A parameterized constructor. +public class MyClass2 { + + int x; + + MyClass2(int i) { // This constructor has a parameter. + // TODO Auto-generated constructor stub + + x = i; + } + +} diff --git a/Chapter4c/MyClass4.java b/Chapter4c/MyClass4.java new file mode 100644 index 0000000..344908b --- /dev/null +++ b/Chapter4c/MyClass4.java @@ -0,0 +1,19 @@ + +public class MyClass4 { + + int x; + + public MyClass4(int x) { + + x = x; + } + + public static void main(String[] args) { + + MyClass4 intel_MyClass4 = new MyClass4(8); + + System.out.println("Value of x = " + intel_MyClass4.x); + + } + +} diff --git a/Chapter4c/ParaConsDemo.java b/Chapter4c/ParaConsDemo.java new file mode 100644 index 0000000..917ce90 --- /dev/null +++ b/Chapter4c/ParaConsDemo.java @@ -0,0 +1,14 @@ + +public class ParaConsDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + MyClass2 t1MyClass2 = new MyClass2(10); + MyClass2 t2MyClass2 = new MyClass2(88); + + System.out.println(t1MyClass2.x + " " + t2MyClass2.x); + + } + +} diff --git a/Chapter4c/ParmDemo.java b/Chapter4c/ParmDemo.java new file mode 100644 index 0000000..2c43a83 --- /dev/null +++ b/Chapter4c/ParmDemo.java @@ -0,0 +1,19 @@ + +public class ParmDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ChkNum e = new ChkNum(); + + if (e.isEven(10) ) // Pass arguments to isEven(). + System.out.println("10 is even."); + + if (e.isEven(9) ) + System.out.println("9 is even."); + if (e.isEven(8) ) + System.out.println("8 is even."); + + } + +} diff --git a/Chapter4c/Pwr.java b/Chapter4c/Pwr.java new file mode 100644 index 0000000..342827e --- /dev/null +++ b/Chapter4c/Pwr.java @@ -0,0 +1,23 @@ + +public class Pwr { + + double b; + int e; + double val; + + public Pwr(double base, int exp) { + + b = base; + e = exp; + + val = 1; + + if(exp == 0 ) return; + for( ; exp>0 ; exp--) val = val*base; + } + + double get_pwr() { + return val; + } + +} diff --git a/Chapter4c/Pwr2.java b/Chapter4c/Pwr2.java new file mode 100644 index 0000000..b01833b --- /dev/null +++ b/Chapter4c/Pwr2.java @@ -0,0 +1,21 @@ + +public class Pwr2 { + + double b ; + int e; + double val; + + public Pwr2(double base, int exp) { + this.b = base; + this.e = exp; + + this.val = 1; + if(exp == 0) return; + for( ; exp > 0 ; exp--) this.val = this.val * base; + } + + double get_pwr() { + return this.val; + } + +} diff --git a/Chapter4c/Pwr3.java b/Chapter4c/Pwr3.java new file mode 100644 index 0000000..821742d --- /dev/null +++ b/Chapter4c/Pwr3.java @@ -0,0 +1,16 @@ + +public class Pwr3 { + + double b, val; + int e; + + public Pwr3(double b, int e) { + this.b = b; + this.e = e; + + val = 1; + if (e==0) return; + for( ; e>0 ; e--) val = val * b; + } + +} diff --git a/Chapter4c/Pwr4.java b/Chapter4c/Pwr4.java new file mode 100644 index 0000000..55318c5 --- /dev/null +++ b/Chapter4c/Pwr4.java @@ -0,0 +1,27 @@ +// Java syntax permits the name of a parameter or a local variable to be the same as the name of an instance variable. +// When this happens, the local name hides the instance variable. +// You can gain access to the hidden instance variable by referring to it through this. + +public class Pwr4 { + + double b; + int e; + double val; + + public Pwr4(double b, int e) { + + this.b = b; + this.e = e; + + this.val = 1; + + if(e == 0) return; + for( ; e > 0 ; e--) this.val = this.val * b; + + } + + double get_pwr() { + return this.val; + } + +} diff --git a/Chapter4c/RetMeth.java b/Chapter4c/RetMeth.java new file mode 100644 index 0000000..0941783 --- /dev/null +++ b/Chapter4c/RetMeth.java @@ -0,0 +1,34 @@ + +// Use a return value. +public class RetMeth { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Vehicle minivan = new Vehicle(); + Vehicle sportscar = new Vehicle(); + + int range1, range2; + + // AssignAddExpression values to fields in minivan + + minivan.passengers = 7; + minivan.fuelcap = 16; + minivan.mpg = 21; + + // assign values to fields in sportscar + sportscar.passengers = 2; + sportscar.fuelcap = 14; + sportscar.mpg = 12; + + // get the ranges + range1 = minivan.range2(); // Assign the value returned to a variable. + range2 = sportscar.range2(); // Assign the values returned to a variable. + + System.out.println("Minivan can carry " + minivan.passengers + " with range of " + range1 + " miles"); + + System.out.println("Sportscar can carry " + sportscar.passengers + " with range of " + range2 + " miles"); + + } + +} diff --git a/Chapter4c/RetMeth2.java b/Chapter4c/RetMeth2.java new file mode 100644 index 0000000..ffadfa6 --- /dev/null +++ b/Chapter4c/RetMeth2.java @@ -0,0 +1,29 @@ + +public class RetMeth2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Vehicle minivan = new Vehicle(); + Vehicle sportscar = new Vehicle(); + + + + // AssignAddExpression values to fields in minivan + + minivan.passengers = 7; + minivan.fuelcap = 16; + minivan.mpg = 21; + + // assign values to fields in sportscar + sportscar.passengers = 2; + sportscar.fuelcap = 14; + sportscar.mpg = 12; + + System.out.println("Minivan can carry " + minivan.passengers + " with range of " + minivan.range2() + " miles"); + + System.out.println("Sportscar can carry " + sportscar.passengers + " with range of " + sportscar.range2() + " miles"); + + } + +} diff --git a/Chapter4c/TwoVehicles.java b/Chapter4c/TwoVehicles.java new file mode 100644 index 0000000..5415c6e --- /dev/null +++ b/Chapter4c/TwoVehicles.java @@ -0,0 +1,33 @@ +// This program creates two Vehicle objects. + +// This class declares an object of type Vehicle. +public class TwoVehicles { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Vehicle minivan = new Vehicle(); + Vehicle sportscar = new Vehicle(); + + int range1, range2; + + // assign values to fields in minivan + minivan.passengers = 7; + minivan.fuelcap = 16; + minivan.mpg = 21; + + // assign values to fields in sportscar + sportscar.passengers = 2; + sportscar.fuelcap = 14; + sportscar.mpg = 12; + + // compute the range assuming a full tank of gas + range1 = minivan.fuelcap * minivan.mpg; + range2 = sportscar.fuelcap * sportscar.mpg; + + System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range1); + + System.out.println("Sportscar can carry " + sportscar.passengers + " with a range of " + range2); + + } + +} diff --git a/Chapter4c/VehConsDemo.java b/Chapter4c/VehConsDemo.java new file mode 100644 index 0000000..0de1c9a --- /dev/null +++ b/Chapter4c/VehConsDemo.java @@ -0,0 +1,21 @@ + +public class VehConsDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + // construct complete vehicles + Vehicle2 minivanVehicle = new Vehicle2(7, 16, 21); + Vehicle2 sportscarVehicle = new Vehicle2(2, 14, 12); + + int dist = 252; + double gallons = minivanVehicle.fuelneeded(dist); + System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel."); + + gallons = sportscarVehicle.fuelneeded(dist); + + System.out.println("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel."); + + } + +} diff --git a/Chapter4c/Vehicle.java b/Chapter4c/Vehicle.java new file mode 100644 index 0000000..d3e4409 --- /dev/null +++ b/Chapter4c/Vehicle.java @@ -0,0 +1,24 @@ + +class Vehicle { + + int passengers; // number of passengers. + int fuelcap; // fuel capacity in gallons. + int mpg; // fuel consumption in miles per gallon. + + // Display the range. + void range() { // The range() method is contained within the Vehicle class. + System.out.println("Range is " + fuelcap * mpg); + } + + // Return the range. + int range2() { + return mpg * fuelcap; + + } + + // Compute fuel needed for a given distance. + double fuelneeded(int miles) { + return miles/mpg; + } + +} \ No newline at end of file diff --git a/Chapter4c/Vehicle2.java b/Chapter4c/Vehicle2.java new file mode 100644 index 0000000..94ff9ab --- /dev/null +++ b/Chapter4c/Vehicle2.java @@ -0,0 +1,31 @@ + +public class Vehicle2 { + + int passengers; // number of passengers. + int fuelcap; // fuel capacity in gallons. + int mpg; // fuel consumption in miles per gallon. + + // Display the range. + void range() { // The range() method is contained within the Vehicle class. + System.out.println("Range is " + fuelcap * mpg); + } + + // Return the range. + int range2() { + return mpg * fuelcap; + + } + + // Compute fuel needed for a given distance. + double fuelneeded(int miles) { + return miles/mpg; + } + + // This is a constructor for Vehicle. + public Vehicle2(int p, int f, int m) { + passengers = p; + fuelcap = f; + mpg = m; + } + +} diff --git a/Chapter4c/VehicleDemo.java b/Chapter4c/VehicleDemo.java new file mode 100644 index 0000000..ce5a4a8 --- /dev/null +++ b/Chapter4c/VehicleDemo.java @@ -0,0 +1,26 @@ + + + +public class VehicleDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Vehicle minivan = new Vehicle(); + + int range; + + // assign values to fields in minivan. + minivan.passengers = 7; + minivan.fuelcap = 16; + minivan.mpg = 21; + + // compute the range assuming a full tank of gas. + range = minivan.fuelcap * minivan.mpg; + + System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range); + + + } + +} diff --git a/Chapter5/CLDemo2.java b/Chapter5/CLDemo2.java new file mode 100644 index 0000000..b5a09ab --- /dev/null +++ b/Chapter5/CLDemo2.java @@ -0,0 +1,15 @@ + +public class CLDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("There are " + args.length + " command-line arguments."); + + System.out.println("They are: "); + + for (int i = 0; i < args.length; i++) + System.out.println( "arg[" + i + "]: " + args[i] ); + } + +} diff --git a/Chapter5/Encode.java b/Chapter5/Encode.java new file mode 100644 index 0000000..c165c4d --- /dev/null +++ b/Chapter5/Encode.java @@ -0,0 +1,34 @@ +// Use XOR to encode and decode a message. +public class Encode { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String msg = "This is a test"; + String encmsgString = ""; + String decmsgString = ""; + + int key = 88; + + System.out.print("Original message: "); + System.out.println(msg); + + // encode the message + for (int i = 0; i < msg.length(); i++) + encmsgString = encmsgString + (msg.charAt(i) ^ key); // This constructs the encoded string. + + System.out.print("Encoded message: "); + System.out.println(encmsgString); + + // decode the message + for (int i = 0; i < msg.length(); i++) { + + decmsgString = decmsgString + (encmsgString.charAt(i) ^ key); // This construct the decoded string. + } + + System.out.print("Decoded message: "); + System.out.println(decmsgString); + + } + +} diff --git a/Chapter5/Encode2.java b/Chapter5/Encode2.java new file mode 100644 index 0000000..0f65f8c --- /dev/null +++ b/Chapter5/Encode2.java @@ -0,0 +1,33 @@ + +public class Encode2 { + + public static void main(String[] args) { + + String msg = "This is a test"; + String encmsgString = ""; + String decmsgString = ""; + + int key = 88; + + System.out.print("Original message: "); + System.out.println(msg); + + // encode the message + for (int i = 0; i < msg.length(); i++) + encmsgString = encmsgString + (char) (msg.charAt(i) ^ key); // This constructs the encoded string. + + System.out.print("Encoded message: "); + System.out.println(encmsgString); + + // decode the message + for (int i = 0; i < msg.length(); i++) { + + decmsgString = decmsgString + (char) (encmsgString.charAt(i) ^ key); // This construct the decoded string. + } + + System.out.print("Decoded message: "); + System.out.println(decmsgString); + + } + +} diff --git a/Chapter5/Get_a_column_in_2D_array.java b/Chapter5/Get_a_column_in_2D_array.java new file mode 100644 index 0000000..10ed11e --- /dev/null +++ b/Chapter5/Get_a_column_in_2D_array.java @@ -0,0 +1,28 @@ + +public class Get_a_column_in_2D_array { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + double data[][] = { + {2000, 1.5}, + {2001, 1.7}, + {2002, 3.6}, + {2001, 2.4}, + {2002, 2.9}, + {2003, 3.2} + }; + + // Accessing the first column. + for (int i = 0; i < data.length; i++) { + System.out.println(data[i][0]); + } + + // Accessing the second column. + for (int i = 0; i < data.length; i++) { + System.out.println(data[i][1]); + } + + } + +} diff --git a/Chapter5/LowCase.java b/Chapter5/LowCase.java new file mode 100644 index 0000000..889aa3f --- /dev/null +++ b/Chapter5/LowCase.java @@ -0,0 +1,35 @@ +// Lowercase letters. +public class LowCase { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + char ch; + for (int i = 0; i < 10; i++) { + + ch = (char) ('A' + i); + System.out.print(ch); + + // This statement turns on the 6th bit. + ch = (char) (ch | 32); // ch is now lowercase. + + /** Binary Octal-decimal Decimal Hexadecimal Glyph + * 100 0001 101 65 41 A + * 110 0001 141 97 61 a + * + * https://en.wikipedia.org/wiki/ASCII#Printable_characters + * + * + * 0000 0000 0100 0001 + * 0000 0000 0010 0000 or + * ----------------------- + * 0000 0000 0110 0001 + * + * */ + + System.out.print(ch + " "); + } + + } + +} diff --git a/Chapter5/Multi_dimensional_array_5.java b/Chapter5/Multi_dimensional_array_5.java new file mode 100644 index 0000000..544344e --- /dev/null +++ b/Chapter5/Multi_dimensional_array_5.java @@ -0,0 +1,26 @@ +import java.util.Scanner; + +public class Multi_dimensional_array_5 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int i, j, input; + int square[][] = { {1, 1}, {2, 4}, {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49}, {8, 56}, {9, 81}, {10, } }; + + System.out.println("Enter a number between 1 and 10 to see its square number: "); + Scanner readScanner = new Scanner(System.in); + input = readScanner.nextInt(); + + for(i= 0; i < 10 ; i++) + if(square[i][0] == input) break; + + // value of i is kept in the memory even when the for loop has been terminated. + System.out.println("The square of " + input + " is " + square[i][1]); + + // Note that the garbage collection in Java only applies to object. + // Reference: https://www.geeksforgeeks.org/garbage-collection-java/ + + } + +} diff --git a/Chapter5/NoZeroDiv.java b/Chapter5/NoZeroDiv.java new file mode 100644 index 0000000..551cfcc --- /dev/null +++ b/Chapter5/NoZeroDiv.java @@ -0,0 +1,19 @@ +// Prevent a division by zero using the ?. +public class NoZeroDiv { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int result; + + for (int i = -5; i < 6; i++) { + + result = i != 0 ? 100 / i : 0; // This prevents a divide-by-zero. + + if (i != 0) + System.out.println("100 / " + i + " is " + result); + } + + } + +} diff --git a/Chapter5/NoZeroDiv2.java b/Chapter5/NoZeroDiv2.java new file mode 100644 index 0000000..c13b87e --- /dev/null +++ b/Chapter5/NoZeroDiv2.java @@ -0,0 +1,19 @@ + +public class NoZeroDiv2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int result; + + for (int i = -5; i < 6; i++) { + + result = i != 0 ? 100 / i : 0; // This prevents a divide-by-zero. + + if (i != 0) + System.out.println("100 / " + i + " is " + result = ( i != 0) ? (100 / i ): ( 0) ;); + } + + } + +} diff --git a/Chapter5/NoZeroDiv3.java b/Chapter5/NoZeroDiv3.java new file mode 100644 index 0000000..52bcdc8 --- /dev/null +++ b/Chapter5/NoZeroDiv3.java @@ -0,0 +1,13 @@ +// Prevent a division by zero using the ?. +public class NoZeroDiv3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + for (int i = -5; i < 6 ; i++) + if (i != 0 ? true : false) + System.out.println("100 / " + i + " is " + 100 / i); + + } + +} diff --git a/Chapter5/NotDemo.java b/Chapter5/NotDemo.java new file mode 100644 index 0000000..47b5cf2 --- /dev/null +++ b/Chapter5/NotDemo.java @@ -0,0 +1,29 @@ +// Demonstrate the bitwise NOT. +public class NotDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + byte b = -34; + for (int t = 128; t > 0; t = t/2) { + if( (b & t) != 0) System.out.print("1 "); + else System.out.print("0 "); + } + + System.out.println(); + + // reverse all bits + b = (byte) -b; + + for (int t = 128; t > 0; t = t / 2) { + + if((b & t) != 0) System.out.print("1 "); + else System.out.print("0 "); + + } + + } + +} + +// See also: https://web.archive.org/web/20201112013328/https://web.stanford.edu/class/cs101/bits-bytes.html diff --git a/Chapter5/QDemo.java b/Chapter5/QDemo.java index fdc0c98..84bd414 100644 --- a/Chapter5/QDemo.java +++ b/Chapter5/QDemo.java @@ -21,7 +21,7 @@ void put(char ch) { return; } - q[putloc++] = ch; + q[putloc++] = ch; // the new element is stored at that location and putloc is increment. } diff --git a/Chapter5/Self_Test_Chapter5_No21.java b/Chapter5/Self_Test_Chapter5_No21.java new file mode 100644 index 0000000..55772fa --- /dev/null +++ b/Chapter5/Self_Test_Chapter5_No21.java @@ -0,0 +1,60 @@ + +class showBits4{ + + int numbits; + + public showBits4(int n) { + // TODO Auto-generated constructor stub + + numbits = n; + } + + void show(long val) { + + long value = 1; + + var mask = value; + + // left-shift a 1 into the proper position + mask <<= numbits-1; // mask = mask << numbits-1; + + int spacer = 0; + + for (; mask != 0; mask >>>= 1 ) { // mask = mask >>> 1; + + if( (val & mask) != 0) System.out.print("1"); + else System.out.print("0"); + spacer++; + if ((spacer & 8 ) == 0) { + System.out.print(" "); + spacer = 0; + } + } + System.out.println(); + } +} + +public class Self_Test_Chapter5_No21 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + showBits4 b = new showBits4(8); + showBits4 i = new showBits4(32); + showBits4 li = new showBits4(64); + System.out.println("123 in binary: "); + b.show(123); + + System.out.println("\n87987 in binary: "); + i.show(87987); + + System.out.println("\n237658768 in binary: "); + li.show(237658768); + + // you can also show low-order bits of any integer + System.out.println("\nLow order 8 bits of 87987 in binary: "); + b.show(87987); + + } + +} diff --git a/Chapter5/Self_Test_Chapter5_No6.java b/Chapter5/Self_Test_Chapter5_No6.java new file mode 100644 index 0000000..0e29749 --- /dev/null +++ b/Chapter5/Self_Test_Chapter5_No6.java @@ -0,0 +1,14 @@ + +public class Self_Test_Chapter5_No6 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String literalString = "I like Java"; + + System.out.println("The length of the string is " + literalString.length()); + System.out.print("The eighth character of the string is " + literalString.charAt(8)); + + } + +} diff --git a/Chapter5/Self_Test_Chapter5_No7.java b/Chapter5/Self_Test_Chapter5_No7.java new file mode 100644 index 0000000..e33ec14 --- /dev/null +++ b/Chapter5/Self_Test_Chapter5_No7.java @@ -0,0 +1,34 @@ + +public class Self_Test_Chapter5_No7 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String msg = "This is a test"; + String encmsgString = ""; + String decmsgString = ""; + + char[] key = {'8' , 's', 'c', 'r', 'i', 'p', 't', 's', '/', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 'i', 's', 't', 'i', 'c', 's'}; + + System.out.print("Original message: "); + System.out.println(msg); + + // encode the message + for (int i = 0; i < msg.length(); i++) + encmsgString = encmsgString + (char) (msg.charAt(i) ^ key[i]); // This constructs the encoded string. + + System.out.print("Encoded message: "); + System.out.println(encmsgString); + + // decode the message + for (int i = 0; i < msg.length(); i++) { + + decmsgString = decmsgString + (char) (encmsgString.charAt(i) ^ key[i]); // This construct the decoded string. + } + + System.out.print("Decoded message: "); + System.out.println(decmsgString); + + } + +} diff --git a/Chapter5/ShiftDemo.java b/Chapter5/ShiftDemo.java new file mode 100644 index 0000000..234be2f --- /dev/null +++ b/Chapter5/ShiftDemo.java @@ -0,0 +1,44 @@ +// Demonstrate the shift << and >> operators. +public class ShiftDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int val = 1; + + for (int i = 0; i < 8; i++) { + + for (int t = 128; t > 0; t = t / 2) { + + if ((val & t) != 0) + System.out.print("1 "); + else + System.out.print("0 "); + } + + System.out.println(); + val = val << 1; // left shift. + + } + + System.out.println(); + + val = 128; + for (int i = 0; i < 8; i++) { + + for (int t = 128; t > 0; t = t / 2) { + + if ((val & t) != 0) + System.out.print("1 "); + else + System.out.print("0 "); + } + + System.out.println(); + + val = val >> 1; // right shift. + } + + } + +} diff --git a/Chapter5/ShowBits.java b/Chapter5/ShowBits.java new file mode 100644 index 0000000..f4cb17d --- /dev/null +++ b/Chapter5/ShowBits.java @@ -0,0 +1,21 @@ +// Display the bits within a byte. +public class ShowBits { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int t; + + byte val; + + val = 123; + for (t = 128; t > 0; t = t/2) { + + if( (val & t) != 0) System.out.print("1 "); + else System.out.print("0 "); + + } + + } + +} diff --git a/Chapter5/ShowBits2.java b/Chapter5/ShowBits2.java new file mode 100644 index 0000000..95395cb --- /dev/null +++ b/Chapter5/ShowBits2.java @@ -0,0 +1,80 @@ + +public class ShowBits2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int t; + + byte val; + + val = 123; // Binary: 0111 1011 + for (t = 128; t > 0; t = t/2) { + + if( (val & t) != 0) System.out.print("1 "); + else System.out.print("0 "); + + + /* 128: + * + * 1000 0000 (128) + * 0111 1011 (123) & + * -------------------- + * 0000 0000 + * + * 64: + * + * 0100 0000 (64) + * 0111 1011 (123) & + * --------------------- + * 0100 0000 + * + * 32: + * + * 0010 0000 (32) + * 0111 1011 (123) & + * ---------------------- + * 0010 0000 + * + * 16: + * + * 0001 0000 (16) + * 0111 1011 (123) & + * -------------------- + * 0001 0000 + * + * 8: + * + * 0000 1000 (8) + * 0111 1011 (123) & + * ------------------- + * 0000 1000 + * + * 4: + * + * 0000 0100 (4) + * 0111 1011 (123) & + * ------------------- + * 0000 0000 + * + * 2: + * + * 0000 0010 (2) + * 0111 1011 (123) & + * ---------------------- + * 0000 0010 + * + * 1: + * + * 0000 0001 (1) + * 0111 1011 (123) & + * ---------------------- + * 0000 0001 + * + * */ + + } + + } + +} diff --git a/Chapter5/ShowBitsDemo.java b/Chapter5/ShowBitsDemo.java new file mode 100644 index 0000000..b4bcc5e --- /dev/null +++ b/Chapter5/ShowBitsDemo.java @@ -0,0 +1,63 @@ +/* Try this 5-3 + * + * A class that displays the binary representation of a value. + * + * */ +class ShowBits3{ + + int numbits; + + public ShowBits3(int n) { + // TODO Auto-generated constructor stub + + numbits = n; + } + + void show(long val) { + long mask = 1; + + // left-shift a 1 into the proper position + mask <<= numbits-1; // mask = mask << numbits-1; + + int spacer = 0; + + for (; mask != 0; mask >>>= 1 ) { // mask = mask >>> 1; + + if( (val & mask) != 0) System.out.print("1"); + else System.out.print("0"); + spacer++; + if ((spacer & 8 ) == 0) { + System.out.print(" "); + spacer = 0; + } + } + System.out.println(); + } +} + + +// Demonstrate ShowBits3. +public class ShowBitsDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ShowBits3 b = new ShowBits3(8); + ShowBits3 i = new ShowBits3(32); + ShowBits3 li = new ShowBits3(64); + System.out.println("123 in binary: "); + b.show(123); + + System.out.println("\n87987 in binary: "); + i.show(87987); + + System.out.println("\n237658768 in binary: "); + li.show(237658768); + + // you can also show low-order bits of any integer + System.out.println("\nLow order 8 bits of 87987 in binary: "); + b.show(87987); + + } + +} diff --git a/Chapter5/Try_This_5_1_2.java b/Chapter5/Try_This_5_1_2.java new file mode 100644 index 0000000..74114ee --- /dev/null +++ b/Chapter5/Try_This_5_1_2.java @@ -0,0 +1,35 @@ + +public class Try_This_5_1_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] nums = {99, -10, 100123, 18, -978, 5623, 463, -9, 287, 49}; + + System.out.print("Original array is: "); + + for (int i = 0; i < nums.length; i++) + System.out.print(" " + nums[i]); + System.out.println(); + + // This is the bubble sort. + for (int i = 0; i < nums.length; i++) { + for (int j = nums.length - 1; j > i ; j--) { + + if (nums[j-1] > nums[j]) { + int k = nums[j-1]; + nums[j-1] = nums[j]; + nums[j] = k; + } + } + } + + System.out.print("Sorted array is: "); + + for (int i = 0; i < nums.length; i++) { + System.out.print(" " + nums[i]); + } + + } + +} diff --git a/Chapter5/UpCase.java b/Chapter5/UpCase.java new file mode 100644 index 0000000..70fd907 --- /dev/null +++ b/Chapter5/UpCase.java @@ -0,0 +1,36 @@ +// Uppercase letters. +public class UpCase { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + char ch; + + for (int i = 0; i < 10; i++) { + + ch = (char) ('a' + i); + System.out.print(ch); + + // This statement turns off the 6th bit. + ch = (char) ( ch & 65503 ); // ch is now uppercase. + + /** Binary Oct Decimal Hexadecimal Glyph + * 100 0001 101 65 41 A + * 110 0001 141 97 61 a + * + * https://en.wikipedia.org/wiki/ASCII#Printable_characters + * + * + * 0000 0000 0110 0001 + * 1111 1111 1101 1111 & + * ----------------------- + * 0000 0000 0100 0001 + * + * */ + + System.out.print(ch + " "); + } + + } + +} \ No newline at end of file diff --git a/Chapter5/names.java b/Chapter5/names.java new file mode 100644 index 0000000..1de2a37 --- /dev/null +++ b/Chapter5/names.java @@ -0,0 +1,25 @@ +import java.util.Scanner; + +// Implement it in Java for Python > How to code in Python 3 > Chapter33 - Functions > names.py +public class names { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + static void names() { + + String nameString; + + Scanner myobj = new Scanner(System.in); + + System.out.println("Enter your name: "); + + nameString = myobj.next(); + + + + } + +} diff --git a/Chapter6/AccessDemo2.java b/Chapter6/AccessDemo2.java new file mode 100644 index 0000000..0b7ed63 --- /dev/null +++ b/Chapter6/AccessDemo2.java @@ -0,0 +1,32 @@ + +class MyClass2{ + private static int alpha; + public static int beta; + static int gamma; + + static int delta = 1; + +// alpha = delta; + + public static void setAlpha(int alpha) { + MyClass2.alpha = alpha; + } + + public static int getAlpha() { + return alpha; + } +} + +public class AccessDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println(MyClass2.delta); + System.out.println(MyClass2.beta); + System.out.println(MyClass2.getAlpha()); +// System.out.println(MyClass2.alpha); + + } + +} diff --git a/Chapter6/AccessExperiment.java b/Chapter6/AccessExperiment.java new file mode 100644 index 0000000..762684b --- /dev/null +++ b/Chapter6/AccessExperiment.java @@ -0,0 +1,28 @@ + +public class AccessExperiment { + + private int alpha; // private access + public int beta; // public access + int gamma; // default access + + /* Methods to access alpha. It is OK for a member of a class to access a private member of the same class.*/ + void setAlpha(int a) { + alpha = a; + } + + int getAlpha() { + return alpha; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + AccessExperiment exploitationAccessExperiment = new AccessExperiment(); + + exploitationAccessExperiment.alpha = 10; + + System.out.println("exploitation.alpha is " + exploitationAccessExperiment.getAlpha()); + + } + +} diff --git a/Chapter6/Block.java b/Chapter6/Block.java new file mode 100644 index 0000000..2459886 --- /dev/null +++ b/Chapter6/Block.java @@ -0,0 +1,31 @@ +// Objects can be passed to methods. +public class Block { + + int a, b, c; + + int volume; + + Block(int i, int j, int k) { + a = i; + b = j; + c = k; + + volume = a * b * c; + } + + // Return true if ob defines same block. + boolean sameBlock(Block ob) { // Use object type for parameter. + if ((ob.a == a) & (ob.b == b) & (ob.c == c)) + return true; + + return false; + } + + // Return true if ob has same volume. + boolean sameVolume(Block ob) { // Use object type for parameter. + if (ob.volume == volume) + return true; + return false; + } + +} diff --git a/Chapter6/CallByValue.java b/Chapter6/CallByValue.java new file mode 100644 index 0000000..debc2ff --- /dev/null +++ b/Chapter6/CallByValue.java @@ -0,0 +1,29 @@ +// Primitive types are passed by value. + +class Test{ + // This method causes no change to the arguments used in the call. + + void noChange(int i, int j) { + i = i + j; + j = - j ; + } +} + + +public class CallByValue { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Test obTest = new Test(); + + int a = 15, b = 20; + System.out.println("a and b before call: " + a + " " + b); + + obTest.noChange(a, b); + + System.out.println("a and b after call: " + a + " " + b); + + } + +} diff --git a/Chapter6/ErrInfo.java b/Chapter6/ErrInfo.java new file mode 100644 index 0000000..245b6a5 --- /dev/null +++ b/Chapter6/ErrInfo.java @@ -0,0 +1,42 @@ +// Return a programmer-defined object. +class Err { + + String msgString; // error message + int severity; // code indicating severity of error. + + public Err(String m, int s) { + msgString = m; + severity = s; + } +} + +class ErrorInfo{ + String msgs[] = {"Output Error", "Input Error", "Disk Full", "Index Out-of-Bounds"}; + + int howbad[] = {3, 3, 2, 4}; + + Err getErrorInfo(int i) { // Return an object of type Err. + if(i >= 0 & i < msgs.length ) + return new Err(msgs[i], howbad[i]); + else + return new Err("Invalid Error Code", 0); + } +} + +public class ErrInfo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ErrorInfo errorInfo = new ErrorInfo(); + Err e; + + e = errorInfo.getErrorInfo(2); + System.out.println(e.msgString + " severity: " + e.severity); + + e = errorInfo.getErrorInfo(19); + System.out.println(e.msgString + " severity: " + e.severity); + + } + +} diff --git a/Chapter6/ErrorMessage.java b/Chapter6/ErrorMessage.java new file mode 100644 index 0000000..96a08e5 --- /dev/null +++ b/Chapter6/ErrorMessage.java @@ -0,0 +1,26 @@ +// Return a String object. +class ErrorMsg{ + + String msgs[] = {"Output Error", "Input Error", "Disk Full", "Index Out-Of-Bounds"}; + + // Return the error message. + String getErrorMsg(int i) { + if(i >= 0 & i < msgs.length) + return msgs[i]; + return "Invalid Error Code"; + } +} + + +public class ErrorMessage { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ErrorMsg err = new ErrorMsg(); + System.out.println(err.getErrorMsg(2)); + System.out.println(err.getErrorMsg(19)); + + } + +} diff --git a/Chapter6/ErrorMessage2.java b/Chapter6/ErrorMessage2.java new file mode 100644 index 0000000..39febf0 --- /dev/null +++ b/Chapter6/ErrorMessage2.java @@ -0,0 +1,17 @@ + +class ErrorMsg2 { + String messages[] = {"Output Error", "Input Error", "Disk Full", "Index Out-Of-Bounds"}; +} + +public class ErrorMessage2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ErrorMsg2 errorMsg2 = new ErrorMsg2(); + System.out.println(errorMsg2.messages[1]); + System.out.println(errorMsg2.messages[4]); + + } + +} diff --git a/Chapter6/FSDemo.java b/Chapter6/FSDemo.java new file mode 100644 index 0000000..ad99130 --- /dev/null +++ b/Chapter6/FSDemo.java @@ -0,0 +1,44 @@ + +// Demonstrate the fail-soft array. +class FSDemo { + + public static void main(String arg[]) { + + FailSoftArray fsFailSoftArray = new FailSoftArray(5, -1); + int x; + + // show quiet failure + System.out.println("Fail quietly."); + for (int i = 0; i < (fsFailSoftArray.length * 2); i++) + fsFailSoftArray.put(i, i * 10); // Access to array must be through its accessor methods. + + for (int i = 0; i < (fsFailSoftArray.length * 2); i++) { + + x = fsFailSoftArray.get(i); // Access to array must be through its accessor methods. + + if (x != -1) + System.out.print(x + " "); + + } + + System.out.println(""); + + // now, handle failures + System.out.println("\nFail with error reports."); + + for (int i = 0; i < (fsFailSoftArray.length * 2); i++) + + if (!fsFailSoftArray.put(i, i * 10)) + System.out.println("Index " + i + " out-of-bounds"); + + for (int i = 0; i < (fsFailSoftArray.length * 2); i++) { + x = fsFailSoftArray.get(i); + if (x != -1) + System.out.print(x + " "); + else + System.out.println("Index " + i + " out-of-bounds"); + } + + } + +} diff --git a/Chapter6/FSDemo2.java b/Chapter6/FSDemo2.java new file mode 100644 index 0000000..923700f --- /dev/null +++ b/Chapter6/FSDemo2.java @@ -0,0 +1,43 @@ + +public class FSDemo2 { + + public static void main(String[] args) { + + FailSoftArray2 fsFailSoftArray2 = new FailSoftArray2(5, -1); + int x; + + // show quiet failure + System.out.println("Fail quietly."); + for (int i = 0; i < (fsFailSoftArray2.length * 2); i++) + fsFailSoftArray2.put(i, i * 10); // Need not the method's caller declare a variable to hold the value returned by the method? + + for (int i = 0; i < (fsFailSoftArray2.length * 2); i++) { + + x = fsFailSoftArray2.get(i); + + if (x != -1) + System.out.print(x + " "); + + } + + System.out.println(""); + + // now, handle failures + System.out.println("\nFail with error reports."); + + for (int i = 0; i < (fsFailSoftArray2.length * 2); i++) + +// if (!fsFailSoftArray2.put(i, i * 10)) + System.out.println("Index " + i + " out-of-bounds"); + + for (int i = 0; i < (fsFailSoftArray2.length * 2); i++) { + x = fsFailSoftArray2.get(i); + if (x != -1) + System.out.print(x + " "); + else + System.out.println("Index " + i + " out-of-bounds"); + } + + } + +} diff --git a/Chapter6/FSDemo_experiment.java b/Chapter6/FSDemo_experiment.java new file mode 100644 index 0000000..0e53bd2 --- /dev/null +++ b/Chapter6/FSDemo_experiment.java @@ -0,0 +1,20 @@ + +public class FSDemo_experiment { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + FailSoftArray failSoftArray = new FailSoftArray(12, -1); + + System.out.println(failSoftArray.get(4)); + + int b[] = new int[12]; + System.out.println(b[4]); + + failSoftArray.put(18, 6); + + System.out.println(failSoftArray.get(18)); + + } + +} diff --git a/Chapter6/Factorial_by_recursion.java b/Chapter6/Factorial_by_recursion.java new file mode 100644 index 0000000..5b3ce01 --- /dev/null +++ b/Chapter6/Factorial_by_recursion.java @@ -0,0 +1,32 @@ +import java.util.Scanner; + +public class Factorial_by_recursion { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int input; + + System.out.println("Enter the number to count its factorial: "); + + Scanner readScanner = new Scanner(System.in); + input = readScanner.nextInt(); + readScanner.close(); + + System.out.println("Your input is " + input); + + System.out.println("The factorial of " + input + " is " + factR(input) + ", using recursive function."); + + } + + static int factR(int n){ + int result; + + if(n == 1) return 1; + + // Execute the recursive call to factR(). + result = factR(n-1) * n; // The factorial of a number n is n*n-1 *n-2*... *1. + return result; + } + +} diff --git a/Chapter6/Factorial_by_recursion2.java b/Chapter6/Factorial_by_recursion2.java new file mode 100644 index 0000000..f20376e --- /dev/null +++ b/Chapter6/Factorial_by_recursion2.java @@ -0,0 +1,32 @@ +import java.util.Scanner; + +public class Factorial_by_recursion2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + int input, result; + + System.out.println("Enter the number to count its factorial: "); + + Scanner readScanner = new Scanner(System.in); + input = readScanner.nextInt(); + readScanner.close(); + + System.out.println("Your input is " + input); + + result = factR(input); + + System.out.println("The factorial of " + input + " is " + result + ", using recursive function."); + } + + static int factR(int n){ + int result; + + if(n == 1) return 1; + + // Execute the recursive call to factR(). + result = factR(n-1) * n; // The factorial of a number n is n*n-1 *n-2*... *1. + return result; + } + +} diff --git a/Chapter6/Factorial_by_recursion3.java b/Chapter6/Factorial_by_recursion3.java new file mode 100644 index 0000000..01cc4cc --- /dev/null +++ b/Chapter6/Factorial_by_recursion3.java @@ -0,0 +1,35 @@ +import java.util.Scanner; + +public class Factorial_by_recursion3 { + + public static void main(String[] args) { + + int input, result; + + System.out.println("Enter the number to count its factorial: "); + + Scanner readScanner = new Scanner(System.in); + input = readScanner.nextInt(); + readScanner.close(); + + System.out.println("Your input is " + input); + + result = factR(input); + + System.out.println("The factorial of " + input + " is " + result + ", using recursive function."); + + } + + static int factR(int n){ + int intermediate_goods, result; + + if(n == 1) return 1; + + // Execute the recursive call to factR(). + intermediate_goods = factR(n-1) ; // The factorial of a number n is n*n-1 *n-2*... *1. + + result = intermediate_goods * n; + + return result; + } +} diff --git a/Chapter6/Factorial_by_recursion_without_if.java b/Chapter6/Factorial_by_recursion_without_if.java new file mode 100644 index 0000000..c6a2380 --- /dev/null +++ b/Chapter6/Factorial_by_recursion_without_if.java @@ -0,0 +1,33 @@ +import java.util.Scanner; + +public class Factorial_by_recursion_without_if { + + public static void main(String[] args) { + // TODO Auto-generated method stub + int input, result; + + System.out.println("Enter the number to count its factorial: "); + + Scanner readScanner = new Scanner(System.in); + input = readScanner.nextInt(); + readScanner.close(); + + System.out.println("Your input is " + input); + + result = factR(input); + + System.out.println("The factorial of " + input + " is " + result + ", using recursive function."); + } + + static int factR(int n){ + int intermediate_goods, result; + + // Execute the recursive call to factR(). + intermediate_goods = factR(n-1) ; // The factorial of a number n is n*n-1 *n-2*... *1. + + result = intermediate_goods * n; + + return result; + } + +} diff --git a/Chapter6/FailSoftArray.java b/Chapter6/FailSoftArray.java index 788a41c..3361b56 100644 --- a/Chapter6/FailSoftArray.java +++ b/Chapter6/FailSoftArray.java @@ -1,42 +1,50 @@ // This class implements a "fail-soft" array which prevents runtime errors. public class FailSoftArray { - - private int a[] ; // reference to array - private int errval; // value to return if get() fails. - public int length; // length is public - - // Construct array given its size and the value to return if get() fails. + + private int a[]; // reference to array + private int errval; // value to return if get() fails. + public int length; // length is public + + // Construct array given its size and the value to return if get() fails. public FailSoftArray(int size, int errv) { - + a = new int[size]; errval = errv; length = size; - + } - + // Return value at given index. public int get(int index) { - - if(indexOK(index)) return a[index]; // Trap on out-of-bounds index. - + + if (indexOK(index)) + return a[index]; // Trap on out-of-bounds index. + return errval; } - - // Put a value at an index. Return false on failure. - public boolean put(int index, int val) { - if(indexOK(index)) { // Trap on out-of-bounds index. + + // Put a value at an index. Return false on failure. + public boolean put(int index, int val) { + + if (indexOK(index)) { // Trap on out-of-bounds index. + a[index] = val; + return true; } - + return false; } - - // Return true if index is within bounds. + + // Return true if index is within bounds. private boolean indexOK(int index) { - if(index >= 0 & index < length) return true; - + + if (index >= 0 & index < length) + return true; + return false; } } + + diff --git a/Chapter6/FailSoftArray2.java b/Chapter6/FailSoftArray2.java new file mode 100644 index 0000000..2ce835a --- /dev/null +++ b/Chapter6/FailSoftArray2.java @@ -0,0 +1,47 @@ + +public class FailSoftArray2 { + + private int a[]; // reference to array + private int errval; // value to return if get() fails. + public int length; // length is public + + // Construct array given its size and the value to return if get() fails. + public FailSoftArray2(int size, int errv) { + + a = new int[size]; + errval = errv; + length = size; + + } + + // Return value at given index. + public int get(int index) { + + if (indexOK(index)) + return a[index]; // Trap on out-of-bounds index. + + return errval; + } + + // Put a value at an index. Return false on failure. + public int put(int index, int val) { + + if (indexOK(index)) { // Trap on out-of-bounds index. + + a[index] = val; + + return 1; + } + + return -1; + } + + // Return true if index is within bounds. + private boolean indexOK(int index) { + + if (index >= 0 & index < length) + return true; + + return false; + } +} diff --git a/Chapter6/LocalClassDemo.java b/Chapter6/LocalClassDemo.java new file mode 100644 index 0000000..2bfccc6 --- /dev/null +++ b/Chapter6/LocalClassDemo.java @@ -0,0 +1,50 @@ + +public class LocalClassDemo { + + public static void main(String[] args) { + + // An inner class version of ShowBits + class ShowBits4 { // A local class nested within a method. + + int numbits; + + public ShowBits4(int n) { + // TODO Auto-generated constructor stub + + numbits = n; + } + + void show(long val) { + long mask = 1; + + // left-shift a 1 into the proper position + mask <<= numbits - 1; // mask = mask << numbits-1; + + int spacer = 0; + + for (; mask != 0; mask >>>= 1) { // mask = mask >>> 1; + + if ((val & mask) != 0) + System.out.print("1"); + else + System.out.print("0"); + spacer++; + if ((spacer & 8) == 0) { + System.out.print(" "); + spacer = 0; + } + } + System.out.println(); + } + } + + for (byte b = 0; b < 10; b++) { + + ShowBits4 byteval = new ShowBits4(8); + System.out.print(b + " in binary: "); + byteval.show(b); + } + + } + +} diff --git a/Chapter6/LocalClassDemo2.java b/Chapter6/LocalClassDemo2.java new file mode 100644 index 0000000..a859099 --- /dev/null +++ b/Chapter6/LocalClassDemo2.java @@ -0,0 +1,12 @@ + +public class LocalClassDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + LocalClassDemo objectClass = new LocalClassDemo(); + objectClass.main(null).; + + } + +} diff --git a/Chapter6/NestedClassDemo.java b/Chapter6/NestedClassDemo.java new file mode 100644 index 0000000..a21fc08 --- /dev/null +++ b/Chapter6/NestedClassDemo.java @@ -0,0 +1,13 @@ + +public class NestedClassDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int x[] = { 3, 2, 1, 5, 6, 9, 7, 8 }; + Outer outOb = new Outer(x); + + outOb.analyze(); + } + +} diff --git a/Chapter6/Outer.java b/Chapter6/Outer.java new file mode 100644 index 0000000..aefb6f1 --- /dev/null +++ b/Chapter6/Outer.java @@ -0,0 +1,49 @@ + +// Use an inner class. +public class Outer { + + int nums[]; + + public Outer(int n[]) { + // TODO Auto-generated constructor stub + nums = n; + } + + void analyze() { + Inner inOb = new Inner(); + + System.out.println("Minimum: " + inOb.min()); + System.out.println("Maximum: " + inOb.max()); + System.out.println("Average: " + inOb.avg()); + } + + // This is an inner class. + class Inner { + + int min() { + int m = nums[0]; + + for (int i = 1; i < nums.length; i++) + if (nums[i] < m) + m = nums[i]; + return m; + } + + int max() { + int m = nums[0]; + for (int i = 1; i < nums.length; i++) + if (nums[i] > m) + m = nums[i]; + + return m; + } + + int avg() { + int a = 0; + for (int i = 0; i < nums.length; i++) + a += nums[i]; + + return a / nums.length; + } + } +} diff --git a/Chapter6/Outer2.java b/Chapter6/Outer2.java new file mode 100644 index 0000000..cf5a27d --- /dev/null +++ b/Chapter6/Outer2.java @@ -0,0 +1,49 @@ + +public class Outer2 { + + int nums[]; + + public Outer2(int n[]) { + // TODO Auto-generated constructor stub + nums = n; + } + + void analyze() { + Inner inOb = new Inner(); + + System.out.println("Minimum: " + inOb.min()); + System.out.println("Maximum: " + inOb.max()); + System.out.println("Average: " + inOb.avg()); + } + + // This is an inner class. + class Inner { + + int min() { + int m = Outer2.nums[0]; // This is senseless because Outer2{} is already the parent of Inner{}. + + for (int i = 1; i < nums.length; i++) + if (nums[i] < m) + m = nums[i]; + return m; + } + + int max() { + int m = nums[0]; + for (int i = 1; i < nums.length; i++) + if (nums[i] > m) + m = nums[i]; + + return m; + } + + int avg() { + int a = 0; + for (int i = 0; i < nums.length; i++) + a += nums[i]; + + return a / nums.length; + } + } + +} diff --git a/Chapter6/OverloadConsDemo.java b/Chapter6/OverloadConsDemo.java new file mode 100644 index 0000000..bc5489a --- /dev/null +++ b/Chapter6/OverloadConsDemo.java @@ -0,0 +1,53 @@ +// Demonstrate an overloaded constructor. + +class MyClass5 { + + int x; + + public MyClass5() { + // TODO Auto-generated constructor stub + + System.out.println("Inside MyClass()."); + x = 0; + } + + MyClass5(int i) { + + System.out.println("Inside MyClass(int). "); + + x = i; + } + + MyClass5(double d) { + + System.out.println("Inside MyClass(double). "); + + x = (int) d; + } + + MyClass5(int i, int j) { + + System.out.println("Inside MyClass(int, int). "); + + x = i * j; + } +} + +public class OverloadConsDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + MyClass5 t1 = new MyClass5(); + MyClass5 t2 = new MyClass5(88); + MyClass5 t3 = new MyClass5(17.23); + MyClass5 t4 = new MyClass5(2, 4); + + System.out.println("t1.x: " + t1.x); + System.out.println("t2.x: " + t2.x); + System.out.println("t3.x: " + t3.x); + System.out.println("t4.x: " + t4.x); + + } + +} diff --git a/Chapter6/OverloadDemo.java b/Chapter6/OverloadDemo.java new file mode 100644 index 0000000..623cb4d --- /dev/null +++ b/Chapter6/OverloadDemo.java @@ -0,0 +1,62 @@ +// Demonstrate method overloading +class Overload{ + + void ovlDemo() { // First version + System.out.println("No parameter"); + } + + // Overload ovlDemo for one integer parameter. + void ovlDemo(int a) { // Second version + System.out.println("One parameter: " + a); + } + + // Overload ovlDemo for two integer parameters. + int ovlDemo(int a, int b) { // third version + + System.out.println("Two parameters: " + a + " " + b); + + return a+b; + + } + + // Overload ovlDemo for two double parameters. + double ovlDemo(double a, double b) { // Fourth version + + System.out.println("Two double parameters: " + a + " " + b); + + return a + b; + + } +} + +public class OverloadDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Overload obOverload = new Overload(); + int resI; + double resD; + + // Call all versions of ovlDemo() + obOverload.ovlDemo(); + + System.out.println(); + + obOverload.ovlDemo(2); + + System.out.println(); + + resI = obOverload.ovlDemo(4, 6); + + System.out.println("Result of obOverload.ovlDemo(4, 6): " + resI); + + System.out.println(); + + resD = obOverload.ovlDemo(1.1, 2.32); + + System.out.println("Result of ob.ovlDemo(1.1, 2.32): " + resD); + + } + +} diff --git a/Chapter6/PassOb.java b/Chapter6/PassOb.java new file mode 100644 index 0000000..1013206 --- /dev/null +++ b/Chapter6/PassOb.java @@ -0,0 +1,22 @@ + +public class PassOb { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Block ob1 = new Block(10, 2, 5); + Block ob2 = new Block(10, 2, 5); + Block ob3 = new Block(4, 5, 5); + + if (ob1 == ob2) + System.out.println("ob1 and ob2 share the same object."); + else + System.out.println("ob 1 and ob2 are different despite having the same properties."); + + System.out.println("ob1 has same dimensions as ob2: " + ob1.sameBlock(ob2)); // Pass an object. + System.out.println("ob1 has same dimensions as ob3: " + ob1.sameBlock(ob3)); // Pass an object. + System.out.println("ob1 has same volume as ob3: " + ob1.sameVolume(ob3)); // Pass an object. + + } + +} diff --git a/Chapter6/PassOb2.java b/Chapter6/PassOb2.java new file mode 100644 index 0000000..fdb6c4f --- /dev/null +++ b/Chapter6/PassOb2.java @@ -0,0 +1,22 @@ + +public class PassOb2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Block ob1 = new Block(10, 2, 5); + Block ob2 = new Block(10, 2, 5); + Block ob3 = new Block(4, 5, 5); + + if (ob1 == ob2) // Check their memory addresses for equivalence. + System.out.println("ob1 and ob2 share the same object."); + else + System.out.println("ob 1 and ob2 are different despite having the same properties."); + + System.out.println("ob1 has same dimensions as ob2: " + ob1.sameBlock(ob2)); // Pass an object. + System.out.println("ob1 has same dimensions as ob3: " + ob1.sameBlock(ob3)); // Pass an object. + System.out.println("ob1 has same volume as ob3: " + ob1.sameVolume(ob3)); // Pass an object. + + } + +} diff --git a/Chapter6/PassOb3.java b/Chapter6/PassOb3.java new file mode 100644 index 0000000..322f045 --- /dev/null +++ b/Chapter6/PassOb3.java @@ -0,0 +1,17 @@ + +public class PassOb3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Block ob1 = new Block(10, 2, 5); + Block ob2 = new Block(10, 2, 5); + Block ob3 = new Block(4, 5, 5); + + System.out.println("ob1 has same dimensions as ob2: " + ob1.sameBlock(ob2)); // Pass an object. + System.out.println("ob1 has same dimensions as ob3: " + ob1.sameBlock(ob3)); // Pass an object. + System.out.println("ob1 has same volume as ob3: " + ob1.sameVolume(ob3)); // Pass an object. + + } + +} diff --git a/Chapter6/PassObRef.java b/Chapter6/PassObRef.java new file mode 100644 index 0000000..71466b5 --- /dev/null +++ b/Chapter6/PassObRef.java @@ -0,0 +1,37 @@ +// Objects are passed through their references. +class Test2{ + int a, b ; + + public Test2(int i, int j) { + // TODO Auto-generated constructor stub + + a = i; + b = j; + + } + + // Pass an object. Now, ob.a and ob.b in object used in the call will be changed. + + void change(Test2 ob) { + ob.a = ob.a + ob.b; + ob.b = -(ob.b); + } +} + + +public class PassObRef { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Test2 ob = new Test2(15, 20); + + System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b) ; + + ob.change(ob); + + System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); + + } + +} diff --git a/Chapter6/QDemo2.java b/Chapter6/QDemo2.java new file mode 100644 index 0000000..5468ac7 --- /dev/null +++ b/Chapter6/QDemo2.java @@ -0,0 +1,120 @@ + +class Queue3 { + + private char q[]; // this array holds the queue input + + private int putloc, getloc; // the put and get indices + + public Queue3(int size) { + + q = new char[size]; // allocate memory for queue. + putloc = getloc = 0; // the put and get indices (plural of index) are initially set to zero. + + } + + // Construct a Queue3 from a Queue3 + Queue3(Queue3 ob){ + + putloc = ob.putloc; + + getloc = ob.getloc; + + q = new char[ob.q.length]; + + // copy elements + for(int i = getloc; i < putloc; i++) + q[i] = ob.q[i]; + } + + // Construct a Queue with initial values. + public Queue3(char a[]) { + + putloc = 0; + getloc = 0; + q = new char[a.length]; + + for (int i = 0; i < a.length ; i++) put(a[i]); + } + + // The put() method, which stores elements. + // put a character into the queue. + void put(char ch) { + + if (putloc == q.length) { + System.out.println(" - Queue is full. "); + return; + } + + q[putloc++] = ch; // the new element is stored at that location and putloc is increment. + + } + + char get() { + + if (getloc == putloc) { + System.out.println(" - Queue is empty. "); + return (char) 0; + } + + return q[getloc++]; // Note the difference between ++getloc and getloc++. + // After the next element is returned, getloc is incremented. + // Thus, getloc always indicates the location of the next element to be + // retrieved. + } +} + +// Demonstrate the Queue class. +public class QDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + // Construct 10-element empty queue + Queue3 q1 = new Queue3(10); + + char name[] = {'T', 'o', 'm'}; + + // construct queue from array + Queue3 q2 = new Queue3(name); + + char ch; + int i; + + // put some characters into q1 + for(i = 0 ; i < 10 ; i++) + q1.put( (char) ('A' + i) ); + + // Construct queue from another queue + Queue3 queue3 = new Queue3(q1); + + // Show the queue + System.out.print("Contents of q1: "); + for (i = 0; i < 10; i++) { + + ch = q1.get(); + + System.out.print(ch); + + } + + System.out.println("\n"); + + System.out.print("Contents of q2: "); + for ( i = 0; i < 3; i++) { + ch = q2.get(); + System.out.print(ch); + } + + System.out.println("\n"); + + System.out.print("Contents of q3: "); + for (i = 0; i < 10; i++) { + + ch = queue3.get(); + System.out.print(ch); + + } + + } + +} diff --git a/Chapter6/QSDemo.java b/Chapter6/QSDemo.java new file mode 100644 index 0000000..a80f2d3 --- /dev/null +++ b/Chapter6/QSDemo.java @@ -0,0 +1,25 @@ + +public class QSDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + char a[] = {'d', 'x', 'a', 'r', 'p', 'j', 'i'}; + int i; + + System.out.println("Original array: "); + for(i = 0 ; i < a.length; i++) + System.out.print(a[i]); + + System.out.println(); + + // now, sort the array + QuickSort.qsort(a); + + System.out.println("Sorted array: "); + for(i= 0; i < a.length; i++) + System.out.print(a[i]); + + } + +} diff --git a/Chapter6/Queue2.java b/Chapter6/Queue2.java new file mode 100644 index 0000000..d3c19c9 --- /dev/null +++ b/Chapter6/Queue2.java @@ -0,0 +1,40 @@ + +public class Queue2 { + + private char q[]; // this array holds the queue input + + private int putloc, getloc; // the put and get indices + + public Queue2(int size) { + + q = new char[size]; // allocate memory for queue. + putloc = getloc = 0; // the put and get indices (plural of index) are initially set to zero. + + } + + // The put() method, which stores elements. + // put a character into the queue. + void put(char ch) { + + if (putloc == q.length) { + System.out.println(" - Queue is full. "); + return; + } + + q[putloc++] = ch; + + } + + char get() { + + if (getloc == putloc) { + System.out.println(" - Queue is empty. "); + return (char) 0; + } + + return q[getloc++]; // Note the difference between ++getloc and getloc++. + // the next element is returned. In this process, getloc is incremented. + // Thus, getloc always indicates the location of the next element to be + // retrieved. + } +} diff --git a/Chapter6/QuickSort.java b/Chapter6/QuickSort.java new file mode 100644 index 0000000..549fba8 --- /dev/null +++ b/Chapter6/QuickSort.java @@ -0,0 +1,33 @@ +// Try This 6-3: A simple version of the Quicksort. +public class QuickSort { + + // Set up a call to the actual Quicksort method. + static void qsort(char items[]) { + qs(items, 0, items.length-1); + } + + // A recursive version of Quicksort for characters. + private static void qs(char items[], int left, int right) { + int i, j; + char x, y; + + i = left; j = right; + x = items[(left + right) / 2]; + + do { + while( (items[i] < x) && (i < right) ) i++; + while( (x < items[j]) && (j > left) ) j--; + + if (i <= j) { + y = items[i]; + items[i] = items[j]; + items[j] = y; + i++; j--; + } + + } while (i <= j); + + if(left < j) qs(items, left, 1); + if(i < right) qs(items, i, right); + } +} diff --git a/Chapter6/Recursion.java b/Chapter6/Recursion.java new file mode 100644 index 0000000..c415288 --- /dev/null +++ b/Chapter6/Recursion.java @@ -0,0 +1,47 @@ +// A single example of recursion. + +class Factorial { // The factorial of five (5 x 4 x 3 x 2 x 1) is 120. Four factorial (4 x 3 x 2 x 1) is 24. + + // This is a recursive function. + int factR(int n){ + int result; + + if(n == 1) return 1; + + // Execute the recursive call to factR(). + result = factR(n-1) * n; // The factorial of a number n is n*n-1 *n-2*... *1. + return result; + } + + // This is an iterative equivalent. + int factI(int n) { + int t, result; + + result = 1; + for(t = 1 ; t <= n ; t++) result *= t ; + return result; + } +} + +public class Recursion { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Factorial factorial = new Factorial(); + + System.out.println("Factorials using recursive method."); + System.out.println("Factorial of 3 is " + factorial.factR(3)); + System.out.println("Factorial of 4 is " + factorial.factR(4)); + System.out.println("Factorial of 5 is " + factorial.factR(5)); + System.out.println(); + + System.out.println("Factorials using iterative method."); + System.out.println("Factorial of 3 is " + factorial.factI(3)); + System.out.println("Factorial of 4 is " + factorial.factI(4)); + System.out.println("Factorial of 5 is " + factorial.factI(5)); + + + } + +} diff --git a/Chapter6/Recursion2.java b/Chapter6/Recursion2.java new file mode 100644 index 0000000..a058ef6 --- /dev/null +++ b/Chapter6/Recursion2.java @@ -0,0 +1,52 @@ +import java.io.IOException; + +class Factorial2 { // The factorial of five (5 x 4 x 3 x 2 x 1) is 120. Four factorial (4 x 3 x 2 x 1) is 24. + + // This is a recursive function. + int factR(int n){ + int result; + + if(n == 1) return 1; + + // Execute the recursive call to factR(). + result = factR(n-1) * n; // The factorial of a number n is n*n-1 *n-2*... *1. + return result; + } + + // This is an iterative equivalent. + int factI(int n) { + int t, result; + + result = 1; + for(t = 1 ; t <= n ; t++) result *= t ; + return result; + } +} + +public class Recursion2 { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + + int i, result, result2; + char input; + + System.out.println("Enter the number to count its factorial: "); + i = System.in.read(); // why I type '9', but it returns 57 ? See: https://stackoverflow.com/a/34120618/14900011 + + System.out.println("Your input is " + i); + + Factorial2 factorial2 = new Factorial2(); + + result = factorial2.factR(i); + result2 = factorial2.factI(i); + + System.out.println("The factorial of " + i + " is " + result + " , using recursive function."); + System.out.println("The factorial of " + i + " is " + result2 + " , using iterative function."); + + System.out.println(factorial2.factR(51)); + System.out.println(factorial2.factR(5)); + + } + +} diff --git a/Chapter6/Recursion3.java b/Chapter6/Recursion3.java new file mode 100644 index 0000000..671e722 --- /dev/null +++ b/Chapter6/Recursion3.java @@ -0,0 +1,51 @@ +import java.util.Scanner; + +class Factorial3 { // The factorial of five (5 x 4 x 3 x 2 x 1) is 120. Four factorial (4 x 3 x 2 x 1) is 24. + + // This is a recursive function. + int factR(int n){ + int result; + + if(n == 1) return 1; + + // Execute the recursive call to factR(). + result = factR(n-1) * n; // The factorial of a number n is n*n-1 *n-2*... *1. + return result; + } + + // This is an iterative equivalent. + int factI(int n) { + int t, result; + + result = 1; + for(t = 1 ; t <= n ; t++) + result *= t ; + return result; + } +} + +public class Recursion3 { + + public static void main(String[] args) { + + int input, result, result2; + + System.out.println("Enter the number to count its factorial: "); + + Scanner readScanner = new Scanner(System.in); + input = readScanner.nextInt(); + readScanner.close(); + + System.out.println("Your input is " + input); + + Factorial3 factorial3 = new Factorial3(); + result = factorial3.factR(input); + + System.out.println("The factorial of " + input + " is " + result + " , using recursive function."); + + result = factorial3.factI(input); + System.out.println("The factorial of " + input + " is " + result + " , using iterative function."); + + } + +} diff --git a/Chapter6/SDemo.java b/Chapter6/SDemo.java new file mode 100644 index 0000000..d5c5f1e --- /dev/null +++ b/Chapter6/SDemo.java @@ -0,0 +1,57 @@ +// Use a static variable +class StaticDemo{ + + int x; // a normal instance variable. + static int y; // A static variable. There is one copy of y for all objects to share. + + // Return the sum of the instance variable x and the static variable y. + int sum() { + return x + y; + } +} + + +public class SDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + StaticDemo ob1 = new StaticDemo(); + StaticDemo ob2 = new StaticDemo(); + + // Each object has its own copy of an instance variable. + ob1.x = 10; + ob2.x = 20; + System.out.println("Of course, ob1.x and ob2.x " + "are independent."); + System.out.println("ob1.x: " + ob1.x + "\nob2.x: " + ob2.x); + System.out.println(); + + // Each object shares one copy of a static variable. + System.out.println("The static variable y is shared."); + StaticDemo.y = 19; + System.out.println("Set StaticDemo.y to 19."); + + System.out.println("ob1.y = " + ob1.y); + System.out.println("ob2.y = " + ob2.y); + System.out.println(); + + System.out.println("Hereby: "); + System.out.println("ob1.sum(): " + ob1.sum()); + System.out.println("ob2.sum(): " + ob2.sum()); + System.out.println(); + + StaticDemo.y = 100; + System.out.println("Change StaticDemo.y to 100"); + + System.out.println("ob1.y = " + ob1.y); + System.out.println("ob2.y = " + ob2.y); + System.out.println(); + + System.out.println("Hereby: "); + System.out.println("ob1.sum(): " + ob1.sum()); + System.out.println("ob2.sum(): " + ob2.sum()); + System.out.println(); + + } + +} diff --git a/Chapter6/SDemo2.java b/Chapter6/SDemo2.java new file mode 100644 index 0000000..9f8acbc --- /dev/null +++ b/Chapter6/SDemo2.java @@ -0,0 +1,27 @@ +// Use a static method. +class StaticMeth{ + static int val = 1024; // a static variable + + // a static method + static int valDiv2() { + return val/2; + } + +} + + +public class SDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("val is " + StaticMeth.val); + System.out.println("StaticMeth.valDiv2(): " + StaticMeth.valDiv2()); + + StaticMeth.val = 4; + System.out.println("val is " + StaticMeth.val); + System.out.println("StaticMeth.valDiv2(): " + StaticMeth.valDiv2()); + + } + +} diff --git a/Chapter6/SDemo3.java b/Chapter6/SDemo3.java new file mode 100644 index 0000000..c4b4a35 --- /dev/null +++ b/Chapter6/SDemo3.java @@ -0,0 +1,31 @@ +// Use a static block +class StaticBlock{ + static double rootOf2; + static double rootOf3; + + // This block is executed when the class is loaded. + static { + System.out.println("Inside static block."); + rootOf2 = Math.sqrt(2.0); + rootOf3 = Math.sqrt(3.0); + } + + public StaticBlock(String msg) { + + System.out.println(msg); + + } +} + +public class SDemo3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + StaticBlock ob = new StaticBlock("Inside Constructor"); + + System.out.println("Square root of 2 is " + StaticBlock.rootOf2); + System.out.println("Square root of 3 is " + StaticBlock.rootOf3); + + } + +} diff --git a/Chapter6/Self_Test_Chapter6_No13.java b/Chapter6/Self_Test_Chapter6_No13.java new file mode 100644 index 0000000..3045865 --- /dev/null +++ b/Chapter6/Self_Test_Chapter6_No13.java @@ -0,0 +1,65 @@ +import java.util.Scanner; + +/* + * Create a varargs method called sum() that sums the int values passed to it. + * */ + +public class Self_Test_Chapter6_No13 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] collection = new int[10]; + + System.out.print("Please enter 10 integers for the program to find the sum of them.\n"); + + for (int i = 0; i < collection.length; i++) { + + switch (i) { + case 0: { + System.out.println("Now, insert the first integer: "); + Scanner myScanner = new Scanner(System.in); + collection[0] = myScanner.nextInt(); +// myScanner.close(); +/* + * What does scanner.close() do? + * + * "Yes, it does mean that System.in will be closed. + * Once closed, you won't be able to use System.in for the rest of your program. + * In most cases you won't want to close System.in, so you won't want to call .close() in that case." + * + * Reference: https://stackoverflow.com/questions/26245468/what-does-scanner-close-do */ + break; + } + + default: + System.out.println("Now, insert the No." + (i + 1) + " value."); + Scanner myScanner = new Scanner(System.in); + collection[i] = myScanner.nextInt(); + } + } + + sums(collection); + } + + + static void sums(int ... v) { + + int summation = 0; + + int[] orthodoxy = new int[v.length]; + + for (int i = 0; i < orthodoxy.length; i++) { + + orthodoxy[i] = v[i]; + } + + for (int i = 0; i < orthodoxy.length; i++) { + summation += orthodoxy[i]; + } + + System.out.println("The sum of the 10 integers you entered is " + summation); + + } + +} diff --git a/Chapter6/Self_Test_Chapter6_No15.java b/Chapter6/Self_Test_Chapter6_No15.java new file mode 100644 index 0000000..87112ed --- /dev/null +++ b/Chapter6/Self_Test_Chapter6_No15.java @@ -0,0 +1,19 @@ + +public class Self_Test_Chapter6_No15 { + + static void vaTest(int ... v) { + + } + + static void vaTest(int w, int ... v) { + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest(1); + + } + +} diff --git a/Chapter6/Self_Test_Chapter6_No3.java b/Chapter6/Self_Test_Chapter6_No3.java new file mode 100644 index 0000000..d3dcd57 --- /dev/null +++ b/Chapter6/Self_Test_Chapter6_No3.java @@ -0,0 +1,110 @@ + +class Stack { + private char[] stack; // This array holds the stack input. + + private int push_at, pop_at; // the push and pop indices. + + public Stack(int size) { + + stack = new char[size]; // Allow the user to specify the size of the stack when it is created. + push_at = 0; // the push indices (plural of index) are initially set to zero. + pop_at = size - 1; + + } + + public Stack(char[] char_array) { + // TODO Auto-generated constructor stub + push_at = 0; + pop_at = char_array.length - 1; + + stack = new char[char_array.length]; + + // Copy elements + for (int i = 0; i < char_array.length; i++) push(char_array[i]); + } + + public Stack(Stack objectStack) { + + push_at = 0; + this.pop_at = objectStack.stack.length -1; + stack = new char[objectStack.stack.length]; + + // Copy elements + for (int i = 0; i < objectStack.stack.length; i++) { + stack[i] = objectStack.stack[i]; + } + } + + void push(char ch) { + if (push_at == stack.length) { + System.out.println(" - Stack is full."); + } else { + stack[push_at++] = ch; + } + } + + char pop() { + if (pop_at < 0) { + System.out.println(" - Stack is empty"); + return (char) 0; + } else { + return stack[pop_at--]; + } + } +} + +public class Self_Test_Chapter6_No3 { + + public static void main(String[] args) { + + // Create 10-element empty stack. + Stack stack1 = new Stack(10); + + char name[] = { 'T', 'O', 'M' }; + + // Construct stack from array. + Stack stack2 = new Stack(name); + + char ch; + int j; + + // push some characters into stack1 + for (j = 0; j < 10; j++) { + stack1.push((char) ('A' + j)); + } + + // Construct stack from another stack + Stack stack3 = new Stack(stack1); + + // show the stack + System.out.print("Content of stack1: "); + for (j = 9; j > -1; j--) { + + ch = stack1.pop(); + + System.out.print(ch); + } + + System.out.println("\n"); + + System.out.print("Content of stack2: "); + for (j = 2; j > -1; j--) { + + ch = stack2.pop(); + + System.out.print(ch); + } + + System.out.println("\n"); + + System.out.print("Content of stack3: "); + for (j = 9; j > -1; j--) { + + ch = stack3.pop(); + + System.out.print(ch); + } + + } + +} diff --git a/Chapter6/Self_Test_Chapter6_No6.java b/Chapter6/Self_Test_Chapter6_No6.java new file mode 100644 index 0000000..1e705cc --- /dev/null +++ b/Chapter6/Self_Test_Chapter6_No6.java @@ -0,0 +1,23 @@ + +public class Self_Test_Chapter6_No6 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} + + +class Recursive { + + String inverseString; + + String Reverse(String forwardString) { + + inverseString = forwardString; + + return inverseString; + + } +} \ No newline at end of file diff --git a/Chapter6/Self_Test_Chapter6_No6_Annotation.java b/Chapter6/Self_Test_Chapter6_No6_Annotation.java new file mode 100644 index 0000000..aff435f --- /dev/null +++ b/Chapter6/Self_Test_Chapter6_No6_Annotation.java @@ -0,0 +1,110 @@ + +class Stack2 { + private char[] stack; + + private int push_at, pop_at; + + public Stack2(int size) { + + stack = new char[size]; + push_at = 0; + pop_at = size - 1; + + } + + public Stack2(char[] char_array) { // Array in Java is implemented as objects. Thus, it is called by reference. + + push_at = 0; + pop_at = char_array.length - 1; + + stack = new char[char_array.length]; // In case of call by reference, it's better to make a copy of the argument for later manipulation because changes to the object inside the method will affect the object used as an argument. See page 138 and 218 of the textbook. + + // Copy elements + for (int i = 0; i < char_array.length; i++) push(char_array[i]); + } + + public Stack2(Stack2 objectStack) { + + push_at = 0; + this.pop_at = objectStack.stack.length -1; + stack = new char[objectStack.stack.length]; + + // Copy elements + for (int i = 0; i < objectStack.stack.length; i++) { + stack[i] = objectStack.stack[i]; + } + } + + void push(char ch) { + if (push_at == stack.length) { + System.out.println(" - Stack is full."); + } else { + stack[push_at++] = ch; + } + } + + char pop() { + if (pop_at < 0) { + System.out.println(" - Stack is empty"); + return (char) 0; + } else { + return stack[pop_at--]; + } + } +} + +public class Self_Test_Chapter6_No6_Annotation { + + public static void main(String[] args) { + + // Create 10-element empty stack. + Stack2 stack2_I = new Stack2(10); + + char name[] = { 'T', 'O', 'M' }; + + // Construct stack from array. + Stack2 stack2_II = new Stack2(name); + + char ch; + int j; + + // push some characters into stack1 + for (j = 0; j < 10; j++) { + stack2_I.push((char) ('A' + j)); + } + + // Construct stack from another stack + Stack2 stack2_III = new Stack2(stack2_I); + + // show the stack + System.out.print("Content of stack1: "); + for (j = 9; j > -1; j--) { + + ch = stack2_I.pop(); + + System.out.print(ch); + } + + System.out.println("\n"); + + System.out.print("Content of stack2: "); + for (j = 2; j > -1; j--) { + + ch = stack2_II.pop(); + + System.out.print(ch); + } + + System.out.println("\n"); + + System.out.print("Content of stack3: "); + for (j = 9; j > -1; j--) { + + ch = stack2_III.pop(); + + System.out.print(ch); + } + + } + +} diff --git a/Chapter6/Self_Test_Chapter6_No7.java b/Chapter6/Self_Test_Chapter6_No7.java new file mode 100644 index 0000000..a5d299d --- /dev/null +++ b/Chapter6/Self_Test_Chapter6_No7.java @@ -0,0 +1,32 @@ + +class Prudential { + + int x; + static int y; + +} + +public class Self_Test_Chapter6_No7 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Prudential controlPrudential = new Prudential(); + Prudential experimentPrudential = new Prudential(); + + controlPrudential.x = 12; + experimentPrudential.x = 34; + + System.out.println("The member variable x of control and experiment objects of class Prudential are " + + controlPrudential.x + " and " + experimentPrudential.x + ", respectively. \n"); + + controlPrudential.y = 56; + experimentPrudential.y = 78; + + System.out + .println("The static member variable y of control" + " and experiment objects of class Prudential are " + + controlPrudential.y + " and " + experimentPrudential.y + ", respectively."); + + } + +} diff --git a/Chapter6/Self_Test_Chpater6_No4.java b/Chapter6/Self_Test_Chpater6_No4.java new file mode 100644 index 0000000..f0f4e69 --- /dev/null +++ b/Chapter6/Self_Test_Chpater6_No4.java @@ -0,0 +1,37 @@ + +class Test3{ + + int a; + public Test3(int i) { + a = i; + } + + static void swap(Test3 first, Test3 second){ + int intermediate; + intermediate = first.a; + + first.a = second.a; + + second.a = intermediate; + } + +} + +public class Self_Test_Chpater6_No4 { + + public static void main(String[] args) { + + Test3 objectTest3 = new Test3(4); + Test3 object2Test3 = new Test3(5); + + System.out.println("The contents of the objectTest3 and object2Test3 are " + + objectTest3.a + " & " + object2Test3.a); + + Test3.swap(object2Test3, objectTest3); + + System.out.println("After the call of swap(), the contents of the objectTest3 and object2Test3 are " + + objectTest3.a + " & " + object2Test3.a); + + } + +} diff --git a/Chapter6/StaticError.java b/Chapter6/StaticError.java new file mode 100644 index 0000000..eea16c3 --- /dev/null +++ b/Chapter6/StaticError.java @@ -0,0 +1,19 @@ + +public class StaticError { + + int denom = 3; // A normal instance variable + static int val = 1024; // A static variable + + /* Error! Can't access a non-static variable from within a static method. */ + static int valDivDenom() { + return val/denom; // won't compile! + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("StaticError.valDivDenom = " + StaticError.valDivDenom()); + + } + +} diff --git a/Chapter6/SumDemo.java b/Chapter6/SumDemo.java new file mode 100644 index 0000000..8052991 --- /dev/null +++ b/Chapter6/SumDemo.java @@ -0,0 +1,33 @@ +// Initialize one object with another. + +class Summation{ + + int sum; + + // Construct from an int. + public Summation(int num) { + + sum= 0; + for(int i = 1; i <= num; i++) + sum += i; + } + + // Construct from another object. + public Summation(Summation ob) { + + sum = ob.sum; + } +} + +public class SumDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Summation s1 = new Summation(5); + Summation s2 = new Summation(s1); + + System.out.println("s1.sum: " + s1.sum); + System.out.println("s2.sum: " + s2.sum); + } + +} diff --git a/Chapter6/SumDemo2.java b/Chapter6/SumDemo2.java new file mode 100644 index 0000000..40e004e --- /dev/null +++ b/Chapter6/SumDemo2.java @@ -0,0 +1,22 @@ +class Summation2{ + + int sum; + + // Construct from another object. + public Summation2(Summation ob) { + + sum = ob.sum; + } +} + +public class SumDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Summation2 s1 = new Summation2(); + Summation2 s2 = new Summation2(s1); + + } + +} diff --git a/Chapter6/TypeConv.java b/Chapter6/TypeConv.java new file mode 100644 index 0000000..441bd4d --- /dev/null +++ b/Chapter6/TypeConv.java @@ -0,0 +1,38 @@ +/* + * Automatic type conversion can affect overloaded method resolution. + */ + +class Overload2{ + void f(int x) { + System.out.println("Inside f(int): " + x); + } + + void f(double x) { + System.out.println("Inside f(double): " + x); + } +} + +public class TypeConv { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Overload2 obOverload2 = new Overload2(); + + int i = 10; + double d = 10.1; + + byte b = 99; + short s = 10; + float f = 11.5F; + + obOverload2.f(i); // calls ob,f(int) + obOverload2.f(d); // calls ob.f(double) + + obOverload2.f(b); // calls ob,f(int) - type conversion + obOverload2.f(s); // calls ob.f(int) - type conversion + obOverload2.f(f); // calls ob.f(double) - type conversion + + } + +} diff --git a/Chapter6/TypeConv2.java b/Chapter6/TypeConv2.java new file mode 100644 index 0000000..1ad7c82 --- /dev/null +++ b/Chapter6/TypeConv2.java @@ -0,0 +1,48 @@ +/* + * In the context of method overload in Java, + * automatic type conversions apply only if there is no direct match between a parameter and an argument. + * + * Textbook page on 226 + * + * */ + +class Overload3{ + + void f(byte x) { + System.out.println("Inside f(byte): " + x); + } + + void f(int x) { + System.out.println("Inside f(int): " + x); + } + + void f(double x) { + System.out.println("Inside f(double): " + x); + } +} + +public class TypeConv2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Overload3 obOverload3 = new Overload3(); + + int i = 10; + double d = 10.1; + + byte b = 99; + short s = 10; + float f = 11.5F; + + obOverload3.f(i); // calls ob,f(int) + obOverload3.f(d); // calls ob.f(double) + + obOverload3.f(b); // now, no type conversion + + obOverload3.f(s); // calls ob.f(int) - type conversion + obOverload3.f(f); // calls ob.f(double) - type conversion + + } + +} diff --git a/Chapter6/Using_class_type_as_parameters_to_methods/A_variable_of_a_class_type.java b/Chapter6/Using_class_type_as_parameters_to_methods/A_variable_of_a_class_type.java new file mode 100644 index 0000000..9bfb52d --- /dev/null +++ b/Chapter6/Using_class_type_as_parameters_to_methods/A_variable_of_a_class_type.java @@ -0,0 +1,47 @@ +package Using_class_type_as_parameters_to_methods; + +class TwoDShape{ + private double width; + private double height; + private String name; + + public TwoDShape() { + width = height = 0.0; + name = "none"; + } + + TwoDShape(double w, double h, String n){ + width = w; + height = h; + name = n; + } + + TwoDShape(double x, String n){ + width = height = x; + name = n; + } + + TwoDShape(TwoDShape ob){ + width = ob.width; + height = ob.height; + name = ob.name; + } +} + +public class A_variable_of_a_class_type { + + public static void main(String[] args) { + + // Declaring a variable of the class type does not define an object. Instead, it is simply a variable that can + // hold the memory address of the object. (The address in memory of the object created by keyword new.) + TwoDShape variableTwoDShape; + + // It is a variable that can hold the object's memory address created by new, but it is not an object itself. + System.out.println(variableTwoDShape.name); + + // The keyword new created a (new) object and assigned its memory address to the variable that can hold it. + TwoDShape referenceShape = new TwoDShape(1.0, "memory address"); + // Now, the variable is linked with an object. + } + +} diff --git a/Chapter6/VarArgs.java b/Chapter6/VarArgs.java new file mode 100644 index 0000000..012b710 --- /dev/null +++ b/Chapter6/VarArgs.java @@ -0,0 +1,27 @@ +// Demonstrate variable-length arguments. +public class VarArgs { + + // vaTest() uses a vararg. + static void vaTest(int ... v ) { + + System.out.println("Number of args: " + v.length); + System.out.println("Contents: "); + + for(int i = 0; i < v.length ; i++) + System.out.println(" arg " + i + ": " + v[i]); + + System.out.println(); + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + + // Notice how vaTest() can be called with a variable number of arguments. + vaTest(10); // 1 arg + vaTest(1, 2, 3); // 3 args + vaTest(); // no args + + } + +} diff --git a/Chapter6/VarArgs2.java b/Chapter6/VarArgs2.java new file mode 100644 index 0000000..64ad448 --- /dev/null +++ b/Chapter6/VarArgs2.java @@ -0,0 +1,24 @@ +// Use varargs with standard arguments. +public class VarArgs2 { + + // Here, msg is a normal parameter and v is a varargs parameter. + static void vaTest(String msg, int ... v) { + System.out.println(msg + v.length); + System.out.println("Contents: " ); + + for(int i = 0; i < v.length ; i++) + System.out.println(" arg " + i + ": " + v[i]); + + System.out.println(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest("One vararg: ", 10); + vaTest("Three varargs: ", 1, 2, 3); + vaTest("No varargs: "); + + } + +} diff --git a/Chapter6/VarArgs3.java b/Chapter6/VarArgs3.java new file mode 100644 index 0000000..d07ff87 --- /dev/null +++ b/Chapter6/VarArgs3.java @@ -0,0 +1,48 @@ + +// VarArgs and overloading. +public class VarArgs3 { + + static void vaTest (int ... v) { + + System.out.println("vaTest(int ... ): " + "Number of args: " + v.length); + + System.out.println("Contents: "); + + for(int i = 0; i < v.length ; i++) + System.out.println(" arg " + i + ": " + v[i]); + + System.out.println(); + } + + static void vaTest(boolean ... v) { + + System.out.println("vaTest(boolean...): " + "Number of args: " + v.length); + System.out.println("Contents: "); + + for(int i = 0 ; i < v.length ; i++) + System.out.println(" arg " + i + ": " + v[i]); + + System.out.println(); + } + + static void vaTest(String msg, int ... v) { + + System.out.println("vaTest(String msg, int ... v): " + "Testing: " + v.length); + System.out.println("Contents: "); + + for(int i = 0 ; i < v.length ; i++) + System.out.println(" arg " + i + ": " + v[i]); + + System.out.println(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest(1, 2, 3); + vaTest("Testing: ", 10, 20 ); + vaTest(true, false, false); + + } + +} diff --git a/Chapter6/VarArgs4.java b/Chapter6/VarArgs4.java new file mode 100644 index 0000000..b47c2cf --- /dev/null +++ b/Chapter6/VarArgs4.java @@ -0,0 +1,26 @@ +// Varargs, overloading, and ambiguity. +// +// This program contains an error and will not compile. +public class VarArgs4 { + + // Use an int vararg parameter. + static void vaTest(int ... v) { + /// ... + } + + // Use a boolean vararg parameter. + static void vaTest(boolean ... v ) { + // ... + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest(1,2,3); // ok + vaTest(true, false, false); // ok + + vaTest(); // Ambiguous! + + } + +} diff --git a/Chapter6/VarArgs5.java b/Chapter6/VarArgs5.java new file mode 100644 index 0000000..3d9d944 --- /dev/null +++ b/Chapter6/VarArgs5.java @@ -0,0 +1,20 @@ + +public class VarArgs5 { + + static void vaTest(int n, int ... v) { + + System.out.println("Contents of array v: "); + + for(int i = 0 ; i < v.length ; i++) + System.out.print(v[i] + " "); + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest(5); + + } + +} diff --git a/Chapter6/VarArgs6.java b/Chapter6/VarArgs6.java new file mode 100644 index 0000000..9a5266d --- /dev/null +++ b/Chapter6/VarArgs6.java @@ -0,0 +1,22 @@ + +public class VarArgs6 { + + static void vaTest(int n, int ... v) { + + System.out.println("Contents of array v: "); + + for(int i = 0 ; i < v.length ; i++) + System.out.print(v[i] + " "); + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest(5); + + int[] null_array = {null, null, null}; + + } + +} diff --git a/Chapter6/VarArgs7.java b/Chapter6/VarArgs7.java new file mode 100644 index 0000000..a6702ad --- /dev/null +++ b/Chapter6/VarArgs7.java @@ -0,0 +1,20 @@ + +public class VarArgs7 { + + static void vaTest(int n, int ... v) { // Parameters of a method are essentially "variables" that receive the value of arguments passed to the method when it is called. See Textbook page 140. + + System.out.println("Contents of array v: "); + + for(int i = -5 ; i < v.length ; i++) + System.out.print(v[i] + " "); + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + vaTest(5); + + } + +} diff --git a/Chapter6/refresher/NestedClassDemo.java b/Chapter6/refresher/NestedClassDemo.java new file mode 100644 index 0000000..61a3093 --- /dev/null +++ b/Chapter6/refresher/NestedClassDemo.java @@ -0,0 +1,69 @@ +package refresher; + +class Outer { + + int nums[]; + + Outer(int n[]) { + // TODO Auto-generated constructor stub + nums = n; + } + + void analyze() { + Inner inOb = new Inner(); + + System.out.println("Minimum: " + inOb.min()); + System.out.println("Maximum: " + inOb.max()); + System.out.println("Average: " + inOb.avg()); + } + + // This is an inner class. + class Inner { + + int min() { + int m = nums[0]; + + for (int i = 1; i < nums.length; i++) + if (nums[i] < m) + m = nums[i]; + return m; + } + + int max() { + int m = nums[0]; + for (int i = 1; i < nums.length; i++) + if (nums[i] > m) + m = nums[i]; + + return m; + } + + int avg() { + int a = 0; + for (int i = 0; i < nums.length; i++) + a += nums[i]; + + return a / nums.length; + } + } +} + + +public class NestedClassDemo { + + public static void main(String[] args) { + + int x[] = { 3, 2, 1, 5, 6, 9, 7, 8 }; + + Outer outOb = new Outer(x); + + outOb.analyze(); + + // No enclosing instance of type Outer is accessible. + // Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() + // where x is an instance of Outer). +// Inner inner = new Inner(); + + } + +} diff --git a/Chapter6/refresher/NestedClassDemo2.java b/Chapter6/refresher/NestedClassDemo2.java new file mode 100644 index 0000000..a97e4c2 --- /dev/null +++ b/Chapter6/refresher/NestedClassDemo2.java @@ -0,0 +1,66 @@ +package refresher; + +class Outer2 { + + int nums[]; + + Outer2(int n[]) { + // TODO Auto-generated constructor stub + nums = n; + } + + void analyze() { + Inner inOb = new Inner(); + + System.out.println("Minimum: " + inOb.min()); + System.out.println("Maximum: " + inOb.max()); + System.out.println("Average: " + inOb.avg()); + } + + // This is an inner class. + class Inner { + + int min() { + int m = nums[0]; + + for (int i = 1; i < nums.length; i++) + if (nums[i] < m) + m = nums[i]; + return m; + } + + int max() { + int m = nums[0]; + for (int i = 1; i < nums.length; i++) + if (nums[i] > m) + m = nums[i]; + + return m; + } + + int avg() { + int a = 0; + for (int i = 0; i < nums.length; i++) + a += nums[i]; + + return a / nums.length; + } + } +} + +public class NestedClassDemo2 { + + public static void main(String[] args) { + + + int x[] = { 3, 2, 1, 5, 6, 9, 7, 8 }; + + Outer2 outOb = new Outer2(x); + + outOb.analyze(); + + refresher.Outer2.Inner inner = new refresher.Outer2.Inner(); + + } + +} diff --git a/Chapter6/refresher/NestedClassDemo3.java b/Chapter6/refresher/NestedClassDemo3.java new file mode 100644 index 0000000..f54cd0c --- /dev/null +++ b/Chapter6/refresher/NestedClassDemo3.java @@ -0,0 +1,66 @@ +package refresher; + + +class Outer3 { + + int nums[]; + + Outer3(int n[]) { + // TODO Auto-generated constructor stub + nums = n; + } + + void analyze() { + Inner inOb = new Inner(); + + System.out.println("Minimum: " + inOb.min()); + System.out.println("Maximum: " + inOb.max()); + System.out.println("Average: " + inOb.avg()); + } + + // This is an inner class. + class Inner { + + int min() { + int m = nums[0]; + + for (int i = 1; i < nums.length; i++) + if (nums[i] < m) + m = nums[i]; + return m; + } + + int max() { + int m = nums[0]; + for (int i = 1; i < nums.length; i++) + if (nums[i] > m) + m = nums[i]; + + return m; + } + + int avg() { + int a = 0; + for (int i = 0; i < nums.length; i++) + a += nums[i]; + + return a / nums.length; + } + } +} + +public class NestedClassDemo3 { + + public static void main(String[] args) { + + int[] x = {2, 4, 6, 8, 10}; + + Outer3 outer3 = new Outer3(x); + + outer3.analyze(); + + // outer3.analyze().; + + } + +} diff --git a/Chapter6/refresher/Self_Test_Chapter6_No3.java b/Chapter6/refresher/Self_Test_Chapter6_No3.java new file mode 100644 index 0000000..9e258ac --- /dev/null +++ b/Chapter6/refresher/Self_Test_Chapter6_No3.java @@ -0,0 +1,23 @@ +package refresher; + +class Stack{ + + private char stck[]; // this array holds the stack. + private int tos; // top of stack + + // Construct an empty Stack given its size. + public Stack(int size) { + stck = new char[size]; + tos = 0; + } + +} + +public class Self_Test_Chapter6_No3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/A.java b/Chapter7/A.java new file mode 100644 index 0000000..d6774bc --- /dev/null +++ b/Chapter7/A.java @@ -0,0 +1,22 @@ +// Using super to overcome name hiding. +public class A { + + int i ; + +} + +class B extends A { + + int i; // this i hides the i in A. + + public B(int a, int b) { + + super.i = a ; // Here, super.i refers to the i in A. + i = b ; // i in B + } + + void show() { + System.out.println("i in superclass: " + super.i); + System.out.println("i in subclass: " + i); + } +} diff --git a/Chapter7/AbsShape.java b/Chapter7/AbsShape.java new file mode 100644 index 0000000..26f4f57 --- /dev/null +++ b/Chapter7/AbsShape.java @@ -0,0 +1,23 @@ + +public class AbsShape { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + TwoDShape_abstract shapes[] = new TwoDShape_abstract[4]; + + shapes[0] = new Triangle_extends_abstract_superclass("outlined", 8.0, 12.0); + shapes[1] = new Rectangle_extends_abstract_superclass(10); + shapes[2] = new Rectangle_extends_abstract_superclass(10, 4); + shapes[3] = new Triangle_extends_abstract_superclass(7.0); + + for (int i = 0; i < shapes.length; i++) { + System.out.println("Object is " + shapes[i].getName()); + System.out.println("Area is " + shapes[i].area()); + + System.out.println(); + } + + } + +} diff --git a/Chapter7/Abstract_Class.java b/Chapter7/Abstract_Class.java new file mode 100644 index 0000000..11a8783 --- /dev/null +++ b/Chapter7/Abstract_Class.java @@ -0,0 +1,165 @@ + +abstract class Abstract_TwoDShape { + + private double width; + private double height; + private String name; + + // A default constructor + public Abstract_TwoDShape() { + width = height = 0.0; + name = "none"; + } + + // Parameterized constructor. + Abstract_TwoDShape(double w, double h, String n){ + width = w; + height = h; + name = n; + } + + // Construct object with equal width and height. + Abstract_TwoDShape(double x, String n){ + width = height = x; + name = n; + } + + // Construct an object from an object. + Abstract_TwoDShape(Abstract_TwoDShape ob){ + width = ob.width; + height = ob.height; + name = ob.name; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + String getName() { + return name; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + + // declare an abstract method + abstract double area(); + +} + + +class Triangle_extends_abstract_superclass2 extends Abstract_TwoDShape { + + private String styleString; + + // A default constructor + public Triangle_extends_abstract_superclass2() { + // TODO Auto-generated constructor stub + super(); + + styleString = "none"; + + } + + // Constructor for Triangle + Triangle_extends_abstract_superclass2(String s, double w, double h){ + super(w, h, "triangle"); + + styleString = s; + } + + // One argument constructor. + Triangle_extends_abstract_superclass2(double x){ + super(x, "triangle"); // call superclass constructor + + styleString = "filled"; + } + + // Construct an object from an object. + Triangle_extends_abstract_superclass2(Triangle_extends_abstract_superclass2 ob){ + super(ob); // pass object to TwoDShape constructor + styleString = ob.styleString; + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } +} + + +class Rectangle_extends_abstract_superclass2 extends Abstract_TwoDShape { + + // A default constructor + public Rectangle_extends_abstract_superclass2() { + // TODO Auto-generated constructor stub + super(); + } + + // Constructor for Rectangle + Rectangle_extends_abstract_superclass2(double w, double h){ + super(w, h, "rectangle"); // Call superclass constructor + } + + // Construct a square + Rectangle_extends_abstract_superclass2(double x) { + super(x, "rectangle"); // call superclass constructor + } + + // Construct an object from an object. + Rectangle_extends_abstract_superclass2(Rectangle_extends_abstract_superclass2 ob){ + super(ob); // pass object to TwoDShape constructor. + } + + boolean isSquare() { + + if ( getWidth() == getHeight() ) + return true; + + return false; + } + + double area() { + return getWidth() * getHeight(); + } + +} + +public class Abstract_Class { + + public static void main(String[] args) { + + Abstract_TwoDShape shapes[] = new Abstract_TwoDShape[4]; + + shapes[0] = new Triangle_extends_abstract_superclass2("outlined", 8.0, 12.0); + shapes[1] = new Rectangle_extends_abstract_superclass2(10); + shapes[2] = new Rectangle_extends_abstract_superclass2(10, 4); + shapes[3] = new Triangle_extends_abstract_superclass2(7.0); + + for (int i = 0; i < shapes.length; i++) { + System.out.println("Object is " + shapes[i].getName()); + System.out.println("Area is " + shapes[i].area()); + + System.out.println(); + } + + } + +} diff --git a/Chapter7/An_example_of_inheritance.java b/Chapter7/An_example_of_inheritance.java new file mode 100644 index 0000000..2176b85 --- /dev/null +++ b/Chapter7/An_example_of_inheritance.java @@ -0,0 +1,104 @@ +// Source: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html +class Bicycle { + + // the Bicycle class has three fields + public int cadence; + public int gear; + public int speed; + + // the Bicycle class has one constructor + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } + + // the Bicycle class has four methods + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void applyBrake(int decrement) { + speed -= decrement; + } + + public void speedUp(int increment) { + speed += increment; + } + +} + +class MountainBike extends Bicycle { + + // the MountainBike subclass adds one field + public int seatHeight; + + // the MountainBike subclass has one constructor + public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { + super(startCadence, startSpeed, startGear); + + seatHeight = startHeight; + } + + // the MountainBike subclass adds one method + public void setHeight(int newValue) { + seatHeight = newValue; + } +} + +/* MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. + * Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, + * with four fields and five methods. + * + * However, you didn't have to do all the work. + * + * This would be especially valuable if the methods in the Bicycle class were complex + * and had taken substantial time to debug. + * + * */ + +public class An_example_of_inheritance { + + public static void main(String[] args) { + + MountainBike giantBike = new MountainBike(15, 28, 0, 10); + + System.out.println(giantBike.cadence); + + } +} + +/* Keynote: + * In the Java language, classes can be derived from other classes, + * thereby inheriting fields and methods from those classes. + * + * Definitions: + * A class that is derived from another class is called a subclass (also a derived class, + * extended class, or child class). The class from which the subclass is derived is called a superclass + * (also a base class or a parent class). + * + * The idea of inheritance is simple but powerful: When you want to create a new class and + * there is already a class that includes some of the code that you want, + * you can derive your new class from the existing class. + * + * In doing this, you can reuse the fields and methods of the existing class without having to write + * (and debug!) them yourself. + * + * A subclass inherits all the members (fields, methods, and nested classes) from its superclass. + * Constructors are not members, so they are not inherited by subclasses, + * but the constructor of the superclass can be invoked from the subclass. + * +Private Members in a Superclass: +A subclass does not inherit the private members of its parent class. +However, if the superclass has public or protected methods for accessing its private fields, +these can also be used by the subclass. + +A nested class has access to all the private members of its enclosing class—both fields and methods. +Therefore, a public or protected nested class inherited by a subclass has indirect access to +all of the private members of the superclass. + * + * */ diff --git a/Chapter7/An_example_of_inheritance2.java b/Chapter7/An_example_of_inheritance2.java new file mode 100644 index 0000000..b6a8828 --- /dev/null +++ b/Chapter7/An_example_of_inheritance2.java @@ -0,0 +1,34 @@ +// Source: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + +/* What You Can Do in a Subclass: + * + * A subclass inherits all of the public and protected members of its parent, + * no matter what package the subclass is in. + * + * If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. + * + * You can use the inherited members as is, replace them, hide them, or supplement them with new members: + * + ** The inherited fields can be used directly, just like any other fields. + * + ** You can declare a field in the subclass with the same name as the one in the superclass, + * thus hiding it (not recommended). + * + ** You can declare new fields in the subclass that are not in the superclass. + * + ** The inherited methods can be used directly as they are. + * + ** You can write a new "instance" method in the subclass that has the same signature as the one in the superclass, + * thus overriding it. + * + ** You can write a new "static" method in the subclass that has the same signature as the one in the superclass, + * thus hiding it. + * + ** You can write a subclass constructor that invokes the constructor of the superclass, + * either implicitly or by using the keyword super. + * + * */ + +public class An_example_of_inheritance2 { + +} diff --git a/Chapter7/Circle.java b/Chapter7/Circle.java new file mode 100644 index 0000000..f7beed1 --- /dev/null +++ b/Chapter7/Circle.java @@ -0,0 +1,13 @@ + +public class Circle extends TwoDShape11 { + + public Circle() { + super(); + } + + double area(double radius) { + + return radius * radius * 3.14; + } + +} diff --git a/Chapter7/Circle_test.java b/Chapter7/Circle_test.java new file mode 100644 index 0000000..8d90d76 --- /dev/null +++ b/Chapter7/Circle_test.java @@ -0,0 +1,18 @@ + + +public class Circle_test { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Circle circumstancesCircle = new Circle(); + + double area; + + area = circumstancesCircle.area(10); + + System.out.println("The area of circle is " + area); + + } + +} diff --git a/Chapter7/ColorTriangle.java b/Chapter7/ColorTriangle.java new file mode 100644 index 0000000..09bcf4b --- /dev/null +++ b/Chapter7/ColorTriangle.java @@ -0,0 +1,22 @@ +// ColorTriangle inherits Triangle7 which is descended from TwoDShape, so ColorTriangle includes all members of Triangle7 +// and TwoDShape. + +public class ColorTriangle extends Triangle7 { + + private String colorString; + + public ColorTriangle(String c, String s, double w, double h) { + super(s, w, h); + + colorString = c; + } + + String getColor() { + return colorString; + } + + void showColor() { + System.out.println("Color is " + colorString); + } + +} diff --git a/Chapter7/DynShapes.java b/Chapter7/DynShapes.java new file mode 100644 index 0000000..21133a1 --- /dev/null +++ b/Chapter7/DynShapes.java @@ -0,0 +1,22 @@ + +public class DynShapes { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + TwoDShape11 shapes[] = new TwoDShape11[5]; + + shapes[0] = new Triangle11("outlined", 8.0, 12.0); + shapes[1] = new Rectangle11(10); + shapes[2] = new Rectangle11(10, 4); + shapes[3] = new Triangle11(7.0); + shapes[4] = new TwoDShape11(10, 20, "generic"); + + for (int i = 0; i < shapes.length; i++) { + System.out.println("object is " + shapes[i].getName()); + System.out.println("Area is " + shapes[i].area());//The proper version of area() is called for each shape. + } + + } + +} diff --git a/Chapter7/Dynamic_Dispatch_Demo.java b/Chapter7/Dynamic_Dispatch_Demo.java new file mode 100644 index 0000000..55590cb --- /dev/null +++ b/Chapter7/Dynamic_Dispatch_Demo.java @@ -0,0 +1,43 @@ +// Demonstrate dynamic method dispatch. +class Sup { + + void who() { + System.out.println("Who() in Sup"); + } +} + +class Sub1 extends Sup { + + void who() { + System.out.println("Who() in Sub1"); + } +} + +class Sub2 extends Sup { + void who() { + System.out.println("Who () in Sub2"); + } +} + +public class Dynamic_Dispatch_Demo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Sup superOb = new Sup(); + Sub1 subOb1 = new Sub1(); + Sub2 subOb2 = new Sub2(); + + Sup supRef; // Declaring a variable called supRef of the class type Sup. This variable does not define an object. Instead, it is simply a variable that can refer to an object. + + supRef = superOb; + supRef.who(); // In each case, the version of who() to call is determined at run time by ... + + supRef = subOb1; + supRef.who(); // ... the type of object being referred to. + + supRef = subOb2; + supRef.who(); + } + +} diff --git a/Chapter7/Dynamic_Disptach_Demo_2.java b/Chapter7/Dynamic_Disptach_Demo_2.java new file mode 100644 index 0000000..9babea9 --- /dev/null +++ b/Chapter7/Dynamic_Disptach_Demo_2.java @@ -0,0 +1,19 @@ + +public class Dynamic_Disptach_Demo_2 { + + public static void main(String[] args) { + + Sup superOb = new Sup(); + + superOb.who(); // In each case, the version of who() to call is determined at run time by ... + + superOb = new Sub1(); + superOb.who(); // ... the type of object being referred to. + + superOb = new Sub2(); + superOb.who(); + + + } + +} diff --git a/Chapter7/Final/FinalD.java b/Chapter7/Final/FinalD.java new file mode 100644 index 0000000..845dbe0 --- /dev/null +++ b/Chapter7/Final/FinalD.java @@ -0,0 +1,22 @@ +package Final; + +class W3school { + final int x = 10; // Set a variable to final, to prevent it from being modified: +} + +public class FinalD { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + W3school myW3school = new W3school(); + + myW3school.x = 25; // will generate an error: cannot assign a value to a final variable. + + System.out.println(myW3school.x); + + } + +} + +// Reference: https://web.archive.org/web/20210829102525/https://www.w3schools.com/java/ref_keyword_final.asp \ No newline at end of file diff --git a/Chapter7/Final/FinalD_.java b/Chapter7/Final/FinalD_.java new file mode 100644 index 0000000..ac689db --- /dev/null +++ b/Chapter7/Final/FinalD_.java @@ -0,0 +1,18 @@ +package Final; + +class W3Cschool { + final int x = 10; +} + +public class FinalD_ { + + public static void main(String[] args) { + W3Cschool myW3Cschool = new W3Cschool(); + + int y = myW3Cschool.x; + + System.out.println("final x = " + myW3Cschool.x + "; int y = " + y); + + } + +} diff --git a/Chapter7/Final/Named_constant.java b/Chapter7/Final/Named_constant.java new file mode 100644 index 0000000..73feb40 --- /dev/null +++ b/Chapter7/Final/Named_constant.java @@ -0,0 +1,13 @@ +package Final; + +public class Named_constant { + + final int defuse; + + public static void main(String[] args) { + + + + } + +} diff --git a/Chapter7/Final/Named_constants.java b/Chapter7/Final/Named_constants.java new file mode 100644 index 0000000..c472a8e --- /dev/null +++ b/Chapter7/Final/Named_constants.java @@ -0,0 +1,16 @@ +package Final; + +public class Named_constants { + + static int constant = 1; + final static int named_constant = 2; + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println(constant); + System.out.println(named_constant); + + } + +} diff --git a/Chapter7/Final/Named_constants_.java b/Chapter7/Final/Named_constants_.java new file mode 100644 index 0000000..6ae479c --- /dev/null +++ b/Chapter7/Final/Named_constants_.java @@ -0,0 +1,29 @@ +package Final; + +// An enumeration is a list of named constants that define a new data type. +public enum Named_constants_ { + Zero, + One, + Two, + Three, + Four, + Five, + Six, + Seven, + Eight, + Nine + +} + +class exploitation { + + + public static void main(String[] args) { + + Named_constants_ falloutConstants_ = Named_constants_.Eight; + + Named_constants_ rock_solidConstants_ = falloutConstants_; + + System.out.println(rock_solidConstants_); + } +} diff --git a/Chapter7/Final/Named_constants_initial_value.java b/Chapter7/Final/Named_constants_initial_value.java new file mode 100644 index 0000000..ea7ecaf --- /dev/null +++ b/Chapter7/Final/Named_constants_initial_value.java @@ -0,0 +1,20 @@ +package Final; + +public class Named_constants_initial_value { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + final int defuse = 8; + + defuse = 10; + + final int bells_and_whistles; + + bells_and_whistles = 22; + + bells_and_whistles = 33; + + } + +} diff --git a/Chapter7/Final/switching.java b/Chapter7/Final/switching.java new file mode 100644 index 0000000..d4be1cc --- /dev/null +++ b/Chapter7/Final/switching.java @@ -0,0 +1,42 @@ +package Final; + +public class switching { + + public static void main(String[] args) { + + int i; + + i = 10; + + System.out.println("Value of i: " + i); + + System.out.println(); + + i = 2; + + if (i == 2) + System.out.println("i contains 2.\n"); + + switch (i) { + case 2: + System.out.println("A boat sails on water."); + break; + case 4: + System.out.println("A truck carries freight."); + break; + case 6: + System.out.println("An airplane flies."); + break; + case 8: + System.out.println("Smooth sailing."); + break; + case 10: + System.out.println("Freight trains."); + break; + default: + break; + } + + } + +} diff --git a/Chapter7/FinalD.java b/Chapter7/FinalD.java new file mode 100644 index 0000000..e5cb210 --- /dev/null +++ b/Chapter7/FinalD.java @@ -0,0 +1,44 @@ +// Return a String object. +class ErrorMsg_final { + // Declare final constants + // Error codes. + final int OUTERR = 0; + final int INERR = 1; + final int DISKERR = 2; + final int INDEXERR = 3; + + String msgs[] = { + "Output Error", + "Input Error", + "Disk Full", + "Index Out-Of_Bounds" + }; + + // Return the error message. + String getErrorMsg(int i) { + if (i >= 0 & i < msgs.length) + return msgs[i]; + else + return "Invalid Error Code"; + } +} + + +public class FinalD { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ErrorMsg_final errorMsg_final = new ErrorMsg_final(); + + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.OUTERR)); + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.DISKERR)); + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.INERR)); + + System.out.println(errorMsg_final.getErrorMsg(2)); + System.out.println(errorMsg_final.getErrorMsg(0)); + System.out.println(errorMsg_final.getErrorMsg(4)); + + } + +} diff --git a/Chapter7/FinalD_.java b/Chapter7/FinalD_.java new file mode 100644 index 0000000..61517ed --- /dev/null +++ b/Chapter7/FinalD_.java @@ -0,0 +1,44 @@ + +// Return a String object. +class ErrorMsg_final_ { + + // Error codes. + int OUTERR = 0; + int INERR = 1; + int DISKERR = 2; + int INDEXERR = 3; + + String msgs[] = { + "Output Error", + "Input Error", + "Disk Full", + "Index Out-Of_Bounds" + }; + + // Return the error message. + String getErrorMsg(int i) { + if (i >= 0 & i < msgs.length) + return msgs[i]; + else + return "Invalid Error Code"; + } +} + +public class FinalD_ { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ErrorMsg_final_ errorMsg_final = new ErrorMsg_final_(); + + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.OUTERR)); + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.DISKERR)); + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.INERR)); + + System.out.println(errorMsg_final.getErrorMsg(2)); + System.out.println(errorMsg_final.getErrorMsg(0)); + System.out.println(errorMsg_final.getErrorMsg(4)); + + } + +} diff --git a/Chapter7/Final_classes_or_methods.java b/Chapter7/Final_classes_or_methods.java new file mode 100644 index 0000000..9cfaacf --- /dev/null +++ b/Chapter7/Final_classes_or_methods.java @@ -0,0 +1,22 @@ +// Use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. + +// You might wish to make a method final if it has an implementation that should not be changed and +// it is critical to the consistent state of the object. + +// For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final: +class ChessAlgorithm{ + enum ChessPlayer {WHITE, BLACK} + + final ChessPlayer getFirstPlayer() { + return ChessPlayer.WHITE; + } +} + +public class Final_classes_or_methods { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/IncompatibleRef.java b/Chapter7/IncompatibleRef.java new file mode 100644 index 0000000..c161811 --- /dev/null +++ b/Chapter7/IncompatibleRef.java @@ -0,0 +1,38 @@ +// This will not compile +class X { + + int a; + + X(int i) { + a = i; + } +} + +class Y { + + int a; + + Y(int i) { + a = i; + } + +} + +public class IncompatibleRef { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + X x = new X(10); + + X x2; + + Y y = new Y(5); + + x2 = x; // Ok, both of same type. + + x2 = y; // Error, not of same type. + + } + +} diff --git a/Chapter7/OrderOfConstruction.java b/Chapter7/OrderOfConstruction.java new file mode 100644 index 0000000..d982107 --- /dev/null +++ b/Chapter7/OrderOfConstruction.java @@ -0,0 +1,34 @@ +// Demonstrate when constructors are executed. + +// Create a super class. +class A2{ + public A2() { + // TODO Auto-generated constructor stub + System.out.println("Constructing A2."); + } +} + +// Create a subclass by extending class A2. +class B2 extends A2{ + public B2() { + System.out.println("Constructing B2."); + } +} + +// Create another subclass by extending B2. +class C2 extends B2{ + public C2() { + System.out.println("Constructing C2."); + } +} + +public class OrderOfConstruction { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + C2 c2 = new C2(); + + } + +} diff --git a/Chapter7/Overide_v_Overload.java b/Chapter7/Overide_v_Overload.java new file mode 100644 index 0000000..4811874 --- /dev/null +++ b/Chapter7/Overide_v_Overload.java @@ -0,0 +1,48 @@ +/* + * Methods with differing signatures are overloaded and not overridden. + * */ + +class AAAAA { + + int i, j; + + AAAAA(int a, int b){ + i = a; + j = b; + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class BBBBB extends AAAAA { + + int k; + + BBBBB(int a, int b, int c){ + super(a, b); + + k = c; + } + + // overload show() + void show(String msg) { // Because signatures differ, this show() simply overloads show() in superclass A. + System.out.println(msg + k); + } +} + +public class Overide_v_Overload { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + BBBBB subBbbbb = new BBBBB(1, 2, 3); + + subBbbbb.show("This is K: "); // This calls show() in B. + subBbbbb.show(); // This calls show() in A. + + } + +} diff --git a/Chapter7/Override.java b/Chapter7/Override.java new file mode 100644 index 0000000..58f83fe --- /dev/null +++ b/Chapter7/Override.java @@ -0,0 +1,47 @@ +// Method overloading +class AA { + + int i, j; + + public AA(int a, int b) { + + i = a; + j = b; + + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class BB extends AA { + + int k; + + public BB(int a, int b, int c) { + super(a, b); + + k = c; + } + + // display k - this overrides show() in AA + void show() { // This show() in BB overrides the one defined by A. + System.out.println("k: " + k); + } + +} + +public class Override { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + BB subOBb = new BB(1, 2, 3); + + subOBb.show(); // This calls show() in B. + + } + +} diff --git a/Chapter7/Override2.java b/Chapter7/Override2.java new file mode 100644 index 0000000..c3ec202 --- /dev/null +++ b/Chapter7/Override2.java @@ -0,0 +1,51 @@ +// Method overloading +class AAA { + + int i, j; + + public AAA(int a, int b) { + + i = a; + j = b; + + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class BBB extends AAA { + + int k; + + public BBB(int a, int b, int c) { + super(a, b); + + k = c; + } + + // display k - this overrides show() in AA + void show() { // This show() in BB overrides the one defined by A. + System.out.println("k: " + k); + } + +} + +public class Override2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + BBB subOBb = new BBB(1, 2, 3); + + subOBb.show(); // This calls show() in B. + + AAA obAaa = new AAA(2, 3); + + obAaa.show(); // This calls show() in A. + + } + +} diff --git a/Chapter7/Override3.java b/Chapter7/Override3.java new file mode 100644 index 0000000..c954670 --- /dev/null +++ b/Chapter7/Override3.java @@ -0,0 +1,52 @@ +// Method overloading +class AAAA { + + int i, j; + + public AAAA(int a, int b) { + + i = a; + j = b; + + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class BBBB extends AAAA { + + int k; + + public BBBB(int a, int b, int c) { + super(a, b); + + k = c; + } + + void show() { + super.show(); // This calls A's show(). + System.out.println("k: " + k); + } + +} + +public class Override3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + + BBBB subOBb = new BBBB(1, 2, 3); + + subOBb.show(); // This calls show() in B. + + AAAA obAaa = new AAAA(2, 3); + + obAaa.show(); // This calls show() in A. + + } + +} diff --git a/Chapter7/Override4.java b/Chapter7/Override4.java new file mode 100644 index 0000000..7dd464e --- /dev/null +++ b/Chapter7/Override4.java @@ -0,0 +1,44 @@ +// Method overriding. + +class AAAAAA{ + int i, j; + + public AAAAAA(int a, int b) { + // TODO Auto-generated constructor stub + + i = a; + + j = b; + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class BBBBBB extends AAAAAA { + int k; + + public BBBBBB(int a, int b, int c) { + super(a, b); + k = c; + } + + // display k -- this overrides show() in A + void show() { + System.out.println("k: " + k); + } +} + +public class Override4 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + BBBBBB suBbbbbb = new BBBBBB(2, 4, 6); + suBbbbbb.super.show(); + + } + +} diff --git a/Chapter7/Override5.java b/Chapter7/Override5.java new file mode 100644 index 0000000..5873d8e --- /dev/null +++ b/Chapter7/Override5.java @@ -0,0 +1,44 @@ + +class Ace{ + int i, j; + + public Ace(int a, int b) { + // TODO Auto-generated constructor stub + + i = a; + + j = b; + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class Baclofen extends Ace { + int k; + + public Baclofen(int a, int b, int c) { + super(a, b); + k = c; + } + + // display k -- this overrides show() in A + void show() { + System.out.println("k: " + k); + } +} + +public class Override5 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Ace inhibitor_Ace = new Baclofen(2, 4, 6); + inhibitor_Ace.show(); + + + } + +} diff --git a/Chapter7/Override_v_Overload.java b/Chapter7/Override_v_Overload.java new file mode 100644 index 0000000..514b8dc --- /dev/null +++ b/Chapter7/Override_v_Overload.java @@ -0,0 +1,58 @@ + +class Enchanted { + int i, j; + + public Enchanted(int a, int b) { + // TODO Auto-generated constructor stub + i = a; + j = b; + } + + void show() { + System.out.println("i and j are " + i + " " + j); + } + + void stilted () { + System.out.println("(of behavior, speech, or writing) too formal and not smooth or natural."); + } +} + +class Indebted extends Enchanted{ + + int k; + + public Indebted(int a, int b, int c) { + super(a, b); + // TODO Auto-generated constructor stub + + k = c; + } + + void show(String message) { + System.out.println(message + "\n" + "k is " + k); + } + + void stilted() { + System.out.println("(of a person's behaviour or way of speaking or writing) too formal and not smooth or natural."); + } + +} + +public class Override_v_Overload { + + public static void main(String[] args) { + Indebted indeptednessIndebted = new Indebted(1, 2, 3); + + // subclass object has two versions of show() to use, thanks to method overload. + indeptednessIndebted.show(); + indeptednessIndebted.show("subclass object has two versions of show() to use, thanks to method overload."); + + System.out.println(); + + // subclass object has only one version of stilted() to use as its own stilted() has overridden + // that of superclass. + indeptednessIndebted.stilted(); + + } + +} diff --git a/Chapter7/Override_v_Overload2.java b/Chapter7/Override_v_Overload2.java new file mode 100644 index 0000000..d4a7346 --- /dev/null +++ b/Chapter7/Override_v_Overload2.java @@ -0,0 +1,46 @@ + +class Stratify { + int i, j; + + Stratify(int a, int b){ + i = a; + j = b; + } + + // display i and j + void show() { + System.out.println("i and j: " + i + " " + j); + } +} + +class Optical_illusion extends Stratify { + + int k; + + Optical_illusion(int a, int b, int c){ + super(a, b); + + k = c; + } + + // overload show() + void show(String msg) { // Because signatures differ, this show() simply overloads show() in superclass A. + System.out.println(msg + k); + } + +} + +public class Override_v_Overload2 { + + public static void main(String[] args) { + + Stratify stratified_Stratify = new Stratify(2, 3); + + Optical_illusion illusion = new Optical_illusion(4, 5, 6); + + illusion.show(); // calling superclass' show() + illusion.show("Method overloading lets you choose a version from a various methods with the same name."); + + } + +} diff --git a/Chapter7/Override_versus_Overload.java b/Chapter7/Override_versus_Overload.java new file mode 100644 index 0000000..216da96 --- /dev/null +++ b/Chapter7/Override_versus_Overload.java @@ -0,0 +1,61 @@ +/* Methods with differing signatures are overloaded and not overridden. */ + +class Crossover { + + int i, j; + + public Crossover(int a, int b) { + + i = a; + j = b; + } + + // display i an j + void show() { + System.out.println("i and j: " + i + " " + j); + } + + // display i an j + void show2() { + System.out.println("i and j: " + i + " " + j); + } +} + +class Slice extends Crossover { + + int k; + + public Slice(int a, int b, int c) { + super(a, b); + + k = c; + } + + // Because signature differ, this show() simply overloads show() in superclass Crossover. + void show(String message) { + System.out.println(message + k); + } + + // display i an j + void show2() { + System.out.println("k: " + k ); + } +} + +public class Override_versus_Overload { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + // Check if superclass type variable can access to the subclass non-overridden method. + Crossover check_if_Superclass_variable_can_access = new Slice(1, 2, 3); + + // show() is simply overloaded. + check_if_Superclass_variable_can_access.show(); + + // show2() is overridden. + check_if_Superclass_variable_can_access.show2(); + + } + +} diff --git a/Chapter7/Polymorphism.java b/Chapter7/Polymorphism.java new file mode 100644 index 0000000..1e20cb0 --- /dev/null +++ b/Chapter7/Polymorphism.java @@ -0,0 +1,75 @@ + +class Cohesion { + + int a, b, c; + + public Cohesion(int i, int j, int k) { + // TODO Auto-generated constructor stub + + a = i; + b = j; + c = k; + } + + void polymorphy() { + + if ((b * c) > 0) { + System.out.println("A reference variable of a superclass can be assigned an object of " + + "any subclass derived from that superclass."); + } + + System.out.println(); + + if ((c * b) > 0) { + System.out.println("When a reference to a subclass object is assigned to a superclass reference variable, " + + "you will have access only to those parts of the object defined by the superclass."); + + System.out.print("It makes sense because superclass has no knowledge of what a subclass adds to it."); + } + + } + +} + +class Subversion extends Cohesion { + + int d, e, f; + + public Subversion(int i, int j, int k) { + super(i, j, k); + // TODO Auto-generated constructor stub + + d = i; + e = j; + f = k; + } + + void polymorphy() { + System.out.println("When an overridden method is called through a superclass reference variable, " + + "Java determines which version of that method to execute based upon the type of the object " + + "being referred to at the time the call occurs."); + } + +} + +public class Polymorphism { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Cohesion superCohesion = new Cohesion(2, 4, 6); + Subversion subversion = new Subversion(8, 10, 12); + + Cohesion superReferenceVariableCohesion; + + superReferenceVariableCohesion = superCohesion; + superReferenceVariableCohesion.polymorphy(); + + System.out.println("\n"); + + superReferenceVariableCohesion = subversion; + superReferenceVariableCohesion.polymorphy(); + + } + +} diff --git a/Chapter7/Rectangle.java b/Chapter7/Rectangle.java new file mode 100644 index 0000000..1fa6741 --- /dev/null +++ b/Chapter7/Rectangle.java @@ -0,0 +1,16 @@ +import Unresolved.TwoDShape; + +// A subclass of TwoDShape for rectangles. +public class Rectangle extends TwoDShape { + + boolean isSquare() { + if(width == height) + return true; + return false; + } + + double area() { + return width * height; + } + +} diff --git a/Chapter7/Rectangle11.java b/Chapter7/Rectangle11.java new file mode 100644 index 0000000..089ff04 --- /dev/null +++ b/Chapter7/Rectangle11.java @@ -0,0 +1,40 @@ +// A subclass of TwoDShape for rectangles. +public class Rectangle11 extends TwoDShape11 { + + // A default constructor. + public Rectangle11() { + super(); + } + + // Constructor for Rectangle. + Rectangle11(double w, double h) { + super(w, h, "rectangle"); // call superclass constructor. + } + + // Construct a square. + Rectangle11(double x) { + super(x, "rectangle"); // call superclass constructor. + } + + // Construct an object from an object. + Rectangle11(Rectangle11 ob) { + super(ob); // Pass object to TwoDShape constructor. + } + + boolean isSquare() { + if( getWidth() == getHeight() ) return true; + + return false; + } + + // Override area() for Rectangle. + double area() { + return getWidth() * getHeight(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/Rectangle_extends_abstract_superclass.java b/Chapter7/Rectangle_extends_abstract_superclass.java new file mode 100644 index 0000000..5127501 --- /dev/null +++ b/Chapter7/Rectangle_extends_abstract_superclass.java @@ -0,0 +1,42 @@ +// A subclass of TwoDShape for rectangles. +public class Rectangle_extends_abstract_superclass extends TwoDShape_abstract { + + // A default constructor + public Rectangle_extends_abstract_superclass() { + // TODO Auto-generated constructor stub + super(); + } + + // Constructor for Rectangle + Rectangle_extends_abstract_superclass(double w, double h){ + super(w, h, "rectangle"); // Call superclass constructor + } + + // Construct a square + Rectangle_extends_abstract_superclass(double x) { + super(x, "rectangle"); // call superclass constructor + } + + // Construct an object from an object. + Rectangle_extends_abstract_superclass(Rectangle_extends_abstract_superclass ob){ + super(ob); // pass object to TwoDShape constructor. + } + + boolean isSquare() { + + if ( getWidth() == getHeight() ) + return true; + + return false; + } + + double area() { + return getWidth() * getHeight(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/Self_Test_7_2_2.java b/Chapter7/Self_Test_7_2_2.java new file mode 100644 index 0000000..3779a7a --- /dev/null +++ b/Chapter7/Self_Test_7_2_2.java @@ -0,0 +1,28 @@ + +class geriatric{ + int a = 2; + static int b = 5; + + static int exploitation (){ + return b * 6; + } +} + +class slippery_slope extends geriatric{ + int c = a * b; + +} + + +public class Self_Test_7_2_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + slippery_slope slope = new slippery_slope(); + + System.out.println(slope.c); + + } + +} diff --git a/Chapter7/Self_Test_7_3.java b/Chapter7/Self_Test_7_3.java new file mode 100644 index 0000000..3823f41 --- /dev/null +++ b/Chapter7/Self_Test_7_3.java @@ -0,0 +1,25 @@ + +class supra_class{ + private int a = 1; + + int get(){ + return a; + } + + void amendment(int new_number){ + a = new_number; + } +} + +class elitist extends supra_class{ + int b = a * 5; +} + +public class Self_Test_7_3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/Self_Test_7_4.java b/Chapter7/Self_Test_7_4.java new file mode 100644 index 0000000..c32a052 --- /dev/null +++ b/Chapter7/Self_Test_7_4.java @@ -0,0 +1,45 @@ + +class concede { + int a; + int b; + int c; + + public concede(int d, int e, int f) { + a = d; + b = e; + c = f; + } + + void performant() { + System.out.println("This is the from superclass."); + } +} + +class secret_sauce extends concede{ + + int g = 10; + int h; + int i; + + public secret_sauce() { + super(g, h, i); + + + } + + void performant() { + super.performant(); + + System.out.println("This is from sub-class."); + } +} + + +public class Self_Test_7_4 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/Self_Test_7_4_2.java b/Chapter7/Self_Test_7_4_2.java new file mode 100644 index 0000000..9882c1b --- /dev/null +++ b/Chapter7/Self_Test_7_4_2.java @@ -0,0 +1,45 @@ + +class concession { + int a; + int b; + int c; + + public concession(int d, int e, int f) { + // TODO Auto-generated constructor stub + + a = d; + b = e; + c = f; + } + + void performant() { + System.out.println("This is the from superclass."); + } +} + +class excerpt extends concession { + + int a = 18; + int g = super.a; + + public excerpt(int d, int e, int f) { + super(d, e, f); + // TODO Auto-generated constructor stub + + System.out.println("a and super.a are " + a + ", " + g); + + } + +} + + +public class Self_Test_7_4_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + excerpt callbackExcerpt = new excerpt(1, 2, 3); + + } + +} diff --git a/Chapter7/Self_test_7_11.java b/Chapter7/Self_test_7_11.java new file mode 100644 index 0000000..06f27b0 --- /dev/null +++ b/Chapter7/Self_test_7_11.java @@ -0,0 +1,33 @@ +class A_{ + +} + +class B_ extends A_{ + + public B_() { + // TODO Auto-generated constructor stub + } + + public A_ make_ob(int which) { + // TODO Auto-generated method stub + if (which == 0) + return new A_(); + else + return new B_(); + } +} + +public class Self_test_7_11 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + B_ aversionB_ = new B_(); + + var myRef = aversionB_.make_ob(1); + + var check = myRef.make_ob(1); + + } + +} diff --git a/Chapter7/Self_test_7_14.java b/Chapter7/Self_test_7_14.java new file mode 100644 index 0000000..dce74ca --- /dev/null +++ b/Chapter7/Self_test_7_14.java @@ -0,0 +1,30 @@ + +class A__{ + +} + +class B__ extends A__{ + + public A__ makeObj (int which) { + if(which == 0) + return new A__(); + else { + return new B__(); + } + } +} + +public class Self_test_7_14 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + B__ aversionB__ = new B__(); + + var myRef = (B__) aversionB__.makeObj(1); + + var check = myRef.makeObj(0); + + } + +} diff --git a/Chapter7/Shape4.java b/Chapter7/Shape4.java new file mode 100644 index 0000000..c46ead7 --- /dev/null +++ b/Chapter7/Shape4.java @@ -0,0 +1,22 @@ + +public class Shape4 { + + public static void main(String args[]) { + + Triangle4 t1 = new Triangle4("filled", 4.0, 4.0); + Triangle4 t2 = new Triangle4("Outlined", 8.0, 12.0); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + } + +} diff --git a/Chapter7/Shape5.java b/Chapter7/Shape5.java new file mode 100644 index 0000000..f7548ef --- /dev/null +++ b/Chapter7/Shape5.java @@ -0,0 +1,23 @@ + +public class Shape5 { + + public static void main(String[] args) { + + Triangle5 t1 = new Triangle5("filled", 4.0, 4.0); + Triangle5 t2 = new Triangle5("Outlined", 8.0, 12.0); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/Shape6.java b/Chapter7/Shape6.java new file mode 100644 index 0000000..deb13ff --- /dev/null +++ b/Chapter7/Shape6.java @@ -0,0 +1,24 @@ + +public class Shape6 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Triangle6 t1 = new Triangle6(); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + Triangle6 t2 = new Triangle6("Good", 5.3, 2.0); + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/Shape7.java b/Chapter7/Shape7.java new file mode 100644 index 0000000..ff2d48c --- /dev/null +++ b/Chapter7/Shape7.java @@ -0,0 +1,36 @@ + +public class Shape7 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Triangle7 t1 = new Triangle7(); + Triangle7 t2 = new Triangle7("Outlined", 8.0, 12.0); + Triangle7 t3 = new Triangle7(4.0); + + t1 = t2 ; + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t3: "); + t3.showStyle(); + t3.showDim(); + System.out.println("Area is " + t3.area()); + + System.out.println(); + + } + +} diff --git a/Chapter7/Shape8.java b/Chapter7/Shape8.java new file mode 100644 index 0000000..a798b41 --- /dev/null +++ b/Chapter7/Shape8.java @@ -0,0 +1,24 @@ + +public class Shape8 { + + public static void main(String[] args) { + + Triangle8 t1 = new Triangle8(); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + Triangle8 t2 = new Triangle8("Good", 5.3, 8.0); + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + + } + +} diff --git a/Chapter7/Shapes.java b/Chapter7/Shapes.java new file mode 100644 index 0000000..0032f58 --- /dev/null +++ b/Chapter7/Shapes.java @@ -0,0 +1,32 @@ + +public class Shapes { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Triangle t1 = new Triangle(); + Triangle t2 = new Triangle(); + + t1.width = 4.0; + t1.height = 4.0; // All members of Triangle are available to Triangle objects, even those inherited from TwoDShape. + t1.style = "filled"; + + t2.width = 8.0; + t2.height = 12.0; + t2.style = "outlined"; + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/Shapes10.java b/Chapter7/Shapes10.java new file mode 100644 index 0000000..76e311f --- /dev/null +++ b/Chapter7/Shapes10.java @@ -0,0 +1,26 @@ + +public class Shapes10 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Triangle9 t1 = new Triangle9("outlined", 8.0, 12.0); + + // make a copy of t1. + Triangle9 t2 = new Triangle9(t1); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/Shapes3.java b/Chapter7/Shapes3.java new file mode 100644 index 0000000..926b3dc --- /dev/null +++ b/Chapter7/Shapes3.java @@ -0,0 +1,32 @@ + +public class Shapes3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Triangle3 t1 = new Triangle3(); + Triangle3 t2 = new Triangle3(); + + t1.setWidth(4.0); + t2.setHeight(4.0); + t1.styleString = "filled"; + + t2.setWidth(8.0); + t2.setHeight(12.0); + t2.styleString = "outlined"; + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/Shapes9.java b/Chapter7/Shapes9.java new file mode 100644 index 0000000..7e926c7 --- /dev/null +++ b/Chapter7/Shapes9.java @@ -0,0 +1,26 @@ + +public class Shapes9 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ColorTriangle t1 = new ColorTriangle("Blue", "Outlined", 8.0, 12.0); + ColorTriangle t2 = new ColorTriangle("Red", "filled", 2.0, 2.0); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + t1.showColor(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); // A ColorTriangle object can call methods defined by itself and its superclasses. + t2.showDim(); + t2.showColor(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/SupSubRef.java b/Chapter7/SupSubRef.java new file mode 100644 index 0000000..0084155 --- /dev/null +++ b/Chapter7/SupSubRef.java @@ -0,0 +1,44 @@ +// A superclass reference can refer to a subclass object. + +class X2 { + int a; + + public X2(int i) { + // TODO Auto-generated constructor stub + + a = i; + } +} + +class Y2 extends X2 { + int b; + + public Y2(int i, int j) { + // TODO Auto-generated constructor stub + super(j); + b = i; + } +} + +public class SupSubRef { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + X2 x = new X2(10); + X2 x2; + Y2 y = new Y2(5, 6); + + x2 = x; // OK, both of same type. + System.out.println("X2.a: " + x2.a); + + x2 = y; // still ok because Y2 is derived from X2. Both of somewhat same type. + System.out.println("X2.a: " + x2.a); + + // X references know only about X members + x2.a = 19; // OK +// x2.b = 27; // Error, X does not have a b member. + + } + +} diff --git a/Chapter7/SupSubRef2.java b/Chapter7/SupSubRef2.java new file mode 100644 index 0000000..3a9a0a3 --- /dev/null +++ b/Chapter7/SupSubRef2.java @@ -0,0 +1,41 @@ +// A superclass reference can refer to a subclass object. + +class X3 { + int a; + + public X3(int i) { + // TODO Auto-generated constructor stub + + a = i; + } +} + +class Y3 extends X3 { + int b; + + public Y3(int i, int j) { + // TODO Auto-generated constructor stub + super(j); + b = i; + } +} + +public class SupSubRef2 { + + public static void main(String[] args) { + + X3 x3 = new X3(10); + Y3 y3 = new Y3(5, 6); + + System.out.println("X.a: " + x3.a); + + x3 = y3; + System.out.println("X.a: " + x3.a); + + // X references know only about X members + x3.a = 19; // OK +// x3.b = 27; // Error, X does not have a b member. + + } + +} diff --git a/Chapter7/Triangle.java b/Chapter7/Triangle.java new file mode 100644 index 0000000..7f9bdab --- /dev/null +++ b/Chapter7/Triangle.java @@ -0,0 +1,17 @@ +import Unresolved.TwoDShape; + +// A subclass of TwoDShape for triangles. + +public class Triangle extends TwoDShape { // Triangle inherits TwoDShape + + String style; + + double area() { + return (width * height) / 2 ; // Triangle can refer to the members of TwoDShape as if they were part of Triangle. + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + +} diff --git a/Chapter7/Triangle11.java b/Chapter7/Triangle11.java new file mode 100644 index 0000000..5c85f67 --- /dev/null +++ b/Chapter7/Triangle11.java @@ -0,0 +1,48 @@ +// A subclass of TwoDShape for triangles. +public class Triangle11 extends TwoDShape11 { + + private String style; + + // A default constructor. + public Triangle11() { + // TODO Auto-generated constructor stub + super(); + style = "none"; + } + + // Constructor for Triangle. + Triangle11(String s, double w, double h){ + super(w, h, "triangle"); + + style = s; + } + + // One argument constructor + Triangle11(double x){ + super(x, "triangle"); // call superclass constructor. + + style = "filled"; + } + + // Construct an object from an object. + Triangle11(Triangle11 ob){ + super(ob); // pass object to TwoDShape constructor. + + style = ob.style; + } + + // Override area() for Triangle. + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/Triangle2.java b/Chapter7/Triangle2.java new file mode 100644 index 0000000..90d24c1 --- /dev/null +++ b/Chapter7/Triangle2.java @@ -0,0 +1,14 @@ +// This example will not compile. +public class Triangle2 { + + String style; + + double area() { + return width * height / 2; // Can't access a private member of a superclass. + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + +} diff --git a/Chapter7/Triangle2_.java b/Chapter7/Triangle2_.java new file mode 100644 index 0000000..8c2713c --- /dev/null +++ b/Chapter7/Triangle2_.java @@ -0,0 +1,19 @@ + +public class Triangle2_ extends TwoDShape2 { + + String styleString; + + double area() { + return width * height / 2; + } + + void show() { + System.out.println("Triangle is " + styleString); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/Triangle3.java b/Chapter7/Triangle3.java new file mode 100644 index 0000000..1ab7b0d --- /dev/null +++ b/Chapter7/Triangle3.java @@ -0,0 +1,14 @@ +// A subclass of TwoDShape for triangles. +public class Triangle3 extends TwoDShape3 { + + String styleString; + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle4.java b/Chapter7/Triangle4.java new file mode 100644 index 0000000..c1f10bf --- /dev/null +++ b/Chapter7/Triangle4.java @@ -0,0 +1,24 @@ +// A subclass of TwoDShape3 for triangles. +public class Triangle4 extends TwoDShape3 { + + private String styleString; + + // Constructor + public Triangle4(String s, double w, double h) { + // TODO Auto-generated constructor stub + + setWidth(w); // initialize TwoDShape3 portion of object. + setHeight(h); // initialize TwoDShape3 portion of object. + + styleString = s; + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle5.java b/Chapter7/Triangle5.java new file mode 100644 index 0000000..782c76e --- /dev/null +++ b/Chapter7/Triangle5.java @@ -0,0 +1,21 @@ +// A subclass of TwoDshape for Triangles. +public class Triangle5 extends TwoDShape5 { + + private String styleString; + + public Triangle5(String s, double w, double h) { + super(w, h); // Use super() to build the TwoDShape5 constructor. + + + styleString = s; + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle6.java b/Chapter7/Triangle6.java new file mode 100644 index 0000000..658185b --- /dev/null +++ b/Chapter7/Triangle6.java @@ -0,0 +1,47 @@ + +public class Triangle6 extends TwoDShape6 { + + private String styleString; + + // A default constructor. + public Triangle6() { + // super(); Call superclass constructor. + + styleString = "none"; + } + + /* + * If a constructor does not explicitly invoke a superclass constructor, + * the Java compiler automatically inserts a call to the no-argument constructor of the superclass. + * If the super class does not have a no-argument constructor, you will get a compile-time error. + + References: + https://web.archive.org/web/20210118184134/https://docs.oracle.com/javase/tutorial/java/IandI/super.html + + */ + + // Constructor + Triangle6(String s, double w, double h){ + // super(w, h); Use super() to call the various forms of the TwoDShape constructor. + + // width = w; + + styleString = s; + } + + // One argument constructor. + Triangle6(double x){ + // super(x); Use super() to construct the various forms of the TwoDShape constructor. + styleString = "filled"; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle7.java b/Chapter7/Triangle7.java new file mode 100644 index 0000000..42ed9ab --- /dev/null +++ b/Chapter7/Triangle7.java @@ -0,0 +1,36 @@ + +public class Triangle7 extends TwoDShape7 { + + private String styleString; + + // A default constructor. + public Triangle7() { + super(); // Call superclass constructor. + + styleString = "none"; + } + + // Constructor + Triangle7(String s, double w, double h){ + super(w, h); // Use super() to call the various forms of the TwoDShape constructor. + + styleString = s; + } + + // One argument constructor. + Triangle7(double x){ + super(x); // Use super() to construct the various forms of the TwoDShape constructor. + + styleString = "filled"; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle8.java b/Chapter7/Triangle8.java new file mode 100644 index 0000000..1a9aad8 --- /dev/null +++ b/Chapter7/Triangle8.java @@ -0,0 +1,38 @@ + +public class Triangle8 extends TwoDShape8 { + + private String styleString; + + // A default constructor. + public Triangle8() { + // super(); Call superclass constructor. + + styleString = "none"; + } + + // Constructor + Triangle8(String s, double w, double h){ + // super(w, h); Use super() to call the various forms of the TwoDShape constructor. + + width = w; + height = h; + + styleString = s; + } + + // One argument constructor. + Triangle8(double x){ + // super(x); Use super() to construct the various forms of the TwoDShape constructor. + styleString = "filled"; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle9.java b/Chapter7/Triangle9.java new file mode 100644 index 0000000..8514474 --- /dev/null +++ b/Chapter7/Triangle9.java @@ -0,0 +1,44 @@ + +public class Triangle9 extends TwoDShape9 { + + private String styleString; + + // A default constructor. + public Triangle9() { + super(); // Call superclass constructor. + + styleString = "none"; + } + + // Constructor + Triangle9(String s, double w, double h){ + super(w, h); // Use super() to call the various forms of the TwoDShape constructor. + + width = w; + height = h; + + styleString = s; + } + + // One argument constructor. + Triangle9(double x){ + super(x); // Use super() to construct the various forms of the TwoDShape constructor. + styleString = "filled"; + + } + + // Construct an object from an object. + Triangle9(Triangle9 ob){ + super(ob); // pass object to TwoDShape9 constructor, i.e., pass a Triangle9 reference to TwoDShape9's constructor. + styleString = ob.styleString; + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + +} diff --git a/Chapter7/Triangle_.java b/Chapter7/Triangle_.java new file mode 100644 index 0000000..44bc960 --- /dev/null +++ b/Chapter7/Triangle_.java @@ -0,0 +1,28 @@ +import Unresolved.TwoDShape; + +// Even though TwoDShape is a superclass for Triangle, it is also a completely independent, stand-alone class. +public class Triangle_ extends TwoDShape { + + String style; + + double area() { + return (width * height) / 2 ; // Triangle can refer to the members of TwoDShape as if they were part of Triangle. + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + TwoDShape shape = new TwoDShape(); + + shape.height = 20; + shape.width = 10; + + shape.showDim(); + + } + +} diff --git a/Chapter7/Triangle_extends_abstract_superclass.java b/Chapter7/Triangle_extends_abstract_superclass.java new file mode 100644 index 0000000..db3d058 --- /dev/null +++ b/Chapter7/Triangle_extends_abstract_superclass.java @@ -0,0 +1,50 @@ + +public class Triangle_extends_abstract_superclass extends TwoDShape_abstract { + + private String styleString; + + // A default constructor + public Triangle_extends_abstract_superclass() { + // TODO Auto-generated constructor stub + super(); + + styleString = "none"; + + } + + // Constructor for Triangle + Triangle_extends_abstract_superclass(String s, double w, double h){ + super(w, h, "triangle"); + + styleString = s; + } + + // One argument constructor. + Triangle_extends_abstract_superclass(double x){ + super(x, "triangle"); // call superclass constructor + + styleString = "filled"; + } + + // Construct an object from an object. + Triangle_extends_abstract_superclass(Triangle_extends_abstract_superclass ob){ + super(ob); // pass object to TwoDShape constructor + styleString = ob.styleString; + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + styleString); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + + + } + +} diff --git a/Chapter7/Truck.java b/Chapter7/Truck.java new file mode 100644 index 0000000..0e8e1de --- /dev/null +++ b/Chapter7/Truck.java @@ -0,0 +1,26 @@ +// Extend vehicle to create a Truck specialization. +public class Truck extends Vehicle3 { + + // This is a constructor for Truck + public Truck(int p, int f, int m, int c) { + + // Initialize Vehicle3 members using Vehicle3's constructor. + super(p, f, m); + + cargocap = c; + } + + private int cargocap; // cargo capacity in pounds. + + // Accessor methods for cargocap. + int getCargo() { + return cargocap; + } + + void putCargo(int c) { + + cargocap = c; + + } + +} diff --git a/Chapter7/TruckDemo.java b/Chapter7/TruckDemo.java new file mode 100644 index 0000000..1eb75ba --- /dev/null +++ b/Chapter7/TruckDemo.java @@ -0,0 +1,25 @@ + +public class TruckDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + // Construct some trucks. + Truck semiTruck = new Truck(2, 200, 7, 44000); + Truck pickupTruck = new Truck(3, 28, 15, 2000); + double gallons; + int dist = 252; + + gallons = semiTruck.fuelneeded(dist); + + System.out.println("SemiTruck can carry " + semiTruck.getCargo() + " pounds."); + System.out.println("To go " + dist + " miles semiTruck needs " + gallons + " gallons of fuel. \n"); + + gallons = pickupTruck.fuelneeded(dist); + + System.out.println("PickupTruck can carry " + pickupTruck.getCargo() + " pounds."); + System.out.println("To go " + dist + " miles semiTruck needs " + gallons + " gallons of fuel. \n"); + + } + +} diff --git a/Chapter7/TwoDShape.java b/Chapter7/TwoDShape.java new file mode 100644 index 0000000..80e4d82 --- /dev/null +++ b/Chapter7/TwoDShape.java @@ -0,0 +1,11 @@ + +public class TwoDShape { + + double width; + double height; + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + +} diff --git a/Chapter7/TwoDShape11.java b/Chapter7/TwoDShape11.java new file mode 100644 index 0000000..8d0bd56 --- /dev/null +++ b/Chapter7/TwoDShape11.java @@ -0,0 +1,69 @@ +// Use dynamic method dispatch. +public class TwoDShape11 { + + private double width; + private double height; + private String name; + + // A default constructor + public TwoDShape11() { + width = height = 0.0; + name = "none"; + } + + // Parameterized constructor. + TwoDShape11(double w, double h, String n){ + width = w; + height = h; + name = n; + } + + // Construct object with equal width and height. + TwoDShape11(double x, String n){ + width = height = x; + name = n; + } + + // Construct an object from an object. + TwoDShape11(TwoDShape11 ob){ + width = ob.width; + height = ob.height; + name = ob.name; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + String getName() { + return name; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + + double area() { // The area() method defined by TwoDShape + System.out.println("area() must be overridden"); + return 0.0; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/TwoDShape2.java b/Chapter7/TwoDShape2.java new file mode 100644 index 0000000..fb26876 --- /dev/null +++ b/Chapter7/TwoDShape2.java @@ -0,0 +1,12 @@ +// Private members are not inherited. + +public class TwoDShape2 { + + private double width; + private double height; + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + +} diff --git a/Chapter7/TwoDShape3.java b/Chapter7/TwoDShape3.java new file mode 100644 index 0000000..1bdcd6a --- /dev/null +++ b/Chapter7/TwoDShape3.java @@ -0,0 +1,30 @@ +// Use accessor methods to set and get private members. + +// A class for two-dimensional objects. +public class TwoDShape3 { + + private double width; + private double height; + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + +} diff --git a/Chapter7/TwoDShape5.java b/Chapter7/TwoDShape5.java new file mode 100644 index 0000000..3fe9013 --- /dev/null +++ b/Chapter7/TwoDShape5.java @@ -0,0 +1,35 @@ +// Add constructor to TwoDShape +public class TwoDShape5 { + + private double width; + private double height; + + // Parameterized constructor. + public TwoDShape5(double w, double h) { + // TODO Auto-generated constructor stub + + width = w; + height = h; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } +} diff --git a/Chapter7/TwoDShape6.java b/Chapter7/TwoDShape6.java new file mode 100644 index 0000000..8a772ea --- /dev/null +++ b/Chapter7/TwoDShape6.java @@ -0,0 +1,45 @@ +// Add more constructors to TwoDShape +public class TwoDShape6 { + + private double width; + private double height; + + // A default constructor + public TwoDShape6() { + + width = height = 0.0; + } + + // Parameterized constructor. + TwoDShape6(double w, double h){ + width = w; + height = h; + } + + // Construct object with equal width and height. + TwoDShape6(double x){ + width = height = x; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + +} diff --git a/Chapter7/TwoDShape7.java b/Chapter7/TwoDShape7.java new file mode 100644 index 0000000..17f4f16 --- /dev/null +++ b/Chapter7/TwoDShape7.java @@ -0,0 +1,46 @@ +// Add more constructors to TwoDShape +public class TwoDShape7 { + + private double width; + private double height; + + // A default constructor + public TwoDShape7() { + + width = height = 0.0; + } + + // Parameterized constructor. + TwoDShape7(double w, double h){ + width = w; + height = h; + } + + // Construct object with equal width and height. + TwoDShape7(double x){ + width = height = x; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + + +} diff --git a/Chapter7/TwoDShape8.java b/Chapter7/TwoDShape8.java new file mode 100644 index 0000000..0587bc4 --- /dev/null +++ b/Chapter7/TwoDShape8.java @@ -0,0 +1,45 @@ +// Add more constructors to TwoDShape +public class TwoDShape8 { + + double width; + double height; + + // A default constructor + public TwoDShape8() { + + width = height = 0.0; + } + + // Parameterized constructor. + TwoDShape8(double w, double h){ + width = w; + height = h; + } + + // Construct object with equal width and height. + TwoDShape8(double x){ + width = height = x; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + +} diff --git a/Chapter7/TwoDShape9.java b/Chapter7/TwoDShape9.java new file mode 100644 index 0000000..66976a3 --- /dev/null +++ b/Chapter7/TwoDShape9.java @@ -0,0 +1,51 @@ + +public class TwoDShape9 { + + double width; + double height; + + // A default constructor + public TwoDShape9() { + + width = height = 0.0; + } + + // Parameterized constructor. + TwoDShape9(double w, double h){ + width = w; + height = h; + } + + // Construct object with equal width and height. + TwoDShape9(double x){ + width = height = x; + } + + // Construct an object from an object. + TwoDShape9(TwoDShape9 ob){ + width = ob.width; + height = ob.height; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + +} diff --git a/Chapter7/TwoDShape_.java b/Chapter7/TwoDShape_.java new file mode 100644 index 0000000..42e8aea --- /dev/null +++ b/Chapter7/TwoDShape_.java @@ -0,0 +1,18 @@ +import Unresolved.TwoDShape; + +// Even though TwoDShape is a superclass, it is also a completely independent, stand-alone class. +public class TwoDShape_ extends TwoDShape { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + TwoDShape shape = new TwoDShape(); + + shape.height = 20; + shape.width = 10; + + shape.showDim(); + + } + +} diff --git a/Chapter7/TwoDShape_abstract.java b/Chapter7/TwoDShape_abstract.java new file mode 100644 index 0000000..b3bc830 --- /dev/null +++ b/Chapter7/TwoDShape_abstract.java @@ -0,0 +1,67 @@ + +public abstract class TwoDShape_abstract { + + private double width; + private double height; + private String name; + + // A default constructor + public TwoDShape_abstract() { + width = height = 0.0; + name = "none"; + } + + // Parameterized constructor. + TwoDShape_abstract(double w, double h, String n){ + width = w; + height = h; + name = n; + } + + // Construct object with equal width and height. + TwoDShape_abstract(double x, String n){ + width = height = x; + name = n; + } + + // Construct an object from an object. + TwoDShape_abstract(TwoDShape_abstract ob){ + width = ob.width; + height = ob.height; + name = ob.name; + } + + // Accessor methods for width and height. + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + String getName() { + return name; + } + + void showDim() { + System.out.println("Width and height are " + width + " and " + height); + } + + // declare an abstract method + abstract double area(); + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/UseSuper.java b/Chapter7/UseSuper.java new file mode 100644 index 0000000..78f5c1d --- /dev/null +++ b/Chapter7/UseSuper.java @@ -0,0 +1,13 @@ + +public class UseSuper { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + B suB = new B(1, 2); + + suB.show(); + + } + +} diff --git a/Chapter7/Vehicle3.java b/Chapter7/Vehicle3.java new file mode 100644 index 0000000..c5bc857 --- /dev/null +++ b/Chapter7/Vehicle3.java @@ -0,0 +1,59 @@ + +public class Vehicle3 { + + private int passengers; // number of passengers. + private int fuelcap; // fuel capacity in gallons. + private int mpg; // fuel consumption in miles per gallon. + + // Display the range. + void range() { // The range() method is contained within the Vehicle class. + System.out.println("Range is " + fuelcap * mpg); + } + + // Return the range. + int range2() { + return mpg * fuelcap; + + } + + // Compute fuel needed for a given distance. + double fuelneeded(int miles) { + return (double) miles / mpg; + } + + // This is a constructor for vehicle3 + public Vehicle3(int p, int f, int m) { + + passengers = p; + fuelcap = f; + mpg = m; + } + + // Accessor methods for instance variables. + int getPassengers() { + return passengers; + } + + void setPassengers(int p) { + passengers = p; + } + + int getFuelcap() { + return fuelcap; + } + + void setFuelcap(int f) { + fuelcap = f; + } + + int getMpg() { + return mpg; + } + + void setMpg(int m) { + + mpg = m; + + } + +} diff --git a/Chapter7/calling_superclass_member.java b/Chapter7/calling_superclass_member.java new file mode 100644 index 0000000..52e47ac --- /dev/null +++ b/Chapter7/calling_superclass_member.java @@ -0,0 +1,39 @@ + +class Super { + int i; + + void performative() { + System.out.println("Super's perfomative method."); + } +} + +class Sub extends Super { + + int a = i * 10; +// i = 10; + + void performative() { + System.out.println("Sub's performative method."); + } + + double decorative() { + return i + 1; + } + +} + +public class calling_superclass_member { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Sub sub = new Sub(); + sub.performative(); + + double catcher = sub.decorative(); + + System.out.println(catcher); + + } + +} diff --git a/Chapter7/final_prevents_inheritance.java b/Chapter7/final_prevents_inheritance.java new file mode 100644 index 0000000..f21e083 --- /dev/null +++ b/Chapter7/final_prevents_inheritance.java @@ -0,0 +1,16 @@ +final class Analogous { + +} + +class backward_looking extends Analogous { // Error! Can't subclass Analogous + +} + +public class final_prevents_inheritance { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/final_prevents_inheritance2.java b/Chapter7/final_prevents_inheritance2.java new file mode 100644 index 0000000..13ff37b --- /dev/null +++ b/Chapter7/final_prevents_inheritance2.java @@ -0,0 +1,14 @@ +final abstract civic { // It's illegal to declare a class as both abstract and final. + + // It's illegal because an abstract class is incomplete by itself and relies upon its subclasses to provide + // complete implementation. + +} +public class final_prevents_inheritance2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/final_prevents_overriding.java b/Chapter7/final_prevents_overriding.java new file mode 100644 index 0000000..70e10c1 --- /dev/null +++ b/Chapter7/final_prevents_overriding.java @@ -0,0 +1,24 @@ +class Apple { + + final void meth() { + System.out.println("This is a final method."); + } +} + +class Whistle_blower extends Apple { + +} + + +public class final_prevents_overriding { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Whistle_blower informantBlower = new Whistle_blower(); + + informantBlower.meth(); + + } + +} diff --git a/Chapter7/final_prevents_overriding2.java b/Chapter7/final_prevents_overriding2.java new file mode 100644 index 0000000..aad8fa8 --- /dev/null +++ b/Chapter7/final_prevents_overriding2.java @@ -0,0 +1,26 @@ + +class Apple2 { + final void meth() { + System.out.println("This is a final method."); + } +} + +class Whistle_blower2 extends Apple2 { + void meth(String eatString) { + System.out.println(eatString + " ( Method overload is allowed in final. )"); + } +} + +public class final_prevents_overriding2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Whistle_blower2 informantBlower2 = new Whistle_blower2(); + informantBlower2.meth("Method from Whistle blower2"); + + informantBlower2.meth(); + + } + +} diff --git a/Chapter7/final_prevents_overriding3.java b/Chapter7/final_prevents_overriding3.java new file mode 100644 index 0000000..72d4690 --- /dev/null +++ b/Chapter7/final_prevents_overriding3.java @@ -0,0 +1,25 @@ + +class Apple3 { + final void meth () { + System.out.println("This is a final method."); + } +} + +class Whistle_blower3 extends Apple3 { + void meth() { + System.out.println("Attempting to override the meth() preceded by final, in the superclass"); + } +} + +public class final_prevents_overriding3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Whistle_blower3 informantBlower3 = new Whistle_blower3(); + + informantBlower3.meth(); + + } + +} diff --git a/Chapter7/theoretical/Create_a_multilevel_hierarchy.java b/Chapter7/theoretical/Create_a_multilevel_hierarchy.java new file mode 100644 index 0000000..8c62c4a --- /dev/null +++ b/Chapter7/theoretical/Create_a_multilevel_hierarchy.java @@ -0,0 +1,20 @@ +package theoretical; + +class TwoDShape_1 { + private double width; + private double height; + + public TwoDShape_1() { + width = height = 0.0; + } + +} + +public class Create_a_multilevel_hierarchy { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/theoretical/SupSubRef.java b/Chapter7/theoretical/SupSubRef.java new file mode 100644 index 0000000..e735611 --- /dev/null +++ b/Chapter7/theoretical/SupSubRef.java @@ -0,0 +1,48 @@ +package theoretical; + +//A superclass reference can refer to a subclass object. + +class X { + + int a; + + public X(int i) { + a = i; + } +} + + +class Y extends X { + + int b; + + public Y(int i, int j) { + + super(j); + b = i; + } +} + + +public class SupSubRef { + + public static void main(String[] args) { + + X x = new X(10); + X x2; + Y y = new Y(5, 6); + + x2 = x; // OK, both of same type. + System.out.println("X2.a: " + x2.a); + System.out.println("x.a: " + x.a); + + x2 = y; // still ok because Y is derived from X. + System.out.println("X2.a: " + x2.a); + + // X references know only about X members + x2.a = 19; // OK +// x2.b = 27; // Error, X does not have a b member. + + } + +} diff --git a/Chapter7/theoretical/Super_Class_References_and_Subclass_Objects.java b/Chapter7/theoretical/Super_Class_References_and_Subclass_Objects.java new file mode 100644 index 0000000..9bc860a --- /dev/null +++ b/Chapter7/theoretical/Super_Class_References_and_Subclass_Objects.java @@ -0,0 +1,125 @@ +package theoretical; + +class TwoDShape_2{ + + private double width; + private double height; + String title; + + public TwoDShape_2(double w, double h) { + width = w; + height = h; + } + + public TwoDShape_2() { + // TODO Auto-generated constructor stub + } + + TwoDShape_2(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + // Construct object from an object. + TwoDShape_2(TwoDShape_2 ob){ + width = ob.width; + height = ob.height; + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + + void showTitle_2() { + System.out.println("Triangle is also " + title); + } + +} + + +class Triangle_2 extends TwoDShape_2{ + + private String style; + + public Triangle_2() { + // TODO Auto-generated constructor stub + } + + public Triangle_2(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangle_2(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + Triangle_2(Triangle_2 ob){ + super(ob); + } + + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTheTitle() { + + return showTitle(); + + } + + void showTheTitle_2() { + System.out.println("Triangle is also " + super.title); // super is redundant here. + } + + void showTheTitle_3() { + System.out.println("Triangle is also " + title); + } + +} + + +public class Super_Class_References_and_Subclass_Objects { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/theoretical/Super_Class_References_and_Subclass_Objects_2.java b/Chapter7/theoretical/Super_Class_References_and_Subclass_Objects_2.java new file mode 100644 index 0000000..0455ebe --- /dev/null +++ b/Chapter7/theoretical/Super_Class_References_and_Subclass_Objects_2.java @@ -0,0 +1,145 @@ +package theoretical; + +class TwoDShape_3{ + + private double width; + private double height; + String title; + + public TwoDShape_3(double w, double h) { + width = w; + height = h; + } + + public TwoDShape_3() { + // TODO Auto-generated constructor stub + } + + TwoDShape_3(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + // Construct object from an object. + TwoDShape_3(TwoDShape_3 ob){ + width = ob.width; + height = ob.height; + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + + void showTitle_2() { + System.out.println("Triangle is also " + title); + } + +} + + +class Triangle_3 extends TwoDShape_3{ + + private String style; + + public Triangle_3() { + // TODO Auto-generated constructor stub + } + + public Triangle_3(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangle_3(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + Triangle_3(Triangle_3 ob){ + super(ob); // Pass a Triangle reference to TwoDShape's constructor. + + style = ob.style; + } + + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTheTitle() { + + return showTitle(); + + } + + void showTheTitle_2() { + System.out.println("Triangle is also " + super.title); // super is redundant here. + } + + void showTheTitle_3() { + System.out.println("Triangle is also " + title); + } + +} + + +public class Super_Class_References_and_Subclass_Objects_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Triangle_3 t1 = new Triangle_3("Outlined", 8.0, 12.0); + + // make a copy of t1 + Triangle_3 t2 = new Triangle_3(t1); + + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/theoretical/Using_abstract_classes.java b/Chapter7/theoretical/Using_abstract_classes.java new file mode 100644 index 0000000..58a0fcd --- /dev/null +++ b/Chapter7/theoretical/Using_abstract_classes.java @@ -0,0 +1,38 @@ +package theoretical; + +class TwoDShape{ + private double width; + private double height; + private String name; + + public TwoDShape() { + width = height = 0.0; + name = "none"; + } + + TwoDShape(double w, double h, String n){ + width = w; + height = h; + name = n; + } + + TwoDShape(double x, String n){ + width = height = x; + name = n; + } + + TwoDShape(TwoDShape ob){ + width = ob.width; + height = ob.height; + name = ob.name; + } +} + +public class Using_abstract_classes { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter7/theoretical/Using_abstract_classes_2.java b/Chapter7/theoretical/Using_abstract_classes_2.java new file mode 100644 index 0000000..50dfcfd --- /dev/null +++ b/Chapter7/theoretical/Using_abstract_classes_2.java @@ -0,0 +1,73 @@ +package theoretical; + +abstract class TwoDShapes{ + + private double width; + private double height; + private String name; + + public TwoDShapes() { + + width = height = 0.0; + name = "none"; + } + + TwoDShapes(double w, double h, String n){ + width = w; + height = h; + name = n; + } + + TwoDShapes(double x, String n){ + width = height = x; + name = n; + } + + // Construct an object from an object. + TwoDShapes(TwoDShapes ob){ + width = ob.width; + height = ob.height; + name = ob.name; + } + + + double getWidth() { + return width; + } + + double getHeight() {return height;} + void setWidth(double w) { width = w;} + void setHeight(double h) {height = h;} + String getName() {return name;} + void showDimension() { + System.out.println("Width and height are " + width + " and " + height); + } + + // Now, area() is abstract. + abstract double area(); +} + + +class Triangle extends TwoDShapes{ + + private String style; + + public Triangle() { + // TODO Auto-generated constructor stub + super(); + style = "none"; + } + +} + + +public class Using_abstract_classes_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + + + } + +} diff --git a/Chapter7/theoretical/Using_super_to_call_superclass_constructor.java b/Chapter7/theoretical/Using_super_to_call_superclass_constructor.java new file mode 100644 index 0000000..9e3e923 --- /dev/null +++ b/Chapter7/theoretical/Using_super_to_call_superclass_constructor.java @@ -0,0 +1,83 @@ +package theoretical; + +class TwoDShaper{ + + private double width; + private double height; + + public TwoDShaper(double w, double h) { + // TODO Auto-generated constructor stub + } + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + +} + + +class Triangular extends TwoDShaper{ + + private String style; + + public Triangular(String s, double w, double h) { + super(w, h); + + style = s; + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } +} + +public class Using_super_to_call_superclass_constructor { + + public static void main(String[] args) { + + Triangular t1 = new Triangular("filled", 4.0, 4.0); + Triangular t2 = new Triangular("outlined", 8.0, 12.0); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + } + +} diff --git a/Chapter7/theoretical/Using_super_to_call_superclass_constructor_2.java b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_2.java new file mode 100644 index 0000000..1efe849 --- /dev/null +++ b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_2.java @@ -0,0 +1,122 @@ +package theoretical; + +class TwoDShaper_2{ + + private double width; + private double height; + private String title; + + public TwoDShaper_2(double w, double h) { + // TODO Auto-generated constructor stub + } + + public TwoDShaper_2() { + // TODO Auto-generated constructor stub + } + + TwoDShaper_2(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + +} + + +class Triangular_2 extends TwoDShaper_2{ + + private String style; + + public Triangular_2() { + // TODO Auto-generated constructor stub + } + + public Triangular_2(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangular_2(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTitle() { + + return showTitle(); + + } + +} + + +public class Using_super_to_call_superclass_constructor_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Triangular_2 t1 = new Triangular_2("filled", 4.0, 4.0); + Triangular_2 t2 = new Triangular_2("outlined", 8.0, 12.0); + Triangular_2 t3 = new Triangular_2("Slovenly", "Classy", 8.0, 9.0); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t3: "); + t3.showStyle(); + t3.showDim(); + t3.showTitle(); + System.out.println("Area is " + t3.area()); + } + +} diff --git a/Chapter7/theoretical/Using_super_to_call_superclass_constructor_3.java b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_3.java new file mode 100644 index 0000000..e974c2a --- /dev/null +++ b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_3.java @@ -0,0 +1,127 @@ +package theoretical; + + +class TwoDShaper_3{ + + private double width; + private double height; + private String title; + + public TwoDShaper_3(double w, double h) { + // TODO Auto-generated constructor stub + } + + public TwoDShaper_3() { + // TODO Auto-generated constructor stub + } + + TwoDShaper_3(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + +} + + + +class Triangular_3 extends TwoDShaper_3{ + + private String style; + + public Triangular_3() { + // TODO Auto-generated constructor stub + } + + public Triangular_3(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangular_3(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTheTitle() { + + return showTitle(); + + } + +} + + + +public class Using_super_to_call_superclass_constructor_3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Triangular_3 t1 = new Triangular_3("filled", 4.0, 4.0); + Triangular_3 t2 = new Triangular_3("outlined", 8.0, 12.0); + Triangular_3 t3 = new Triangular_3("Slovenly", "Classy", 8.0, 9.0); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t3: "); + t3.showStyle(); + t3.showDim(); + t3.showTitle(); + t3.showTheTitle(); + System.out.println("Area is " + t3.area()); + + } + +} diff --git a/Chapter7/theoretical/Using_super_to_call_superclass_constructor_4.java b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_4.java new file mode 100644 index 0000000..e58cc11 --- /dev/null +++ b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_4.java @@ -0,0 +1,138 @@ +package theoretical; + + +class TwoDShaper_4{ + + private double width; + private double height; + private String title; + + public TwoDShaper_4(double w, double h) { + width = w; + height = h; + } + + public TwoDShaper_4() { + // TODO Auto-generated constructor stub + } + + TwoDShaper_4(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + +} + + +class Triangular_4 extends TwoDShaper_4{ + + private String style; + + public Triangular_4() { + // TODO Auto-generated constructor stub + } + + public Triangular_4(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangular_4(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTheTitle() { + + return showTitle(); + + } + +} + + + +public class Using_super_to_call_superclass_constructor_4 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Triangular_4 t0 = new Triangular_4(); + Triangular_4 t1 = new Triangular_4("filled", 4.0, 4.0); + Triangular_4 t2 = new Triangular_4("outlined", 8.0, 12.0); + Triangular_4 t3 = new Triangular_4("Slovenly", "Classy", 8.0, 9.0); + + System.out.println("Info for t0: "); + t0.showStyle(); + t0.setHeight(9); + t0.setWidth(3); + t0.showDim(); + t0.showTitle(); + t0.showTheTitle(); + System.out.println("Area is " + t0.area()); + + System.out.println(); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t3: "); + t3.showStyle(); + t3.showDim(); + t3.showTitle(); + t3.showTheTitle(); + System.out.println("Area is " + t3.area()); + } + +} diff --git a/Chapter7/theoretical/Using_super_to_call_superclass_constructor_5.java b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_5.java new file mode 100644 index 0000000..99fdeae --- /dev/null +++ b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_5.java @@ -0,0 +1,144 @@ +package theoretical; + +class TwoDShaper_5{ + + private double width; + private double height; + String title; + + public TwoDShaper_5(double w, double h) { + width = w; + height = h; + } + + public TwoDShaper_5() { + // TODO Auto-generated constructor stub + } + + TwoDShaper_5(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + + void showTitle_2() { + System.out.println("Triangle is also " + title); + } + +} + + +class Triangular_5 extends TwoDShaper_5{ + + private String style; + + public Triangular_5() { + // TODO Auto-generated constructor stub + } + + public Triangular_5(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangular_5(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTheTitle() { + + return showTitle(); + + } + + void showTheTitle_2() { + System.out.println("Triangle is also " + super.title); + } + +} + + +public class Using_super_to_call_superclass_constructor_5 { + + public static void main(String[] args) { + Triangular_5 t0 = new Triangular_5(); + Triangular_5 t1 = new Triangular_5("filled", 4.0, 4.0); + Triangular_5 t2 = new Triangular_5("outlined", 8.0, 12.0); + Triangular_5 t3 = new Triangular_5("Slovenly", "Classy", 8.0, 9.0); + + System.out.println("Info for t0: "); + t0.showStyle(); + t0.setHeight(9); + t0.setWidth(3); + t0.showDim(); + t0.showTitle(); + t0.showTheTitle(); + System.out.println("Area is " + t0.area()); + + System.out.println(); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t3: "); + t3.showStyle(); + t3.showDim(); + t3.showTitle_2(); + t3.showTheTitle_2(); + System.out.println("Area is " + t3.area()); + + } + +} diff --git a/Chapter7/theoretical/Using_super_to_call_superclass_constructor_6.java b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_6.java new file mode 100644 index 0000000..a0f932b --- /dev/null +++ b/Chapter7/theoretical/Using_super_to_call_superclass_constructor_6.java @@ -0,0 +1,151 @@ +package theoretical; + + +class TwoDShaper_6{ + + private double width; + private double height; + String title; + + public TwoDShaper_6(double w, double h) { + width = w; + height = h; + } + + public TwoDShaper_6() { + // TODO Auto-generated constructor stub + } + + TwoDShaper_6(double width, double height, String title){ + + this.width = width; + this.height = height; + this.title = title; + + } + + + double getWidth() { + return width; + } + + double getHeight() { + return height; + } + + void setWidth(double w) { + width = w; + } + + void setHeight(double h) { + height = h; + } + + void showDim() { + + System.out.println("Width and height are " + width + " and " + height); + } + + String showTitle() { + return title; + } + + void showTitle_2() { + System.out.println("Triangle is also " + title); + } + +} + + +class Triangular_6 extends TwoDShaper_6{ + + private String style; + + public Triangular_6() { + // TODO Auto-generated constructor stub + } + + public Triangular_6(String s, double w, double h) { + super(w, h); + + style = s; + } + + Triangular_6(String style, String title, double width, double height){ + + super(width, height, title); + + this.style = style; + + } + + double area() { + return getWidth() * getHeight() / 2; + } + + void showStyle() { + System.out.println("Triangle is " + style); + } + + String showTheTitle() { + + return showTitle(); + + } + + void showTheTitle_2() { + System.out.println("Triangle is also " + super.title); // super is redundant here. + } + + void showTheTitle_3() { + System.out.println("Triangle is also " + title); + } + +} + + +public class Using_super_to_call_superclass_constructor_6 { + + public static void main(String[] args) { + + Triangular_6 t0 = new Triangular_6(); + Triangular_6 t1 = new Triangular_6("filled", 4.0, 4.0); + Triangular_6 t2 = new Triangular_6("outlined", 8.0, 12.0); + Triangular_6 t3 = new Triangular_6("Slovenly", "Classy", 8.0, 9.0); + + System.out.println("Info for t0: "); + t0.showStyle(); + t0.setHeight(9); + t0.setWidth(3); + t0.showDim(); + t0.showTitle(); + t0.showTheTitle(); + System.out.println("Area is " + t0.area()); + + System.out.println(); + + System.out.println("Info for t1: "); + t1.showStyle(); + t1.showDim(); + System.out.println("Area is " + t1.area()); + + System.out.println(); + + System.out.println("Info for t2: "); + t2.showStyle(); + t2.showDim(); + System.out.println("Area is " + t2.area()); + + System.out.println(); + + System.out.println("Info for t3: "); + t3.showStyle(); + t3.showDim(); + t3.showTitle_2(); + t3.showTheTitle_2(); + t3.showTheTitle_3(); + System.out.println("Area is " + t3.area()); + + } + +} diff --git a/Chapter8/Interface/ByThrees.java b/Chapter8/Interface/ByThrees.java new file mode 100644 index 0000000..eb0b095 --- /dev/null +++ b/Chapter8/Interface/ByThrees.java @@ -0,0 +1,34 @@ +package Interface; + +public class ByThrees implements Series { + + int start; + int val; + + public ByThrees() { + // TODO Auto-generated constructor stub + start = 0; + val = 0; + } + + @Override + public int getNext() { + // TODO Auto-generated method stub + val += 3; + return val; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + val = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + val = x; + } + +} diff --git a/Chapter8/Interface/ByTwo.java b/Chapter8/Interface/ByTwo.java new file mode 100644 index 0000000..32795e1 --- /dev/null +++ b/Chapter8/Interface/ByTwo.java @@ -0,0 +1,21 @@ +package Interface; + +public class ByTwo implements Series { + + int start; + int val; + + public int getNext() { + val += 2; + return val; + } + + public void reset() { + + } + + public void setStart(int x) { + + } + +} diff --git a/Chapter8/Interface/ICharQ.java b/Chapter8/Interface/ICharQ.java new file mode 100644 index 0000000..4e2c8d9 --- /dev/null +++ b/Chapter8/Interface/ICharQ.java @@ -0,0 +1,10 @@ +package Interface; + +public class ICharQ { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter8/Interface/IQDemo.java b/Chapter8/Interface/IQDemo.java new file mode 100644 index 0000000..5cc181a --- /dev/null +++ b/Chapter8/Interface/IQDemo.java @@ -0,0 +1,10 @@ +package Interface; + +public class IQDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter8/Interface/Implementing_Interfaces.java b/Chapter8/Interface/Implementing_Interfaces.java new file mode 100644 index 0000000..d70a107 --- /dev/null +++ b/Chapter8/Interface/Implementing_Interfaces.java @@ -0,0 +1,212 @@ +package Interface; + +//An interface specifies what must be done, but not how to get it done. +interface Series4{ + + int getNext(); + void reset(); + void setStart(int x); +} + + +//Implement Series. +class ByTwos2_ implements Series4{ + + // It's both permissible and common for classes that implement interfaces to define additional members + // of their own. (It absolutely is. Without it, how to implement methods in an interface?) + int start; + int value; + + public ByTwos2_() { + start = 0; + value = 0; + } + + // Whenever you implement a method defined by an interface, it must be implemented as public; + // because all members of an interface are implicitly public. + public int getNext() { + value += 2; + return value; + } + + public void reset() { + value = start; + } + + @Override + public void setStart(int x) { + + start = x; + value = x; + + } +} + + +class ByTwos4 implements Series4{ + int start; + int value; + int previous; + + public ByTwos4() { + start = 0; + value = 0; + } + + ByTwos4(int previous) { + + this.previous = previous; + + start = 0; + value = 0; + } + + // Whenever you implement a method defined by an interface, it must be implemented as public; + // because all members of an interface are implicitly public. + public int getNext() { + value += 2; + return value; + } + + public void reset() { + value = start; + } + + @Override + public void setStart(int x) { + + start = x; + value = x; + + } + + // Even though the interface does not define this method, it's both permissible and common for classes + // that implement interfaces to define additional members of their own. + int getPrevious() { + return previous; + } +} + + +class ByThrees2 implements Series4{ // implement Series in a different way. + int start; + int value; + + ByThrees2() { + // TODO Auto-generated constructor stub + start = 0; + value = 0; + } + + public int getNext() { + value += 3; + return value; + } + + public void reset() { + value = start; + } + + public void setStart(int x) { + start = x; + value = x; + } +} + + +// If a class includes an interface but does not fully implement the methods defined by that interface, then +// that class must be declared as abstract. +abstract class implicate implements Series4{ + + int start; + + public void setStart(int start) { + this.start = start; + } + +} + + +public class Implementing_Interfaces { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ByTwos2_ oByTwos2_ = new ByTwos2_(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByTwos2_.getNext()); + } + + System.out.println("\nResetting"); + + oByTwos2_.reset(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByTwos2_.getNext()); + } + + System.out.println("\nStarting at 100"); + + oByTwos2_.setStart(100); + + for (int i = 0; i < 5; i++) { + + System.out.println("Next value is " + oByTwos2_.getNext()); + } + + System.out.println(); + + ByTwos4 oByTwos4 = new ByTwos4(9); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByTwos4.getNext()); + } + + System.out.println("\nResetting"); + + oByTwos4.reset(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByTwos4.getNext()); + } + + System.out.println("\nStarting at 100"); + + oByTwos4.setStart(100); + + for (int i = 0; i < 5; i++) { + + System.out.println("Next value is " + oByTwos4.getNext()); + } + + System.out.println(); + + ByThrees2 oByThrees2 = new ByThrees2(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByThrees2.getNext()); + } + + System.out.println("\nResetting"); + + oByThrees2.reset(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByThrees2.getNext()); + } + + System.out.println("\nStarting at 100"); + + oByThrees2.setStart(100); + + for (int i = 0; i < 5; i++) { + + System.out.println("Next value is " + oByThrees2.getNext()); + } + + System.out.println(); + + } + +} diff --git a/Chapter8/Interface/Implementing_Interfaces_implement_clause.java b/Chapter8/Interface/Implementing_Interfaces_implement_clause.java new file mode 100644 index 0000000..ec8178e --- /dev/null +++ b/Chapter8/Interface/Implementing_Interfaces_implement_clause.java @@ -0,0 +1,59 @@ +package Interface; + +// An interface specifies what to do, not how to do. +interface management{ + + void parenting(); + void baby_talks(); + + +} + +class parents { + + String fatherString; + String motherString; + +} + +// The general form of a class that includes the implements clause looks like this: +class kids extends parents implements management{ + + @Override + public void parenting() { + // TODO Auto-generated method stub + System.out.println(fatherString + "'s fatherhood"); + } + + @Override + public void baby_talks() { + // TODO Auto-generated method stub + System.out.println( motherString + "'s motherese"); + } + +} + + +public class Implementing_Interfaces_implement_clause { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + kids janeKids = new kids(); + kids peterKids = new kids(); + + janeKids.fatherString = "Jansen"; + janeKids.motherString = "Sharon"; + janeKids.baby_talks(); + janeKids.parenting(); + + + peterKids.fatherString = "Bill"; + peterKids.motherString = "Laura"; + peterKids.baby_talks(); + peterKids.parenting(); + + + } + +} diff --git a/Chapter8/Interface/Interfaces_Can_Be_Extended.java b/Chapter8/Interface/Interfaces_Can_Be_Extended.java new file mode 100644 index 0000000..69c49e7 --- /dev/null +++ b/Chapter8/Interface/Interfaces_Can_Be_Extended.java @@ -0,0 +1,51 @@ +package Interface; + +// One interface can extend another. +interface A{ + + void meth1(); + void meth2(); +} + +// B now includes meth1() and meth2() - it adds meth3(). +interface B extends A{ // B inherits A. + void meth3(); +} + +// This class must implement all of A and B +class MyClass implements B{ + + @Override + public void meth1() { + // TODO Auto-generated method stub + System.out.println("Implement meth1(). "); + } + + @Override + public void meth2() { + // TODO Auto-generated method stub + System.out.println("Implement meth2(). "); + } + + @Override + public void meth3() { + // TODO Auto-generated method stub + System.out.println("Implement meth3(). "); + } +} + + +public class Interfaces_Can_Be_Extended { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + MyClass obMyClass = new MyClass(); + + obMyClass.meth1(); + obMyClass.meth2(); + obMyClass.meth3(); + + } + +} diff --git a/Chapter8/Interface/Partial_Implementation.java b/Chapter8/Interface/Partial_Implementation.java new file mode 100644 index 0000000..8677c7a --- /dev/null +++ b/Chapter8/Interface/Partial_Implementation.java @@ -0,0 +1,47 @@ +package Interface; + +// If a class includes an interface but does not fully implement the methods defined by that interface, then that class +// must be declared as abstract. +abstract class mouthpiece implements Series { + + public void reset() { + + } + + public void setStart() { + + } +} + +// The subclasses of the abstract class can provide the remaining implementations. +class Redress extends mouthpiece { + + int current = 0; + int next = 0; + + public int getNext() { + next = current + 1; + + return next; + } + + // The type signature of the implementing method must match exactly the type signature specified in the interface. + public void setStart(int x) { + current = x; + } +} + +public class Partial_Implementation { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Redress redress = new Redress(); + + redress.setStart(5); + + System.out.println(redress.getNext()); + + } + +} diff --git a/Chapter8/Interface/Series.java b/Chapter8/Interface/Series.java new file mode 100644 index 0000000..33c4f46 --- /dev/null +++ b/Chapter8/Interface/Series.java @@ -0,0 +1,8 @@ +package Interface; + +public interface Series { + int getNext(); // return next number in series. + void reset(); // restart. + void setStart(int x); // set starting value. + +} diff --git a/Chapter8/Interface/SeriesDemo.java b/Chapter8/Interface/SeriesDemo.java new file mode 100644 index 0000000..91bcb84 --- /dev/null +++ b/Chapter8/Interface/SeriesDemo.java @@ -0,0 +1,61 @@ +package Interface; + +class ByTwos implements Series { + + int start; + int val; + + public ByTwos() { + // TODO Auto-generated constructor stub + start = 0; + val = 0; + } + + @Override + public int getNext() { + // TODO Auto-generated method stub + val += 2; + return val; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + val = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + val = x; + } + +} + +public class SeriesDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ByTwos obByTwos = new ByTwos(); + + for (int i = 0; i < 5; i++) + System.out.println("Next value is " + obByTwos.getNext()); + + System.out.println("\nResetting"); + obByTwos.reset(); + + for (int i = 0; i < 5; i++) + System.out.println("Next value is " + obByTwos.getNext()); + + System.out.println("\nStarting at 100"); + + obByTwos.setStart(100); + + for (int i = 0; i < 5; i++) + System.out.println("Next value is " + obByTwos.getNext()); + + } + +} diff --git a/Chapter8/Interface/SeriesDemo2.java b/Chapter8/Interface/SeriesDemo2.java new file mode 100644 index 0000000..5664c58 --- /dev/null +++ b/Chapter8/Interface/SeriesDemo2.java @@ -0,0 +1,59 @@ +package Interface; + +class ByTwo2 implements Series { + + int start = 0; + int val = 0; + + public ByTwo2() { + // TODO Auto-generated constructor stub + } + + @Override + public int getNext() { + // TODO Auto-generated method stub + val += 2; + return val; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + val = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + val = x; + } + +} + +public class SeriesDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ByTwo2 obByTwos = new ByTwo2(); + + for (int i = 0; i < 5; i++) + System.out.println("Next value is " + obByTwos.getNext()); + + System.out.println("\nResetting"); + obByTwos.reset(); + + for (int i = 0; i < 5; i++) + System.out.println("Next value is " + obByTwos.getNext()); + + System.out.println("\nStarting at 100"); + + obByTwos.setStart(100); + + for (int i = 0; i < 5; i++) + System.out.println("Next value is " + obByTwos.getNext()); + + } + +} diff --git a/Chapter8/Interface/SeriesDemo2_Interface_Reference.java b/Chapter8/Interface/SeriesDemo2_Interface_Reference.java new file mode 100644 index 0000000..caaa47e --- /dev/null +++ b/Chapter8/Interface/SeriesDemo2_Interface_Reference.java @@ -0,0 +1,78 @@ +package Interface; + +class ByTwos_instinct implements Series { + + int start = 0; + int val = 0; + + @Override + public int getNext() { + val += 2; + return val; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + val = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + val = x; + } + +} + +class ByThrees_instinct implements Series { + + int start = 0; + int val = 0; + + @Override + public int getNext() { + val += 3; + return val; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + val = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + val = x; + } + +} + +public class SeriesDemo2_Interface_Reference { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ByTwos_instinct twos_instinct = new ByTwos_instinct(); + + ByThrees_instinct threes_instinct = new ByThrees_instinct(); + + Series refSeries; + + for (int i = 0; i < 5; i++) { + refSeries = twos_instinct; + + System.out.println("Next ByTwos value is " + refSeries.getNext()); + + refSeries = threes_instinct; + + System.out.println("Next ByThrees value is " + refSeries.getNext()); + } + + } + +} diff --git a/Chapter8/Interface/SeriesDemo3.java b/Chapter8/Interface/SeriesDemo3.java new file mode 100644 index 0000000..82fcd28 --- /dev/null +++ b/Chapter8/Interface/SeriesDemo3.java @@ -0,0 +1,65 @@ +package Interface; + +interface ad_hoc_Series { + int getNext(); + void reset(); + void setStart(int x); +} + +class Sniff_ByTwos implements ad_hoc_Series { + + int start = 0; + int value = 0; + + // The method that implements an interface must be declared as public. + public int getNext() { + + value += 2; + + return value; + + } + + public void reset() { + value = start; + } + + public void setStart(int x) { + start = x; + value = x; + } + +} + + +public class SeriesDemo3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Sniff_ByTwos sniff_ByTwos = new Sniff_ByTwos(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + sniff_ByTwos.getNext()); + } + + System.out.println("\nResetting "); + + sniff_ByTwos.reset(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + sniff_ByTwos.getNext()); + } + + System.out.println("\nStarting at 100"); + + sniff_ByTwos.setStart(100); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + sniff_ByTwos.getNext()); + } + + + } + +} diff --git a/Chapter8/Interface/SeriesDemo4.java b/Chapter8/Interface/SeriesDemo4.java new file mode 100644 index 0000000..b1e921e --- /dev/null +++ b/Chapter8/Interface/SeriesDemo4.java @@ -0,0 +1,51 @@ + +package Interface; + +// It is both permissible and common for classes that implement interfaces to define additional members of their own. +class Sniff_ByTwo implements Series { + + int value = 0; + int start = 0; + + int previous = -2; + + public int getNext() { + previous = value; + value += 2; + + return value; + } + + public void reset() { + value = 0; + start = 0; + previous = start - 2; + } + + public void setStart(int x) { + start = x; + value = x; + previous = x - 2; + } + + // Add a method not defined by Series. + int getPrevious() { + return previous; + } +} + +public class SeriesDemo4 { + + public static void main(String[] args) { + + + Sniff_ByTwo sniff_ByTwo = new Sniff_ByTwo(); + + System.out.print(sniff_ByTwo.getPrevious()); + + sniff_ByTwo.setStart(8); + + System.out.println("\n" + sniff_ByTwo.getPrevious()); + } + +} diff --git a/Chapter8/Interface/SeriesDemo_.java b/Chapter8/Interface/SeriesDemo_.java new file mode 100644 index 0000000..81e6319 --- /dev/null +++ b/Chapter8/Interface/SeriesDemo_.java @@ -0,0 +1,47 @@ +package Interface; + +class ByTwos_ implements Series { + + int start = 0; + int val = 0; + int prev = -2; + + public ByTwos_() { + // TODO Auto-generated constructor stub + } + + @Override + public int getNext() { + // TODO Auto-generated method stub + val += 2; + return val; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + val = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + val = x; + } + + // It is both permissible and common for classes that implement interfaces to define additional members of their own. + int getPrevious() { // Add a method not defined by Series. + return prev; + } + +} + +public class SeriesDemo_ { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter8/Interface/Series_Demo.java b/Chapter8/Interface/Series_Demo.java new file mode 100644 index 0000000..8e259e4 --- /dev/null +++ b/Chapter8/Interface/Series_Demo.java @@ -0,0 +1,71 @@ +package Interface; + +// An interface specifies what must be done, but not how to do it. +interface Series2{ + + int getNext(); + void reset(); + void setStart(int x); +} + + +// Implement Series. +class ByTwos2 implements Series2{ + int start; + int value; + + public ByTwos2() { + start = 0; + value = 0; + } + + // Whenever you implement a method defined by an interface, it must be implemented as public; + // because all members of an interface are implicitly public. + public int getNext() { + value += 2; + return value; + } + + public void reset() { + value = start; + } + + @Override + public void setStart(int x) { + + start = x; + value = x; + + } +} + +public class Series_Demo { + + public static void main(String[] args) { + + ByTwos2 oByTwos2 = new ByTwos2(); + + for (int i = 0; i < 5; i++) { + + System.out.println("Next value is " + oByTwos2.getNext()); + } + + System.out.println("\nResetting"); + + oByTwos2.reset(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByTwos2.getNext()); + } + + System.out.println("\nStarting at 100"); + + oByTwos2.setStart(100); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + oByTwos2.getNext()); + } + + } + +} diff --git a/Chapter8/Interface/Series_Demo2.java b/Chapter8/Interface/Series_Demo2.java new file mode 100644 index 0000000..cc89a73 --- /dev/null +++ b/Chapter8/Interface/Series_Demo2.java @@ -0,0 +1,86 @@ +package Interface; + +//An interface specifies what must be done, but not how to do it. +interface Series3{ + + int getNext(); + void reset(); + void setStart(int x); +} + + +//Implement Series. +class ByTwos3 implements Series3{ + int start; + int value; + int previous; + + public ByTwos3() { + start = 0; + value = 0; + } + + ByTwos3(int previous) { + + this.previous = previous; + + start = 0; + value = 0; + } + + // Whenever you implement a method defined by an interface, it must be implemented as public; + // because all members of an interface are implicitly public. + public int getNext() { + value += 2; + return value; + } + + public void reset() { + value = start; + } + + @Override + public void setStart(int x) { + + start = x; + value = x; + + } + + int getPrevious() { + return previous; + } +} + +public class Series_Demo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ByTwos3 obByTwos3 = new ByTwos3(9); + + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + obByTwos3.getNext()); + } + + System.out.println("\nResetting"); + + obByTwos3.reset(); + + for (int i = 0; i < 5; i++) { + System.out.println("Next value is " + obByTwos3.getNext()); + } + + System.out.println("\nStarting at 100"); + + obByTwos3.setStart(100); + + for (int i = 0; i < 5; i++) { + + System.out.println("Next value is " + obByTwos3.getNext()); + } + + } + +} diff --git a/Chapter8/Interface/Using_Interface_References.java b/Chapter8/Interface/Using_Interface_References.java new file mode 100644 index 0000000..fd89725 --- /dev/null +++ b/Chapter8/Interface/Using_Interface_References.java @@ -0,0 +1,98 @@ +package Interface; + +// An interface specifies what to do, not how to do. +interface Seriess{ + int getNext(); + void reset(); + void setStart(int x); +} + +class ByTwoss implements Seriess{ + + int start; + int value; + + public ByTwoss() { + start = 0; + value = 0; + } + + @Override + public int getNext() { + value += 2; + return value; + } + + @Override + public void reset() { + value = start; + + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + value = x; + } + +} + + +class ByThreess implements Seriess{ + + int start; + int value; + + public ByThreess() { + start = 0; + value = 0; + } + + @Override + public int getNext() { + + value += 3; + + return value; + } + + @Override + public void reset() { + // TODO Auto-generated method stub + value = start; + } + + @Override + public void setStart(int x) { + // TODO Auto-generated method stub + start = x; + value = x; + } + +} + + +public class Using_Interface_References { + + public static void main(String[] args) { + + ByTwoss twoOb = new ByTwoss(); + ByThreess threeOb = new ByThreess(); + Seriess ob; + + for (int i = 0; i < 5; i++) { + + ob = twoOb; + + System.out.println("Next ByTwos value is " + ob.getNext()); + + ob = threeOb; + + System.out.println("Next ByThrees value is " + ob.getNext()); + + } + + } + +} diff --git a/Chapter8/Interface/default_method_fundamentals.java b/Chapter8/Interface/default_method_fundamentals.java new file mode 100644 index 0000000..7249806 --- /dev/null +++ b/Chapter8/Interface/default_method_fundamentals.java @@ -0,0 +1,43 @@ +package Interface; + +interface MyIF{ + + // This is a "normal" interface method declaration. + // It does NOT define a default implementation. + int getUserID(); + + + // This is a default method. Notice that it provides a default implementation. + default int getAdminID() { + return 1; + } +} + + +class MyIFImp implements MyIF{ + + // Only getUserID() defined by MyIF needs to be implemented. getAdminID() can be allowed to default. + public int getUserID() { + + return 100; + + } + +} + + +public class default_method_fundamentals { + + public static void main(String[] args) { + + MyIFImp obj = new MyIFImp(); + + // Can call getUserID(), because it is explicitly implemented by MyIFImp: + System.out.println("User ID is " + obj.getUserID()); + + // Can also call getAdminID(), because of default implementation: + System.out.println("Administrator ID is " + obj.getAdminID()); + + } + +} diff --git a/Chapter8/Methods_in_an_interface_are_implicitly_public.java b/Chapter8/Methods_in_an_interface_are_implicitly_public.java new file mode 100644 index 0000000..8ccd9b7 --- /dev/null +++ b/Chapter8/Methods_in_an_interface_are_implicitly_public.java @@ -0,0 +1,18 @@ + +class frown { + + private int getNext() { + System.out.println("getNext() ought to be overridden."); + return 1; + } + +} + +public class Methods_in_an_interface_are_implicitly_public { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter8/Series.java b/Chapter8/Series.java new file mode 100644 index 0000000..b429554 --- /dev/null +++ b/Chapter8/Series.java @@ -0,0 +1,7 @@ + +public interface Series { + int getNext(); // Return next number in series + void reset(); // Restart + void setStart(int x); // set starting value + +} diff --git a/Chapter8/Try_This_8_1.java b/Chapter8/Try_This_8_1.java new file mode 100644 index 0000000..542eb47 --- /dev/null +++ b/Chapter8/Try_This_8_1.java @@ -0,0 +1,225 @@ +// A character queue interface + +interface ICharQ{ + + // Put a character into the queue. + void put(char ch); + + // Get a character from the queue. + char get(); +} + + +// A fixed-size queue class for characters. +class FixedQueue implements ICharQ{ + + private char q[]; // This array holds the queue. + private int putloc, getloc; // The put and get indices. + + public FixedQueue(int size) { + q = new char[size]; // allocate memory for queue. + + putloc = getloc = 0; + } + + public void put(char ch) { + if(putloc == q.length) { + System.out.println(" - Queue is full."); + return; + } + + q[putloc++] = ch; + } + + public char get() { + + if (getloc == putloc) { + System.out.println(" - Queue is empty."); + + return (char) 0; + } + return q[getloc++]; + } + +} + +class CircularQueue implements ICharQ{ + private char q[]; // this array holds the queue. + private int putloc, getloc; // the put and get indices. + + // Construct an empty queue given its size. + public CircularQueue(int size) { + q = new char[size + 1]; // allocate memory for queue + putloc = getloc = 0; + } + + public void put(char ch) { + /* + * Queue is full if either putloc is one less than getloc, + * or if putloc is at the end of the array and getloc is at + * the beginning. + * */ + + if (putloc + 1 == getloc | ((putloc == q.length - 1) & (getloc == 0))) { + System.out.println(" - Queue is full. "); + return; + } + + q[putloc++] = ch; + + if (putloc == q.length) { + putloc = 0; + } + + } + + public char get() { + // TODO Auto-generated method stub + if (getloc == putloc) { + System.out.println(" - Queue is empty."); + return (char) 0; + } + + char ch = q[getloc++]; + + if (getloc == q.length) { + getloc = 0; + } + + return ch; + } +} + + +class DynQueue implements ICharQ{ + + private char q[]; + private int putloc, getloc; + + public DynQueue(int size) { + q = new char[size]; + putloc = getloc = 0; + } + + + public void put(char ch) { + // TODO Auto-generated method stub + + if (putloc == q.length) { + // increase queue size + char t[] = new char[q.length * 2]; + + // copy elements into new queue + for (int i = 0; i < q.length; i++) { + + t[i] = q[i]; + } + + q = t; + } + + q[putloc++] = ch; + } + + + public char get() { + + if (getloc == putloc) { + System.out.println(" - Queue is empty."); + return (char) 0; + } + + return q[getloc++]; + + } + +} + + +public class Try_This_8_1 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + FixedQueue q1 = new FixedQueue(10); + DynQueue q2 = new DynQueue(5); + CircularQueue q3 = new CircularQueue(10); + + ICharQ iQ; + + char ch; + int i; + + iQ = q1; + + // Put some characters into fixed queue. + for (i = 0; i < 10; i++) { + iQ.put((char) ('A' + i)); + } + + // Show the queue. + System.out.print("Contents of fixed queue: "); + + for (i = 0; i < 10; i++) { + ch = iQ.get(); + System.out.print(ch); + } + + System.out.println(); + + iQ = q2; + + // Put some characters into dynamic queue. + for (i = 0; i < 10; i++) { + iQ.put((char) ('Z' - i)); + } + + // Show the queue. + System.out.print("Contents of dynamic queue: "); + for (i = 0; i < 10; i++) { + ch = iQ.get(); + System.out.print(ch); + } + + System.out.println(); + + iQ = q3; + + // Put some characters into circular queue. + for (i = 0; i < 10; i++) { + iQ.put((char) ('A' + i)); + } + + // Show the queue. + System.out.print("Contents of circular queue: "); + for (i = 0; i < 10; i++) { + ch = iQ.get(); + System.out.print(ch); + } + + System.out.println(); + + // Put more characters into circular queue. + for (i = 10; i < 20; i++) { + iQ.put((char) ('A' + i)); + } + + // Show the queue. + System.out.print("Contents of circular queue: "); + for (i = 0; i < 10; i++) { + ch = iQ.get(); + System.out.print(ch); + } + + System.out.println("\nStore and consume from" + " circular queue."); + + // Store in and consume from circular queue. + for (i = 0; i < 20; i++) { + iQ.put((char) ('A' + i)); + ch = iQ.get(); + System.out.print(ch); + } + + } + +} diff --git a/Chapter8/bookpack/Book3.java b/Chapter8/bookpack/Book3.java new file mode 100644 index 0000000..e54e02c --- /dev/null +++ b/Chapter8/bookpack/Book3.java @@ -0,0 +1,23 @@ +package bookpack; + +public class Book3 { + + private String titleString; + private String authorString; + private int pubDate; + + // Now public. + public Book3(String t, String a, int d) { + titleString = t; + authorString = a; + pubDate = d; + } + + public void show() { + System.out.println(titleString); + System.out.println(authorString); + System.out.println(pubDate); + System.out.println(); + } + +} diff --git a/Chapter8/bookpack/BookDemo.java b/Chapter8/bookpack/BookDemo.java new file mode 100644 index 0000000..5db19ea --- /dev/null +++ b/Chapter8/bookpack/BookDemo.java @@ -0,0 +1,44 @@ +// A short package demonstration. + +package bookpack; // This file is part of bookpack package. + +class Book { // Thus, Book is part of bookpack. + private String titleString; + private String authorString; + private int pubDate; + + public Book(String t, String a, int d) { + // TODO Auto-generated constructor stub + titleString = t; + authorString = a; + pubDate = d; + } + + void show() { + System.out.println(titleString); + System.out.println(authorString); + System.out.println(pubDate); + System.out.println(); + } +} + +public class BookDemo { // BookDemo is also part of bookpack. + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Book booksBook[] = new Book[5]; + + booksBook[0] = new Book("Java: A Beginner's Guide", "Schildt", 2019); + booksBook[1] = new Book("Java: The Complete Reference", "Schildt", 2019); + booksBook[2] = new Book("Introducing JavaFX 8 Programming", "Schildt", 2015); + booksBook[3] = new Book("Red Storm Rising", "Clancy", 1986); + booksBook[4] = new Book("On the Road", "Kerouac", 1955); + + for (int i = 0; i < booksBook.length; i++) { + booksBook[i].show(); + } + + } + +} diff --git a/Chapter8/bookpack/BookDemo2.java b/Chapter8/bookpack/BookDemo2.java new file mode 100644 index 0000000..f506972 --- /dev/null +++ b/Chapter8/bookpack/BookDemo2.java @@ -0,0 +1,33 @@ +// Book recorded for public use. + +package bookpack; + +class Book2{ + private String titleString; + private String authorString; + private int pubDate; + + // Now public. + public Book2(String t, String a, int d) { + titleString = t; + authorString = a; + pubDate = d; + } + + public void show() { + System.out.println(titleString); + System.out.println(authorString); + System.out.println(pubDate); + System.out.println(); + } + +} + +public class BookDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter8/bookpack/ProtectedBook.java b/Chapter8/bookpack/ProtectedBook.java new file mode 100644 index 0000000..7d48c29 --- /dev/null +++ b/Chapter8/bookpack/ProtectedBook.java @@ -0,0 +1,29 @@ +package bookpack; + +class ProtectedBook { + + protected String titleString; + protected String authorString; + protected int pubDate; + + public ProtectedBook(String t, String a, int p) { + // TODO Auto-generated constructor stub + + titleString = t; + authorString = a; + pubDate = p; + } + + public void show() { + System.out.println(titleString); + System.out.println(authorString); + System.out.println(pubDate); + System.out.println(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Chapter8/bookpack/ProtectedBook2.java b/Chapter8/bookpack/ProtectedBook2.java new file mode 100644 index 0000000..cfa4d60 --- /dev/null +++ b/Chapter8/bookpack/ProtectedBook2.java @@ -0,0 +1,24 @@ +package bookpack; + +public class ProtectedBook2 { + + protected String titleString; + protected String authorString; + protected int pubDate; + + public ProtectedBook2(String t, String a, int p) { + // TODO Auto-generated constructor stub + + titleString = t; + authorString = a; + pubDate = p; + } + + public void show() { + System.out.println(titleString); + System.out.println(authorString); + System.out.println(pubDate); + System.out.println(); + } + +} diff --git a/Chapter8/bookpackext/ExtBook.java b/Chapter8/bookpackext/ExtBook.java new file mode 100644 index 0000000..1ef3f1b --- /dev/null +++ b/Chapter8/bookpackext/ExtBook.java @@ -0,0 +1,52 @@ +package bookpackext; + +public class ExtBook extends bookpack.ProtectedBook2 { + + private String publisher; + + public ExtBook(String t, String a, int p, String publisher) { + super(t, a, p); + // TODO Auto-generated constructor stub + this.publisher = publisher; + } + + public void show() { + super.show(); + System.out.println(publisher); + System.out.println(); + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String p) { + publisher = p; + } + + // These are OK because subclass can access a protected member. + public String getTitle() { + return titleString; + } + + public void setTitle(String t) { + titleString = t; + } + + public String getAuthorString() { + return authorString; + } + + public void setAuthor(String a) { + authorString = a; + } + + public int getPubDate() { + return pubDate; + } + + public void setPubDate(int d) { + pubDate = d; + } + +} diff --git a/Chapter8/bookpackext/ProtectDemo.java b/Chapter8/bookpackext/ProtectDemo.java new file mode 100644 index 0000000..fb5c8a9 --- /dev/null +++ b/Chapter8/bookpackext/ProtectDemo.java @@ -0,0 +1,33 @@ +package bookpackext; + +public class ProtectDemo { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ExtBook books[] = new ExtBook[5]; + + books[0] = new ExtBook("Java: A Beginner's Guide", "Schildt", 2019, "Oracle Press"); + books[1] = new ExtBook("Java: The Complete Reference", "Schildt", 2019, "Oracle Press"); + books[2] = new ExtBook("Introducing JavaFX 8 Programming", "Schildt", 2015, "Oracle Press"); + books[3] = new ExtBook("Red Storm Rising", "Clancy", 1986, "Putnam"); + books[4] = new ExtBook("On the Road", "Kerouac", 1955, "Viking"); + + for (int i = 0; i < books.length; i++) { + books[i].show(); + } + + // Find books by author. + System.out.println("Showing all books by Schildt."); + for (int i = 0; i < books.length; i++) { + if (books[i].getAuthorString() == "Schildt") { + System.out.println(books[i].getTitle()); + } + + // Access to protected field not allowed by non-subclass. +// books[0].title = "test title"; + } + + } + +} diff --git a/Chapter8/bookpackext/ProtectDemo2.java b/Chapter8/bookpackext/ProtectDemo2.java new file mode 100644 index 0000000..50414c3 --- /dev/null +++ b/Chapter8/bookpackext/ProtectDemo2.java @@ -0,0 +1,32 @@ +package bookpackext; + +public class ProtectDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ExtBook books[] = new ExtBook[5]; + + books[0] = new ExtBook("Java: A Beginner's Guide", "Schildt", 2019, "Oracle Press"); + books[1] = new ExtBook("Java: The Complete Reference", "Schildt", 2019, "Oracle Press"); + books[2] = new ExtBook("Introducing JavaFX 8 Programming", "Schildt", 2015, "Oracle Press"); + books[3] = new ExtBook("Red Storm Rising", "Clancy", 1986, "Putnam"); + books[4] = new ExtBook("On the Road", "Kerouac", 1955, "Viking"); + + for (int i = 0; i < books.length; i++) { + books[i].show(); + } + + // Find books by author. + System.out.println("Showing all books by Schildt."); + for (int i = 0; i < books.length; i++) { + if (books[i].getAuthorString() == "Schildt") { + System.out.println(books[i].getTitle()); + } + + // Access to protected field not allowed by non-subclass. + books[0].title = "test title"; + } + + } +} diff --git a/Chapter8/bookpackext/ProtectDemo3.java b/Chapter8/bookpackext/ProtectDemo3.java new file mode 100644 index 0000000..a533310 --- /dev/null +++ b/Chapter8/bookpackext/ProtectDemo3.java @@ -0,0 +1,33 @@ +package bookpackext; + +public class ProtectDemo3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ExtBook books[] = new ExtBook[5]; + + books[0] = new ExtBook("Java: A Beginner's Guide", "Schildt", 2019, "Oracle Press"); + books[1] = new ExtBook("Java: The Complete Reference", "Schildt", 2019, "Oracle Press"); + books[2] = new ExtBook("Introducing JavaFX 8 Programming", "Schildt", 2015, "Oracle Press"); + books[3] = new ExtBook("Red Storm Rising", "Clancy", 1986, "Putnam"); + books[4] = new ExtBook("On the Road", "Kerouac", 1955, "Viking"); + + for (int i = 0; i < books.length; i++) { + books[i].show(); + } + + // Find books by author. + System.out.println("Showing all books by Schildt."); + for (int i = 0; i < books.length; i++) { + if (books[i].getAuthorString() == "Schildt") { + System.out.println(books[i].getTitle()); + } + + // Access to protected field not allowed by non-subclass. + books[0].titleString = "test title"; + } + + } + +} diff --git a/Chapter8/bookpackext/ProtectDemo4.java b/Chapter8/bookpackext/ProtectDemo4.java new file mode 100644 index 0000000..63a2ae7 --- /dev/null +++ b/Chapter8/bookpackext/ProtectDemo4.java @@ -0,0 +1,32 @@ +package bookpackext; + +public class ProtectDemo4 { + public static void main(String[] args) { + // TODO Auto-generated method stub + + ExtBook books[] = new ExtBook[5]; + + books[0] = new ExtBook("Java: A Beginner's Guide", "Schildt", 2019, "Oracle Press"); + books[1] = new ExtBook("Java: The Complete Reference", "Schildt", 2019, "Oracle Press"); + books[2] = new ExtBook("Introducing JavaFX 8 Programming", "Schildt", 2015, "Oracle Press"); + books[3] = new ExtBook("Red Storm Rising", "Clancy", 1986, "Putnam"); + books[4] = new ExtBook("On the Road", "Kerouac", 1955, "Viking"); + + for (int i = 0; i < books.length; i++) { + books[i].show(); + } + + // Find books by author. + System.out.println("Showing all books by Schildt."); + for (int i = 0; i < books.length; i++) { + if (books[i].getAuthorString() == "Schildt") { + System.out.println(books[i].getTitle()); + } + + // Access to protected field not allowed by non-subclass, including subclass' instance because + // the instance of subclass is itself not a class but a "realization" of a class. + books[0].titleString = "test title"; + } + + } +} diff --git a/Chapter8/bookpackext/UseBook.java b/Chapter8/bookpackext/UseBook.java new file mode 100644 index 0000000..9cf4bc6 --- /dev/null +++ b/Chapter8/bookpackext/UseBook.java @@ -0,0 +1,12 @@ +// This class is in package bookpackext +package bookpackext; + +// Use the Book from bookpack +public class UseBook { + + public static void main(String[] args) { + bookpack.Book2 books[] = new bookpack.Book2[5]; + + } + +} diff --git a/Chapter8/bookpackext/UseBook2.java b/Chapter8/bookpackext/UseBook2.java new file mode 100644 index 0000000..6db48c8 --- /dev/null +++ b/Chapter8/bookpackext/UseBook2.java @@ -0,0 +1,24 @@ +package bookpackext; + +import bookpack.Book3; + +public class UseBook2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + bookpack.Book3[] books = new Book3[5]; + + books[0] = new Book3("Java: A Beginner's Guide", "Schildt", 2019); + books[1] = new Book3("Java: The Complete Reference", "Schildt", 2019); + books[2] = new Book3("Introducing JavaFX 8 Programming", "Schildt", 2015); + books[3] = new Book3("Red Storm Rising", "Clancy", 1986); + books[4] = new Book3("On the Road", "Kerouac", 1955); + + for (int i = 0; i < books.length; i++) { + books[i].show(); + } + + } + +} diff --git a/Chapter8/bookpackext/UseBook_asterisk.java b/Chapter8/bookpackext/UseBook_asterisk.java new file mode 100644 index 0000000..6a92bee --- /dev/null +++ b/Chapter8/bookpackext/UseBook_asterisk.java @@ -0,0 +1,23 @@ +// Demonstrate import. +package bookpackext; +import bookpack.*; + +public class UseBook_asterisk { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Book3 books[] = new Book3[5]; + + books[0] = new Book3("Java: A Beginner's Guide", "Schildt", 2019); + books[1] = new Book3("Java: The Complete Reference", "Schildt", 2019); + books[2] = new Book3("Introducing JavaFX 8 Programming", "Schildt", 2015); + books[3] = new Book3("Red Storm Rising", "Clancy", 1986); + books[4] = new Book3("On the Road", "Kerouac", 1995); + + for (int i = 0; i < books.length; i++) { + books[i].show(); + } + + } + +} diff --git a/Chapter8/default_method_fundamentals.java b/Chapter8/default_method_fundamentals.java new file mode 100644 index 0000000..43c431e --- /dev/null +++ b/Chapter8/default_method_fundamentals.java @@ -0,0 +1,65 @@ +interface MyIF{ + + // This is a "normal" interface method declaration. + // It does NOT define a default implementation. + int getUserID(); + + + // This is a default method. Notice that it provides a default implementation. + default int getAdminID() { + return 1; + } +} + + +class MyIFImp implements MyIF{ + + // Only getUserID() defined by MyIF needs to be implemented. getAdminID() can be allowed to default. + public int getUserID() { + + return 100; + + } + +} + + +class MyIFImp2 implements MyIF { + + public int getUserID() { + + return 100; + + } + + public int getAdminID() { + + return 42; + } + +} + + +public class default_method_fundamentals { + + public static void main(String[] args) { + + MyIFImp obj = new MyIFImp(); + + // Can call getUserID(), because it is explicitly implemented by MyIFImp: + System.out.println("User ID is " + obj.getUserID()); + + // Can also call getAdminID(), because of default implementation: + System.out.println("Administrator ID is " + obj.getAdminID()); + + + + MyIFImp2 obj2 = new MyIFImp2(); + + System.out.println("User ID is " + obj2.getUserID()); + + System.out.println("Administrator ID is " + obj2.getAdminID()); + + } + +} diff --git a/Example/src/Concatenate.java b/Example/src/Concatenate.java new file mode 100644 index 0000000..1ff551b --- /dev/null +++ b/Example/src/Concatenate.java @@ -0,0 +1,15 @@ + +public class Concatenate { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int my_num = 1 + 2 + 3 + 4 + 5; + int my_num2 = 1 + 2 + 3 + 4 + 5; + + System.out.println(my_num + ", " + my_num2); + System.out.println(my_num + my_num2); + + } + +} diff --git a/Handy/supplementary_material/Nested_functions.java b/Handy/supplementary_material/Nested_functions.java new file mode 100644 index 0000000..d9c25e6 --- /dev/null +++ b/Handy/supplementary_material/Nested_functions.java @@ -0,0 +1,18 @@ +package supplementary_material; + +public class Nested_functions { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + void say_name() { + String mydogString = "Joey"; + + void say_food() { + String myfoodString = "Pizza"; + } + } + +} diff --git a/Handy/supplementary_material/Passing_an_array_to_a_function.java b/Handy/supplementary_material/Passing_an_array_to_a_function.java new file mode 100644 index 0000000..f5cb796 --- /dev/null +++ b/Handy/supplementary_material/Passing_an_array_to_a_function.java @@ -0,0 +1,41 @@ +package supplementary_material; + +public class Passing_an_array_to_a_function { + + public static int max(int[] array) { + int max = 0; + + for (int i = 0; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + return max; + } + + public static int min(int[] array) { + int min = array[0]; + + for (int i = 0; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + return min; + } + + public static void main(String[] args) { + int rock_solid[] = new int[10]; + + for (int i = 0; i < rock_solid.length; i++) { + rock_solid[i] = i; + } + + System.out.println("The max element of the array is " + max(rock_solid)); + System.out.println("The minimum element of the array is " + min(rock_solid)); + + } + +} + +// Reference: https://www.tutorialspoint.com/How-to-pass-Arrays-to-Methods-in-Java diff --git a/Miscellaneous/Accessing_public_class_from_other_package.java b/Miscellaneous/Accessing_public_class_from_other_package.java new file mode 100644 index 0000000..1ecedb4 --- /dev/null +++ b/Miscellaneous/Accessing_public_class_from_other_package.java @@ -0,0 +1,12 @@ +import bookpack.BookDemo; + +public class Accessing_public_class_from_other_package { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + + + } + +} diff --git a/Miscellaneous/Array.java b/Miscellaneous/Array.java new file mode 100644 index 0000000..cf7941d --- /dev/null +++ b/Miscellaneous/Array.java @@ -0,0 +1,38 @@ + +public class Array { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + double[] array_of_double = new double[10]; + +// array_of_double = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}; + + int[] array_of_integers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + array_of_double[0] = 0.1; + array_of_double[1] = 0.2; + array_of_double[2] = 0.3; + array_of_double[3] = 0.4; + array_of_double[4] = 0.5; + array_of_double[5] = 0.6; + array_of_double[6] = 0.7; + array_of_double[7] = 0.8; + array_of_double[8] = 0.9; + + System.out.println(array_of_integers); + System.out.println(array_of_double); + + for (int i : array_of_integers) { + System.out.println(i); + } + + for (double i : array_of_double) { + System.out.println(i); + } + + System.out.println("Initial value of each element in array_of_double is " + array_of_double[9]); + + } + +} diff --git a/Miscellaneous/Binary_Search_Tree.java b/Miscellaneous/Binary_Search_Tree.java new file mode 100644 index 0000000..f9131b0 --- /dev/null +++ b/Miscellaneous/Binary_Search_Tree.java @@ -0,0 +1,58 @@ +public class Binary_Search_Tree { + + private static class Node { + int data; + Node left; + Node right; + + public Node(int data) { + this.data = data; + } + } + + public static Node insert(Node root, int val) { + + if (root == null) { + root = new Node(val); + return root; + } + + if (root.data > val) { + root.left = insert(root.left, val); + } else { + root.right = insert(root.right, val); + } + + return root; + } + + public static void inorder(Node root) { + + if(root == null) + return; + + inorder(root.left); + + System.out.println(root.data + " "); + + inorder(root.right); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int value[] = {3, 4, 6, 2, 7, 9, 5, 8}; + + Node root = null; + + for(int i = 0; i < value.length; i++) { + root = insert(root, value[i]); + } + + inorder(root); + } + +} + + +// Source: https://www.youtube.com/shorts/PVazOskZlfY \ No newline at end of file diff --git a/Miscellaneous/Binary_Search_Tree_non_static_nested_class.java b/Miscellaneous/Binary_Search_Tree_non_static_nested_class.java new file mode 100644 index 0000000..f463b02 --- /dev/null +++ b/Miscellaneous/Binary_Search_Tree_non_static_nested_class.java @@ -0,0 +1,55 @@ +class Node{ + + int data; + Node left; + Node right; + + public Node(int data) { + // TODO Auto-generated constructor stub + this.data = data; + } + + // A method can return any type of data, including class types. + Node insertNode(Node root, int value) { + + if (root == null) { + root = new Node(value); + return root; + } + + if(root.data > value) + root.left = insertNode(root.left, value); + else + root.right = insertNode(root.right, value); + + return root; + } + + void inorder(Node root) { + if(root == null) + return; + + inorder(root.left); + + System.out.println(root.data + " "); + + inorder(root.right); + } + +} + + +public class Binary_Search_Tree_non_static_nested_class { + + public static void main(String[] args) { + + int value[] = {3, 4, 6, 2, 7, 9, 5, 8}; + + Node rootNode = null; + + for (int i = 0; i < value.length; i++) { + rootNode = + } + } + +} diff --git a/Miscellaneous/C/Uninitialized_array_element_content.java b/Miscellaneous/C/Uninitialized_array_element_content.java new file mode 100644 index 0000000..77b95ac --- /dev/null +++ b/Miscellaneous/C/Uninitialized_array_element_content.java @@ -0,0 +1,24 @@ +package C; + +public class Uninitialized_array_element_content { + + public static void main(String[] args) { + + final int ALL_INPUT_LINES_LONGER_THAN_EIGHTY = 500; + + char more_than_80_characters[] = new char[ALL_INPUT_LINES_LONGER_THAN_EIGHTY]; + + if(more_than_80_characters[0] == 0) + System.out.println("Look! more_than_80_characters[0] is 0"); + else + + System.out.println("See! more_than_80_characters[0] is " + more_than_80_characters[0]); + + + } + +} + +// Adapted from https://github.com/ResilientSpring/The-C-Programming-Language/blob/main/Blend/Uninitialized%20array%20element's%20content%202/bruise%203.c + +// Important Note: https://chatgpt.com/c/68349761-6ad8-8008-8673-728152e81f3a \ No newline at end of file diff --git a/Miscellaneous/Cpp/Array_initialization.java b/Miscellaneous/Cpp/Array_initialization.java new file mode 100644 index 0000000..a17a08e --- /dev/null +++ b/Miscellaneous/Cpp/Array_initialization.java @@ -0,0 +1,24 @@ +package Cpp; + +public class Array_initialization { + + public static void main(String[] args) { + + int sqrs[][] = { + + 1, 1, + 2, 4, + 3, 9, + 4, 16, + 5, 25, + 6, 36, + 7, 49, + 8, 64, + 9, 81 + 10, 100 + + }; + + } + +} diff --git a/Miscellaneous/Cpp/Array_initialization_2.java b/Miscellaneous/Cpp/Array_initialization_2.java new file mode 100644 index 0000000..69b9b8d --- /dev/null +++ b/Miscellaneous/Cpp/Array_initialization_2.java @@ -0,0 +1,25 @@ +package Cpp; + +public class Array_initialization_2 { + + public static void main(String[] args) { + + int sqrs[][] = { + + {1, 1}, + {2, 4}, + {3, 9}, + {4, 16}, + {5, 25}, + {6, 36}, + {7, 49}, + {8, 64}, + {9, 81}, + {10, 100} + + }; + + + } + +} diff --git a/Miscellaneous/Cpp/Array_of_objects.java b/Miscellaneous/Cpp/Array_of_objects.java new file mode 100644 index 0000000..ab0633b --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_objects.java @@ -0,0 +1,43 @@ +package Cpp; + +class MyClass{ + private int x; + + void set_x(int i) { + x = i; + } + + int get_x() { + return x; + } +} + +public class Array_of_objects { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] array_name = new int[4]; + + int j; + + for (j = 0; j < array_name.length; j++) + array_name[j] = j; + + for (j = 0; j < array_name.length; j++) + System.out.println("array_name[" + j + "]'s value: " + array_name[j] + "\n"); + + + MyClass[] objects = new MyClass[4]; + + int i; + + for (i = 0; i < objects.length; i++) + objects[i].set_x(i); + + for (i = 0; i < objects.length; i++) + System.out.println("Objects[" + i + "].get_x(): " + objects[i].get_x()); + + } + +} diff --git a/Miscellaneous/Cpp/Array_of_objects_2.java b/Miscellaneous/Cpp/Array_of_objects_2.java new file mode 100644 index 0000000..bb7cb99 --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_objects_2.java @@ -0,0 +1,39 @@ +package Cpp; + +class MyClass2{ + private int x; + + void set_x(int i) { + x = i; + } + + int get_x() { + return x; + } +} + +public class Array_of_objects_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] array_name = new int[4]; + + int j; + + for (j = 0; j < array_name.length; j++) + array_name[j] = j; + + for (j = 0; j < array_name.length; j++) + System.out.println("array_name[" + j + "]'s value: " + array_name[j] + "\n"); + + + MyClass2[] objects = new MyClass2[4]; + + int i; + + for (i = 0; i < objects.length; i++) + System.out.println("Objects[" + i + "] = " + objects[i]); + + } +} diff --git a/Miscellaneous/Cpp/Array_of_objects_3.java b/Miscellaneous/Cpp/Array_of_objects_3.java new file mode 100644 index 0000000..aa1f547 --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_objects_3.java @@ -0,0 +1,38 @@ +package Cpp; + +class MyClasses{ + private int x; + + void set_x(int i) { + x = i; + } + + int get_x() { + return x; + } +} + +public class Array_of_objects_3 { + + public static void main(String[] args) { + + MyClasses[] objects = new MyClasses[4]; + + objects[0] = new MyClasses(); + objects[0].set_x(11); + + objects[1] = new MyClasses(); + objects[1].set_x(99); + + objects[2].set_x(22); + objects[3].set_x(33); + +// for (int i = 0; i < objects.length; i++) +// objects[i].set_x(i); + + for (int i = 0; i < objects.length; i++) + System.out.println("Objects[" + i + "].get_x(): " + objects[i].get_x()); + + } + +} diff --git a/Miscellaneous/Cpp/Array_of_strings.java b/Miscellaneous/Cpp/Array_of_strings.java new file mode 100644 index 0000000..5424570 --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_strings.java @@ -0,0 +1,31 @@ +package Cpp; + +import java.io.IOException; + +public class Array_of_strings { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + + String dictionary[][] = { { "Pencil", "A written instrument." }, { "Keyboard", "An input device." }, + { "rifle", "A shoulder-fired firearm." }, { "Airplane", "A fixed-wing aircraft." }, + { "network", "An interconnected group of computers." } }; + + byte[] word = new byte[80]; + + System.out.println("Enter word: "); + System.in.read(word); + System.out.println("You entered: "); + for (int i = 0; i < word.length; i++) + System.out.print((char) word[i]); + + System.out.println(word.toString()); + + for (int i = 0; i < word.length; i++) { + if(word.toString().equals(dictionary[i][0])) + System.out.println(dictionary[i][1]); + } + + } + +} diff --git a/Miscellaneous/Cpp/Array_of_strings_2.java b/Miscellaneous/Cpp/Array_of_strings_2.java new file mode 100644 index 0000000..f4125c9 --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_strings_2.java @@ -0,0 +1,34 @@ +package Cpp; + +import java.io.IOException; + +public class Array_of_strings_2 { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + String dictionary[][] = { { "Pencil", "A written instrument." }, { "Keyboard", "An input device." }, + { "rifle", "A shoulder-fired firearm." }, { "Airplane", "A fixed-wing aircraft." }, + { "network", "An interconnected group of computers." } }; + + byte[] word = new byte[80]; + + System.out.println("Enter word: "); + System.in.read(word); + System.out.println("You entered: "); + for (int i = 0; i < word.length; i++) + System.out.print((char) word[i]); + + char[] input = new char[80]; + + for (int i = 0; i < word.length; i++) + input[i] = (char) word[i]; + + System.out.println(input.toString()); + + for (int i = 0; i < word.length; i++) { + if(input.toString().equals(dictionary[i][0])) + System.out.println(dictionary[i][1]); + } + } + +} diff --git a/Miscellaneous/Cpp/Array_of_strings_3.java b/Miscellaneous/Cpp/Array_of_strings_3.java new file mode 100644 index 0000000..e60e16c --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_strings_3.java @@ -0,0 +1,48 @@ +package Cpp; + +import java.io.IOException; + +public class Array_of_strings_3 { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + String dictionary[][] = { { "Pencil", "A written instrument." }, { "Keyboard", "An input device." }, + { "rifle", "A shoulder-fired firearm." }, { "Airplane", "A fixed-wing aircraft." }, + { "network", "An interconnected group of computers." } }; + + byte[] word = new byte[80]; + + System.out.println("Enter word: "); + System.in.read(word); + System.out.println("You entered: "); + for (int i = 0; i < word.length; i++) + System.out.print((char) word[i]); + + String convertionString = String.valueOf(word); + + System.out.println(convertionString); + + StringBuilder sBuilder = new StringBuilder(); + for (byte b : word) + sBuilder.append((char) b); + + System.out.println(sBuilder); + + System.out.println(sBuilder.toString()); + + for (int i = 0; i < dictionary.length; i++) { + if(sBuilder.toString().equals(dictionary[i][0])) + System.out.println(dictionary[i][1]); + + if(sBuilder.toString().equals(dictionary[i][0]) && i == dictionary.length -1) + System.out.println(sBuilder.toString() + " not found!"); + + if(dictionary[i][0].equals(sBuilder.toString())) + System.out.println(dictionary[i][1]); + + if(dictionary[i][0].equals(sBuilder.toString()) && i == (dictionary.length -1) ) + System.out.println(sBuilder.toString() + " not found!"); + } + } + +} diff --git a/Miscellaneous/Cpp/Array_of_strings_4.java b/Miscellaneous/Cpp/Array_of_strings_4.java new file mode 100644 index 0000000..e316644 --- /dev/null +++ b/Miscellaneous/Cpp/Array_of_strings_4.java @@ -0,0 +1,43 @@ +package Cpp; + +import java.io.IOException; + +public class Array_of_strings_4 { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + // TODO Auto-generated method stub + String dictionary[][] = { { "Pencil", "A written instrument." }, { "Keyboard", "An input device." }, + { "rifle", "A shoulder-fired firearm." }, { "Airplane", "A fixed-wing aircraft." }, + { "network", "An interconnected group of computers." } }; + + byte[] word = new byte[80]; + + System.out.println("Enter word: "); + System.in.read(word); + System.out.println("You entered: "); + for (int i = 0; i < word.length; i++) + System.out.print((char) word[i]); + + String convertionString = String.valueOf(word); + + System.out.println(convertionString); + + StringBuilder sBuilder = new StringBuilder(); + for (byte b : word) + sBuilder.append((char) b); + + System.out.println(sBuilder); + + System.out.println(sBuilder.toString()); + + for (int i = 0; i < dictionary.length; i++) { + if(sBuilder.toString().equals(dictionary[i][0])) + System.out.println(dictionary[i][1]); + + if(i == dictionary.length -1) + System.out.println(sBuilder.toString() + " not found!"); + } + } + +} diff --git a/Miscellaneous/Cpp/Arrays_of_strings.java b/Miscellaneous/Cpp/Arrays_of_strings.java new file mode 100644 index 0000000..807b383 --- /dev/null +++ b/Miscellaneous/Cpp/Arrays_of_strings.java @@ -0,0 +1,23 @@ +package Cpp; + +public class Arrays_of_strings { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String numbers[][] = { + + {"Tom", "555-3322"}, + {"Mary", "555-8976"}, + {"Jon", "555-1037"}, + {"Rachel", "555-1400"}, + {"Sherry", "555-8873"} + }; + + System.out.println("numbers[0]: " + numbers[0]); + + System.out.println("numbers[0][1]: " + numbers[0][1]); + + } + +} diff --git a/Miscellaneous/Cpp/Assigning_Objects.java b/Miscellaneous/Cpp/Assigning_Objects.java new file mode 100644 index 0000000..e6a4eb9 --- /dev/null +++ b/Miscellaneous/Cpp/Assigning_Objects.java @@ -0,0 +1,56 @@ +package Cpp; + +class Test{ + + int a, b; + + void set_ab(int a, int b) { + + this.a = a; + this.b = b; + + } + + void show_ab() { + + System.out.println("a is " + a + "\n"); + System.out.println("b is " + b + "\n"); + } +} + +public class Assigning_Objects { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Test ob1 = new Test(); + Test ob2 = new Test(); + + + ob1.set_ab(10, 20); + ob2.set_ab(0, 0); + + System.out.println("ob1 before assignment: "); + ob1.show_ab(); + System.out.println("ob2 before assignment: "); + ob2.show_ab(); + System.out.println(); + ob2 = ob1; // assign ob1 to ob2 + + System.out.println("ob1 after assignment: "); + ob1.show_ab(); + System.out.println("ob2 after assignment: "); + ob2.show_ab(); + + System.out.println(); + + ob1.set_ab(-1, -1); // change ob1 + + System.out.println("ob1 after changing ob1: "); + ob1.show_ab(); + System.out.println("ob2 after changing ob1: "); + ob2.show_ab(); + + } + +} diff --git a/Miscellaneous/Cpp/Assigning_Objects_2.java b/Miscellaneous/Cpp/Assigning_Objects_2.java new file mode 100644 index 0000000..7cec8c0 --- /dev/null +++ b/Miscellaneous/Cpp/Assigning_Objects_2.java @@ -0,0 +1,56 @@ +package Cpp; + +class Test2{ + + int a, b; + + void set_ab(int a, int b) { + + this.a = a; + this.b = b; + + } + + void show_ab() { + + System.out.println("a is " + a); + System.out.println("b is " + b); + } +} + +public class Assigning_Objects_2 { + + public static void main(String[] args) { + + Test2 ob1 = new Test2(); + Test2 ob2 = new Test2(); + + + ob1.set_ab(10, 20); + ob2.set_ab(0, 0); + + System.out.println("ob1 before assignment ob2 = ob1: "); + ob1.show_ab(); + System.out.println("ob2 before assignment ob2 = ob1: "); + ob2.show_ab(); + System.out.println(); + + ob2 = ob1; // assign ob1 to ob2 + + System.out.println("ob1 after assignment: "); + ob1.show_ab(); + System.out.println("ob2 after assignment: "); + ob2.show_ab(); + + System.out.println(); + + ob1.set_ab(-1, -1); // change ob1 + + System.out.println("ob1 after changing ob1: "); + ob1.show_ab(); + System.out.println("ob2 after changing ob1: "); + ob2.show_ab(); + + } + +} diff --git a/Miscellaneous/Cpp/Character_string.java b/Miscellaneous/Cpp/Character_string.java new file mode 100644 index 0000000..01c92ba --- /dev/null +++ b/Miscellaneous/Cpp/Character_string.java @@ -0,0 +1,12 @@ +package Cpp; + +public class Character_string { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + char dream[] = "String"; + + } + +} diff --git a/Miscellaneous/Cpp/Constructor.java b/Miscellaneous/Cpp/Constructor.java new file mode 100644 index 0000000..95a8fbb --- /dev/null +++ b/Miscellaneous/Cpp/Constructor.java @@ -0,0 +1,38 @@ +package Cpp; + +class Vehicle{ + int passengers; + int fuelcap; + int mpg; + + public Vehicle(int passenger, int fuelcap, int mpg) { + // TODO Auto-generated constructor stub + this.passengers = passenger; + this.fuelcap = fuelcap; + this.mpg = mpg; + } + + int range() { + return fuelcap * mpg; + } +} + +public class Constructor { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Vehicle minivanVehicle = new Vehicle(7, 16, 21); + Vehicle sportscarVehicle = new Vehicle(2, 14, 12); + + int range1, range2; + + range1 = minivanVehicle.range(); + range2 = sportscarVehicle.range(); + + System.out.println("Minivan can carry " + minivanVehicle.passengers + " with a range of " + range1); + System.out.println("Sportscar can carry " + sportscarVehicle.passengers + " with a range of " + range2); + + } + +} diff --git a/Miscellaneous/Cpp/Passing_Objects_to_Functions.java b/Miscellaneous/Cpp/Passing_Objects_to_Functions.java new file mode 100644 index 0000000..3d21e39 --- /dev/null +++ b/Miscellaneous/Cpp/Passing_Objects_to_Functions.java @@ -0,0 +1,54 @@ +package Cpp; + +class My_Class { + + int value; + + public My_Class(int value) { + // TODO Auto-generated constructor stub + + this.value = value; + } + + int get_value() { + return value; + } + + void set_value(int value) { + this.value = value; + } + + static void display(My_Class ob) { + + System.out.println(ob.value); + + } + + static void change(My_Class ob) { + ob.set_value(100); + System.out.println("Value of ob inside: "); + + display(ob); + } +} + +public class Passing_Objects_to_Functions { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + My_Class a = new My_Class(10); + + System.out.println("Value of a before calling change(): "); + + My_Class.display(a); + + My_Class.change(a); + + System.out.println("Value of a after calling change(): "); + + My_Class.display(a); + + } + +} diff --git a/Miscellaneous/Cpp/Pointer_to_object.java b/Miscellaneous/Cpp/Pointer_to_object.java new file mode 100644 index 0000000..3aaa764 --- /dev/null +++ b/Miscellaneous/Cpp/Pointer_to_object.java @@ -0,0 +1,28 @@ +package Cpp; + +class P_example { + private int num; + + void set_num(int val) { + num = val; + } + + void show_num() { + System.out.println(num); + } +} + +public class Pointer_to_object { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + P_example objectives[] = new P_example[2]; + objectives[0].set_num(10); + objectives[1].set_num(20); + + objectives[0].show_num(); + + } + +} diff --git a/Miscellaneous/Cpp/Pointer_to_object2.java b/Miscellaneous/Cpp/Pointer_to_object2.java new file mode 100644 index 0000000..8784043 --- /dev/null +++ b/Miscellaneous/Cpp/Pointer_to_object2.java @@ -0,0 +1,30 @@ +package Cpp; + +class P_example2{ + private int num; + + void set_num(int val) { + num = val; + } + + void show_num() { + System.out.println(num); + } +} + +public class Pointer_to_object2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] array_of_integer = new int[5]; + + P_example2[] objectives = new P_example2[2]; + + objectives[0] = new P_example2(); + objectives[0].set_num(10); + objectives[0].show_num(); + + } + +} diff --git a/Miscellaneous/Cpp/Pointer_to_object3.java b/Miscellaneous/Cpp/Pointer_to_object3.java new file mode 100644 index 0000000..416dfa4 --- /dev/null +++ b/Miscellaneous/Cpp/Pointer_to_object3.java @@ -0,0 +1,30 @@ +package Cpp; + +class P_example3{ + private int num; + + void set_num(int val) { + num = val; + } + + void show_num() { + System.out.println(num); + } +} + +public class Pointer_to_object3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + P_example3 objective[] = {new P_example3(), new P_example3()}; + + objective[0].set_num(10); + objective[0].show_num(); + + objective[1].set_num(20); + objective[1].show_num(); + + } + +} diff --git a/Miscellaneous/Cpp/Reference_Variables_and_Assignment.java b/Miscellaneous/Cpp/Reference_Variables_and_Assignment.java new file mode 100644 index 0000000..90f89af --- /dev/null +++ b/Miscellaneous/Cpp/Reference_Variables_and_Assignment.java @@ -0,0 +1,36 @@ +package Cpp; + +class Car{ + + int passengers; + int fuelcap; + int mpg; + +} + +public class Reference_Variables_and_Assignment { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Car vehicle1 = new Car(); + Car vehicle2 = vehicle1; + + vehicle1.mpg = 26; + + System.out.println(vehicle1.mpg); + System.out.println(vehicle2.mpg); + + ////////////////////////////////////// + + Car vehicle3 = new Car(); + + vehicle2 = vehicle3; + + System.out.println(vehicle1.mpg); + System.out.println(vehicle2.mpg); + System.out.println(vehicle3.mpg); + + } + +} diff --git a/Miscellaneous/Cpp/Reference_Variables_and_Assignment_2.java b/Miscellaneous/Cpp/Reference_Variables_and_Assignment_2.java new file mode 100644 index 0000000..b1f7db4 --- /dev/null +++ b/Miscellaneous/Cpp/Reference_Variables_and_Assignment_2.java @@ -0,0 +1,29 @@ +package Cpp; + +class Car2{ + + int passengers; + int fuelcap; + int mpg; + +} + +public class Reference_Variables_and_Assignment_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Car2 vehicle1 = new Car2(); + Car2 vehicle2; + + vehicle2 = vehicle1; + + vehicle1.mpg = 26; + + System.out.println(vehicle1.mpg); + System.out.println(vehicle2.mpg); + + System.out.println(); + + } + +} diff --git a/Miscellaneous/Cpp/Static_Member_Variable.java b/Miscellaneous/Cpp/Static_Member_Variable.java new file mode 100644 index 0000000..085422c --- /dev/null +++ b/Miscellaneous/Cpp/Static_Member_Variable.java @@ -0,0 +1,34 @@ +package Cpp; + +class ShareVar{ + static private int num; + + public void setnum(int i) { + num = i; + } + + public void shownum() { + System.out.println(num); + } +} + +public class Static_Member_Variable { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ShareVar aShareVar = new ShareVar(); + ShareVar bShareVar = new ShareVar(); + + aShareVar.shownum(); + bShareVar.shownum(); + + aShareVar.setnum(10); + + aShareVar.shownum(); + bShareVar.shownum(); + + + } + +} diff --git a/Miscellaneous/Cpp/static_variable.java b/Miscellaneous/Cpp/static_variable.java new file mode 100644 index 0000000..d6597fa --- /dev/null +++ b/Miscellaneous/Cpp/static_variable.java @@ -0,0 +1,15 @@ +package Cpp; + +class ShareVar{ + + static int num; +} + +public class static_variable { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Miscellaneous/Cpp/this_keyword.java b/Miscellaneous/Cpp/this_keyword.java new file mode 100644 index 0000000..cbc5c6f --- /dev/null +++ b/Miscellaneous/Cpp/this_keyword.java @@ -0,0 +1,80 @@ +package Cpp; + +class Function_that_returns_objects{ + + int value; + + public Function_that_returns_objects(int value) { + + this.value = value; + + System.out.println("Inside constructors \n"); + } + + + int get_value() { + return value; + } + + + // Return an object. + Function_that_returns_objects mkBigger() { + + Function_that_returns_objects object = new Function_that_returns_objects(value * 2); + + return object; + + } + + static void display(Function_that_returns_objects ob) { + + System.out.println(ob.get_value()); + + } + +} + + + +public class this_keyword { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("Before constructing a."); + + Function_that_returns_objects a = new Function_that_returns_objects(10); + + System.out.println("After constructing a."); + + System.out.println(); + + System.out.println("Before call to display()."); + + Function_that_returns_objects.display(a); + + System.out.println("After display() returns."); + + System.out.println(); + + System.out.println("Before call to mkBigger()."); + + System.out.println(); + + a = a.mkBigger(); + + System.out.println("After mkBigger() returns."); + + System.out.println(); + + System.out.println("Before the second call to display()."); + + Function_that_returns_objects.display(a); + + System.out.println("After display() returns."); + + System.out.println(); + + } + +} diff --git a/Miscellaneous/Cpp/this_keyword_2.java b/Miscellaneous/Cpp/this_keyword_2.java new file mode 100644 index 0000000..b20e41e --- /dev/null +++ b/Miscellaneous/Cpp/this_keyword_2.java @@ -0,0 +1,56 @@ +package Cpp; + +class Function_that_returns_objects_2{ + + int value; + + public Function_that_returns_objects_2(int value) { + + this.value = value; + + System.out.println("Inside constructors \n"); + } + + + int get_value() { + return value; + } + + + // Return an object. + Function_that_returns_objects_2 mkBigger() { + + Function_that_returns_objects_2 object = new Function_that_returns_objects_2(value * 2); + + return object; + + } + +} + + +// It seems that a function cannot be declared in the global scope. +void display(Function_that_returns_objects_2 ob) { + + System.out.println(ob.get_value()); + +} + + + +static void display2(Function_that_returns_objects_2 ob) { + + System.out.println(ob.get_value()); + +} + + + +public class this_keyword_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Miscellaneous/Cpp/virtual_function.java b/Miscellaneous/Cpp/virtual_function.java new file mode 100644 index 0000000..7e64589 --- /dev/null +++ b/Miscellaneous/Cpp/virtual_function.java @@ -0,0 +1,39 @@ +package Cpp; + +class B{ + + void who() { + + System.out.println("Base"); + } +} + +class D1 extends B{ + + void who() { + + System.out.println("First derivation"); + } +} + +class D2 extends B{ + + void who() { + System.out.println("Second derivation"); + } +} + +class D3 extends D1 { // Derive from D1, not B. + void who() { + System.out.println("Third derivation"); + } +} + +public class virtual_function { + + public static void main(String[] args) { + + + } + +} diff --git a/Miscellaneous/Different_package/Final_.java b/Miscellaneous/Different_package/Final_.java new file mode 100644 index 0000000..58ab224 --- /dev/null +++ b/Miscellaneous/Different_package/Final_.java @@ -0,0 +1,38 @@ +package Different_package; + +//Return a String object. +class ErrorMsg_final { + // Declare final constants + // Error codes. + int outERR = 0; + int inERR = 1; + int diskERR = 2; + int indexERR = 3; + + String msgs[] = { + "Output Error", + "Input Error", + "Disk Full", + "Index Out-Of_Bounds" + }; + + // Return the error message. + String getErrorMsg(int i) { + if (i >= 0 & i < msgs.length) + return msgs[i]; + else + return "Invalid Error Code"; + } +} + +public class Final_ { + + public static void main(String[] args) { + ErrorMsg_final errorMsg_final = new ErrorMsg_final(); + + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.outERR)); + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.diskERR)); + System.out.println(errorMsg_final.getErrorMsg(errorMsg_final.inERR)); + } + +} diff --git a/Miscellaneous/Final.java b/Miscellaneous/Final.java new file mode 100644 index 0000000..62c3184 --- /dev/null +++ b/Miscellaneous/Final.java @@ -0,0 +1,29 @@ + +// Return a String object. +class ErrorMsg_final { + // Declare final constants + // Error codes. + int outERR = 0; + int inERR = 1; + int diskERR = 2; + int indexERR = 3; + + String msgs[] = { + "Output Error", + "Input Error", + "Disk Full", + "Index Out-Of_Bounds" + }; + + // Return the error message. + String getErrorMsg(int i) { + if (i >= 0 & i < msgs.length) + return msgs[i]; + else + return "Invalid Error Code"; + } +} + +public class Final { + +} diff --git a/Miscellaneous/Function_optional_arguments.java b/Miscellaneous/Function_optional_arguments.java new file mode 100644 index 0000000..55dc823 --- /dev/null +++ b/Miscellaneous/Function_optional_arguments.java @@ -0,0 +1,17 @@ +// Practicing the code from JavaScript A Beginner's Guide, page 95. +public class Function_optional_arguments { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + check_alert(1200, "Corvette"); + + check_alert(0, null); + + } + + public static void check_alert(int paycheck, String car) { + System.out.println("You make $ " + paycheck + " and have a " + car); + } + +} diff --git a/Miscellaneous/Function_place.java b/Miscellaneous/Function_place.java new file mode 100644 index 0000000..6baf807 --- /dev/null +++ b/Miscellaneous/Function_place.java @@ -0,0 +1,17 @@ +// Convert Function_holding_param2 from C++ into Java. +public class Function_place { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + box(7, 20, 4); + box(50, 3, 2); + box(3, 6, 9); + + } + + static void box(int length, int width, int height) { + System.out.println("Volume of box is " + length * width * height); + } + +} diff --git a/Miscellaneous/Function_place2.java b/Miscellaneous/Function_place2.java new file mode 100644 index 0000000..b8bea52 --- /dev/null +++ b/Miscellaneous/Function_place2.java @@ -0,0 +1,18 @@ + +public class Function_place2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} + +void box(int length, int width, int height) { + System.out.println("Volume of box is " + length * width * height); +} + +public static void main(String[] args) { + // TODO Auto-generated method stub + +} diff --git a/Miscellaneous/JavaScript/Assign_a_value_to_an_array_s_last_element.java b/Miscellaneous/JavaScript/Assign_a_value_to_an_array_s_last_element.java new file mode 100644 index 0000000..38db911 --- /dev/null +++ b/Miscellaneous/JavaScript/Assign_a_value_to_an_array_s_last_element.java @@ -0,0 +1,23 @@ +package JavaScript; + +public class Assign_a_value_to_an_array_s_last_element { + + public static void main(String[] args) { + + String students[] = {"Thomas", "Roger", "Amber", "Jennifer"}; + + students[0] = "Marty"; + + for (int i = 0; i < students.length; i++) { + System.out.println(students[i]); + } + + students[students.length] = "Thomas"; + + for (int i = 0; i < students.length; i++) { + System.out.println(students[i]); + } + + } + +} diff --git a/Miscellaneous/JavaScript/Changing_Array_Length.java b/Miscellaneous/JavaScript/Changing_Array_Length.java new file mode 100644 index 0000000..89676ee --- /dev/null +++ b/Miscellaneous/JavaScript/Changing_Array_Length.java @@ -0,0 +1,17 @@ +package JavaScript; + +public class Changing_Array_Length { + + public static void main(String[] args) { + + + String[] students = {"Thomas", "Roger", "Amber", "Jennifer"}; + + students.length = 2; + + for(int i = 0; i < students.length; i++) + System.out.println(students[i]); + + } + +} diff --git a/Miscellaneous/JavaScript/Changing_Array_Length_2.java b/Miscellaneous/JavaScript/Changing_Array_Length_2.java new file mode 100644 index 0000000..8abeea8 --- /dev/null +++ b/Miscellaneous/JavaScript/Changing_Array_Length_2.java @@ -0,0 +1,17 @@ +package JavaScript; + +public class Changing_Array_Length_2 { + + public static void main(String[] args) { + + String students[] = {"Thomas", "Roger", "Amber", "Jennifer"}; + + students[6] = "Marty"; + + for (int i = 0; i < students.length; i++) { + System.out.println(students[i]); + } + + } + +} diff --git a/Miscellaneous/JavaScript/Changing_Array_Value.java b/Miscellaneous/JavaScript/Changing_Array_Value.java new file mode 100644 index 0000000..5007d46 --- /dev/null +++ b/Miscellaneous/JavaScript/Changing_Array_Value.java @@ -0,0 +1,18 @@ +package JavaScript; + +public class Changing_Array_Value { + + public static void main(String[] args) { + + String[] students = { "Thomas", "Roger", "Amber", "Jennifer" }; + + for (int i = 0; i < students.length; i++) + students[i] += " Doe"; + + for (int i = 0; i < students.length; i++) { + System.out.println(students[i]); + } + + } + +} diff --git a/Miscellaneous/JavaScript/Context.java b/Miscellaneous/JavaScript/Context.java new file mode 100644 index 0000000..0ecb443 --- /dev/null +++ b/Miscellaneous/JavaScript/Context.java @@ -0,0 +1,24 @@ +package JavaScript; + +public class Context { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String myname = "John"; + + if (myname == "John") { + String sedentary = "Jane"; + String pasteurize = "JavaScript"; + + System.out.println(sedentary); + System.out.println(pasteurize); + } + + System.out.println(myname); + System.out.println(sedentary); + System.out.println(pasteurize); + + } + +} diff --git a/Miscellaneous/JavaScript/Loops_and_Nested_Arrays.java b/Miscellaneous/JavaScript/Loops_and_Nested_Arrays.java new file mode 100644 index 0000000..bb600e0 --- /dev/null +++ b/Miscellaneous/JavaScript/Loops_and_Nested_Arrays.java @@ -0,0 +1,17 @@ +package JavaScript; + +public class Loops_and_Nested_Arrays { + + public static void main(String[] args) { + + String[][] studentStrings = new String[4][3]; + + studentStrings[0][0] = ["Thomas", "92", "90"]; + + String studentStrings2[][] = new String[4][3]; + + studentStrings2[0][0] = ["Thomas", "92", "90"]; + + } + +} diff --git a/Miscellaneous/JavaScript/Loops_and_Nested_Arrays_2.java b/Miscellaneous/JavaScript/Loops_and_Nested_Arrays_2.java new file mode 100644 index 0000000..76d7ed6 --- /dev/null +++ b/Miscellaneous/JavaScript/Loops_and_Nested_Arrays_2.java @@ -0,0 +1,27 @@ +package JavaScript; + +public class Loops_and_Nested_Arrays_2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String[][] students = { { "Thomas", "92", "90" }, { "Roger", "87", "78" }, { "Amber", "81", "85" }, + { "Jennifer", "99", "100" } }; + + for (int i = 0; i < students.length; i++) + + for (int j = 0; j < students[i].length; j++) { + + if (j == 0) + + System.out.print(students[i][j] + ": "); + + else if (j == students[i].length - 1) + + System.out.print(students[i][j] + "\n"); + + } + + } + +} diff --git a/Miscellaneous/JavaScript/Redeclaring.java b/Miscellaneous/JavaScript/Redeclaring.java new file mode 100644 index 0000000..5325b91 --- /dev/null +++ b/Miscellaneous/JavaScript/Redeclaring.java @@ -0,0 +1,17 @@ +package JavaScript; + +public class Redeclaring { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int x = 2; + // Now x is 2 + + int x = 3; + + System.out.println(x); + + } + +} diff --git a/Miscellaneous/JavaScript/Redeclaring_variables.java b/Miscellaneous/JavaScript/Redeclaring_variables.java new file mode 100644 index 0000000..f3c0db8 --- /dev/null +++ b/Miscellaneous/JavaScript/Redeclaring_variables.java @@ -0,0 +1,16 @@ +package JavaScript; + +public class Redeclaring_variables { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int x = 10; + + { + int x = 10; + } + + } + +} diff --git a/Miscellaneous/JavaScript/String_Concatenation.java b/Miscellaneous/JavaScript/String_Concatenation.java new file mode 100644 index 0000000..9678757 --- /dev/null +++ b/Miscellaneous/JavaScript/String_Concatenation.java @@ -0,0 +1,17 @@ +package JavaScript; + +public class String_Concatenation { + + public static void main(String[] args) { + + String pertinent = "pertain to"; + + String brew = " preamble"; + + String remittance = pertinent + brew; + + System.out.println(remittance); + + } + +} diff --git a/Miscellaneous/JavaScript/String_concatenation_2.java b/Miscellaneous/JavaScript/String_concatenation_2.java new file mode 100644 index 0000000..ed84839 --- /dev/null +++ b/Miscellaneous/JavaScript/String_concatenation_2.java @@ -0,0 +1,13 @@ +package JavaScript; + +public class String_concatenation_2 { + + public static void main(String[] args) { + + String brew = "Pertaining to " + "preamble"; + + System.out.println(brew); + + } + +} diff --git a/Miscellaneous/JavaScript/let.java b/Miscellaneous/JavaScript/let.java new file mode 100644 index 0000000..8f190d5 --- /dev/null +++ b/Miscellaneous/JavaScript/let.java @@ -0,0 +1,13 @@ +package JavaScript; + +public class let { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + String xString = "John Doe"; + String xString = "John Doe"; + + } + +} diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Intro_to_CS_No17.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Intro_to_CS_No17.java new file mode 100644 index 0000000..db55ba4 --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Intro_to_CS_No17.java @@ -0,0 +1,13 @@ +package L4_Civil_Servant_Admission_Exam; + +public class Intro_to_CS_No17{ + + public static void main(String[] args) { + + int a = 6; + + System.out.println(6^2); + + } + +} \ No newline at end of file diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Intro_to_CS_No17_2026.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Intro_to_CS_No17_2026.java new file mode 100644 index 0000000..3ea27b6 --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Intro_to_CS_No17_2026.java @@ -0,0 +1,29 @@ +package L4_Civil_Servant_Admission_Exam; + +public class Intro_to_CS_No17_2026 { + + public static void main(String[] args) { + + int month = 1; + + while(month <= 4) { + + switch(month) { + + case 1: + System.out.println("31"); + + case 2: + System.out.println("28"); + + case 4: + System.out.println("30"); + + } + + month++; + } + + } + +} diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1.java new file mode 100644 index 0000000..3f924be --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1.java @@ -0,0 +1,27 @@ +package L4_Civil_Servant_Admission_Exam; + +public class Programming_No1 { + + long Catalan_Number(int n) { + + long sum; + + if(n == 0) + return 1; + + for (int i = 0; i < n; i++) { + + + + } + + return sum; + + } + + public static void main(String[] args) { + + + } + +} diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_2.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_2.java new file mode 100644 index 0000000..2fffd89 --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_2.java @@ -0,0 +1,36 @@ +package L4_Civil_Servant_Admission_Exam; + +import Cpp.static_variable; + +public class Programming_No1_2 { + + long static Catalan_Number(int n) { + + long sum; + + if (n == 0) { + + sum = 1; + + return sum; + + } + + for (int i = 0; i < n; i++) { + + sum = Catalan_Number(i) * Catalan_Number(n - 1 - i); + + } + + return sum; + + } + + public static void main(String[] args) { + + System.out.println(Catalan); + + + } + +} diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_3.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_3.java new file mode 100644 index 0000000..59c2748 --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_3.java @@ -0,0 +1,32 @@ +package L4_Civil_Servant_Admission_Exam; + +public class Programming_No1_3 { + + static long Catalan_Number(int n) { + + long sum; + + if (n == 0) { + + sum = 1; + + return sum; + + } + + for (int i = 0; i < n; i++) { + + sum = Catalan_Number(i) * Catalan_Number(n - 1 - i); + + } + + return sum; + + } + + public static void main(String[] args) { + + + } + +} diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_4.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_4.java new file mode 100644 index 0000000..4a43b43 --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_4.java @@ -0,0 +1,45 @@ +package L4_Civil_Servant_Admission_Exam; + +public class Programming_No1_4 { + + static long Catalan_Number(int n) { + + // But Catalan_Number will call itself later, which might restart the sum from zero every time + // Catalan_Number is called and cause the intermediate result of the sum to be lost. + // + // Each call to Catalan_Number(n) has its own independent copy of the sum variable on the call stack. + // So even though sum is initialized to 0 every time the function is called, + // this happens in the scope of that one call only.[1] + long sum = 0; + + if (n == 0) { + + sum = 1; + + return sum; + + } + + for (int i = 0; i < n; i++) { + + sum = Catalan_Number(i) * Catalan_Number(n - 1 - i); + + } + + return sum; + + } + + public static void main(String[] args) { + + System.out.println(Catalan_Number(4)); + + } + +} + +/* References: + * + * 1. https://chatgpt.com/c/6869ef92-f4c8-8008-b7b6-c9d0ee97820b + * + * */ diff --git a/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_5.java b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_5.java new file mode 100644 index 0000000..d6a41b3 --- /dev/null +++ b/Miscellaneous/L4_Civil_Servant_Admission_Exam/Programming_No1_5.java @@ -0,0 +1,47 @@ +package L4_Civil_Servant_Admission_Exam; + +public class Programming_No1_5 { + + static long Catalan_Number(int n) { + + // But Catalan_Number will call itself later, which might restart the sum from zero every time + // Catalan_Number is called and cause the intermediate result of the sum to be lost. + // + // Each call to Catalan_Number(n) has its own independent copy of the sum variable on the call stack. + // So even though sum is initialized to 0 every time the function is called, + // this happens in the scope of that one call only.[1] + long sum = 0; + + if (n == 0) { + + sum = 1; + + return sum; + + } + + for (int i = 0; i < n; i++) { + + // Catalan Formula involves Sigma, so you must add all operands.[1] + // Sigma means to "add" all operands, rather than to "multiply" all operands.[1] + sum = sum + Catalan_Number(i) * Catalan_Number(n - 1 - i); + + } + + return sum; + + } + + public static void main(String[] args) { + + System.out.println(Catalan_Number(4)); + + } + +} + +/* References: + * + * 1. https://chatgpt.com/c/6869ef92-f4c8-8008-b7b6-c9d0ee97820b + * + * */ diff --git a/Miscellaneous/Nested_for_loops.java b/Miscellaneous/Nested_for_loops.java new file mode 100644 index 0000000..9209be4 --- /dev/null +++ b/Miscellaneous/Nested_for_loops.java @@ -0,0 +1,38 @@ + +public class Nested_for_loops { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] array = new int[9]; + + int counter = 0; + + for(int x = 20; x < 80; x += 20) { + + for(int y = 2 ; y < 8; y += 2 ) { + + array[counter] = x * y; + + counter++; + } + + } + + System.out.println("[" + array + "]"); + + System.out.print("["); + + for (int i : array) { + System.out.print(i); + + if (i != 360) { + System.out.print(", "); + } + } + + System.out.print("]"); + + } + +} diff --git a/Miscellaneous/Nested_if.java b/Miscellaneous/Nested_if.java new file mode 100644 index 0000000..d4a0446 --- /dev/null +++ b/Miscellaneous/Nested_if.java @@ -0,0 +1,84 @@ + +public class Nested_if { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int[] array = new int[100]; + + for (int i = 0; i < 100; i++) { + array[i] = i; + } + + System.out.print("["); + + for (int i : array) { + System.out.print(i); + + if (i != 99) { + System.out.print(", "); + } + } + + System.out.print("]"); + + System.out.println(); + + System.out.print("["); + + for (int i : array) { + if (i % 3 == 0) { + System.out.print(i); + + if (i != 99) { + System.out.print(", "); + } + } + } + + System.out.print("]"); + + System.out.println(); + + System.out.print("["); + + for (int i : array) { + + if (i % 3 == 0 && i % 5 == 0) { + System.out.print(i); + + if (i != 90) { + System.out.print(", "); + } + + } + + } + + System.out.print("]"); + + System.out.println(); + + System.out.print("["); + + for (int i : array) { + if (i % 3 == 0) { + + if (i % 5 == 0) { + + System.out.print(i); + + if (i != 90) { + System.out.print(", "); + } + + } + + } + } + + System.out.print("]"); + + } + +} diff --git a/Miscellaneous/Passing_an_array.java b/Miscellaneous/Passing_an_array.java new file mode 100644 index 0000000..49adb1d --- /dev/null +++ b/Miscellaneous/Passing_an_array.java @@ -0,0 +1,26 @@ + +public class Passing_an_array { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int t[] = new int[10]; + + for (int i = 0; i < t.length; i++) + t[i] = i; + + for (int i : t) { + System.out.print(i + " "); + } + + System.out.println("\n==================================================="); + + } + + static void display(int complex[]) { + for (int i = 0; i < complex.length; i++) { + System.out.print(complex[i] + " "); + } + } + +} diff --git a/Miscellaneous/Passing_an_array2.java b/Miscellaneous/Passing_an_array2.java new file mode 100644 index 0000000..cc8ea3e --- /dev/null +++ b/Miscellaneous/Passing_an_array2.java @@ -0,0 +1,28 @@ + +public class Passing_an_array2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + int t[] = new int[10]; + + for (int i = 0; i < t.length; i++) + t[i] = i; + + for (int i : t) { + System.out.print(i + " "); + } + + System.out.println("\n==================================================="); + + display(t); + + } + + static void display(int complex[]) { + for (int i = 0; i < complex.length; i++) { + System.out.print(complex[i] + " "); + } + } + +} diff --git a/Miscellaneous/SOE/HappyNumber.java b/Miscellaneous/SOE/HappyNumber.java new file mode 100644 index 0000000..4507bc9 --- /dev/null +++ b/Miscellaneous/SOE/HappyNumber.java @@ -0,0 +1,47 @@ +package SOE; + +import java.util.HashSet; +import java.util.Set; + +public class HappyNumber { + + // 計算各位數平方和 + static int next(int n) { + int sum = 0; + while (n > 0) { + int d = n % 10; + sum += d * d; + n /= 10; + } + return sum; + } + + // 遞迴版 isHappy() + static boolean isHappy(int n) { + return isHappyHelper(n, new HashSet<>()); + } + + // 遞迴輔助函式:傳遞 seen 集合 + private static boolean isHappyHelper(int n, Set seen) { + if (n == 1) + return true; // 終止條件:快樂數 + if (seen.contains(n)) + return false; // 終止條件:進入循環 + + seen.add(n); + return isHappyHelper(next(n), seen); + } + + // 測試 + public static void main(String[] args) { + int[] nums = {1, 7, 19, 20, 25, 4}; + + for (int n : nums) { + System.out.printf("%d -> %s%n", n, isHappy(n)); + } + } +} + +// Source: https://chatgpt.com/c/69104fa3-4828-8321-ade1-f983f1f8c14c + + diff --git a/Miscellaneous/many_Binary_Search_Tree/Binary_Search_Trees_non_static_nested_class_2.java b/Miscellaneous/many_Binary_Search_Tree/Binary_Search_Trees_non_static_nested_class_2.java new file mode 100644 index 0000000..ba7930a --- /dev/null +++ b/Miscellaneous/many_Binary_Search_Tree/Binary_Search_Trees_non_static_nested_class_2.java @@ -0,0 +1,26 @@ +package many_Binary_Search_Tree; + +class Node{ + + Node leftNode; + Node rightNode; + int value; + + Node(int value){ + + this.value = value; + + } + + + +} + +public class Binary_Search_Trees_non_static_nested_class_2 { + + public static void main(String[] args) { + + + } + +} diff --git a/Oracle_Java_Tutorials/Abstract_Methods_and_Classes/Abstract_classes.java b/Oracle_Java_Tutorials/Abstract_Methods_and_Classes/Abstract_classes.java new file mode 100644 index 0000000..e013b3b --- /dev/null +++ b/Oracle_Java_Tutorials/Abstract_Methods_and_Classes/Abstract_classes.java @@ -0,0 +1,16 @@ +package Abstract_Methods_and_Classes; + +public class Abstract_classes { + + // An abstract class is a class that is declared "abstract"—it may or may not include abstract methods. + + // Abstract classes cannot be instantiated, but they can be subclassed. + + // When an abstract class is subclassed, + // the subclass usually provides implementations for all of the abstract methods in its parent class. + // However, if it does not, then the subclass must also be declared abstract. + + // Reference: + // https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html + +} diff --git a/Oracle_Java_Tutorials/Abstract_Methods_and_Classes/Abstract_methods.java b/Oracle_Java_Tutorials/Abstract_Methods_and_Classes/Abstract_methods.java new file mode 100644 index 0000000..8a8bfc4 --- /dev/null +++ b/Oracle_Java_Tutorials/Abstract_Methods_and_Classes/Abstract_methods.java @@ -0,0 +1,10 @@ +package Abstract_Methods_and_Classes; + +// If a class includes abstract methods, then the class itself must be declared abstract. +public abstract class Abstract_methods { + + // An abstract method is a method that is declared without an implementation (without braces, + // and followed by a semicolon), like this: + abstract void moveTo(double deltaX, double deltaY); + +} diff --git a/Oracle_Java_Tutorials/Autoboxing_and_unboxing/Unboxing.java b/Oracle_Java_Tutorials/Autoboxing_and_unboxing/Unboxing.java new file mode 100644 index 0000000..dcbdb4f --- /dev/null +++ b/Oracle_Java_Tutorials/Autoboxing_and_unboxing/Unboxing.java @@ -0,0 +1,28 @@ +package Autoboxing_and_unboxing; + +import java.util.ArrayList; +import java.util.List; + +// Source: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html + +public class Unboxing { + + public static void main(String[] args) { + Integer i = new Integer(-8); + + // 1. Unboxing through method invocation + int absVal = absoluteValue(i); + System.out.println("absolute value of " + i + " = " + absVal); + + List ld = new ArrayList<>(); + ld.add(3.1416); // Π is autoboxed through method invocation. + + // 2. Unboxing through assignment + double pi = ld.get(0); + System.out.println("pi = " + pi); + } + + public static int absoluteValue(int i) { + return (i < 0) ? -i : i; + } +} diff --git a/Oracle_Java_Tutorials/Classes_and_Objects/Exercise2.java b/Oracle_Java_Tutorials/Classes_and_Objects/Exercise2.java new file mode 100644 index 0000000..f472ecc --- /dev/null +++ b/Oracle_Java_Tutorials/Classes_and_Objects/Exercise2.java @@ -0,0 +1,26 @@ +package Classes_and_Objects; + +class NumberHolder { + public int anInt; + public float aFloat; + + public NumberHolder(int a, float b) { + anInt = a; + aFloat = b; + } +} + +public class Exercise2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + NumberHolder symposiumNumberHolder = new NumberHolder(1, 2); + + System.out.println(symposiumNumberHolder.anInt + symposiumNumberHolder.aFloat); + + System.out.println(symposiumNumberHolder.anInt + ", " + symposiumNumberHolder.aFloat); + + } + +} diff --git a/Oracle_Java_Tutorials/Classes_and_Objects/Question1.java b/Oracle_Java_Tutorials/Classes_and_Objects/Question1.java new file mode 100644 index 0000000..13b8c4f --- /dev/null +++ b/Oracle_Java_Tutorials/Classes_and_Objects/Question1.java @@ -0,0 +1,29 @@ +package Classes_and_Objects; + +class IdentifyMyParts { + public static int x = 7; // class variable. + public int y = 3; // instance variable. +} + +public class Question1 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + IdentifyMyParts a = new IdentifyMyParts(); + IdentifyMyParts b = new IdentifyMyParts(); + + a.y = 5; + b.y = 6; + + a.x = 1; + b.x = 2; + + System.out.println("a.y = " + a.y); + System.out.println("b.y = " + b.y); + System.out.println("a.x = " + a.x); + System.out.println("b.x = " + b.x); + System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x); + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Bicycle.java b/Oracle_Java_Tutorials/Inheritance/Bicycle.java new file mode 100644 index 0000000..1e12b45 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Bicycle.java @@ -0,0 +1,45 @@ +package Inheritance; + +public class Bicycle { + + // the Bicycle class has three fields + public int cadence; + public int gear; + public int speed; + + // the Bicycle class has one constructor + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } + + // the Bicycle class has four methods + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void applyBrake(int decrement) { + speed -= decrement; + } + + public void speedUp(int increment) { + speed += increment; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public void printDescription() { + + System.out.println("\nBike is " + "in gear " + gear + " with a cadence of " + cadence + + " and travelling at a speed of " + speed + ". "); + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Final_class.java b/Oracle_Java_Tutorials/Inheritance/Final_class.java new file mode 100644 index 0000000..5470c30 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Final_class.java @@ -0,0 +1,19 @@ +/* You can also declare an entire class final. A class that is declared final cannot be subclassed/inherited. + * */ + +package Inheritance; + +public final class Final_class { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} + +class subclassed extends Final_class{ + +} + +// Reference: https://docs.oracle.com/javase/tutorial/java/IandI/final.html diff --git a/Oracle_Java_Tutorials/Inheritance/MountainBike.java b/Oracle_Java_Tutorials/Inheritance/MountainBike.java new file mode 100644 index 0000000..07a75c2 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/MountainBike.java @@ -0,0 +1,53 @@ +package Inheritance; + +public class MountainBike extends Bicycle { + + // the MountainBike subclass adds one field + public int seatHeight; + + // add a field for suspension, which is a String value that indicates if the + // bike has a front shock absorber, "Front". + // Or, the bike has a front and back shock absorber, "Dual". + private String suspension; + + public MountainBike(int startCadence, int startSpeed, int startGear, int startHeight, String suspensionType) { + super(startCadence, startSpeed, startGear); + // TODO Auto-generated constructor stub + seatHeight = startHeight; + suspension = suspensionType; + } + + public MountainBike(int startCadence, int startSpeed, int startGear, String suspensionType) { + super(startCadence, startSpeed, startGear); + // TODO Auto-generated constructor stub + suspension = suspensionType; + } + + // the MountainBike subclass adds one method + public void setHeight(int newValue) { + seatHeight = newValue; + } + + public String getSuspension() { + return this.suspension; + } + + public void setSuspension(String suspensionType) { + this.suspension = suspensionType; + } + + // Note the overridden printDescription method. In addition to the information + // provided before, + // additional data about the suspension is included to the output. + public void printDescription() { + super.printDescription(); + + System.out.println("The " + "MountainBike has a " + getSuspension() + " suspension."); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Object_as_a_Superclass.java b/Oracle_Java_Tutorials/Inheritance/Object_as_a_Superclass.java new file mode 100644 index 0000000..3644ed2 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Object_as_a_Superclass.java @@ -0,0 +1,38 @@ +package Inheritance; + +class Book { + private String ISBN; + + public Book(String isbn) { + ISBN = isbn; + } + + public String getISBN() { + return ISBN; + } + + public boolean equals(Object obj) { + if (obj instanceof Book) + return ISBN.equals(((Book) obj).getISBN()); + else + return false; + } +} + +public class Object_as_a_Superclass { + + public static void main(String[] args) { + + // Swing Tutorial, 2nd edition + Book firstBook = new Book("0201914670"); + Book secondBook = new Book("0201914670"); + + if (firstBook.equals(secondBook)) { + System.out.println("objects are equal"); + } else { + System.out.println("objects are not equal"); + } + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Object_as_a_Superclass_2.java b/Oracle_Java_Tutorials/Inheritance/Object_as_a_Superclass_2.java new file mode 100644 index 0000000..c7da65a --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Object_as_a_Superclass_2.java @@ -0,0 +1,31 @@ +package Inheritance; + +class Book2 { + private String ISBN; + + public Book2(String isbn) { + ISBN = isbn; + } + + public String getISBN() { + return ISBN; + } + +} + +public class Object_as_a_Superclass_2 { + + public static void main(String[] args) { + // Swing Tutorial, 2nd edition + Book2 firstBook = new Book2("0201914670"); + Book2 secondBook = new Book2("0201914670"); + + if (firstBook.equals(secondBook)) { + System.out.println("objects are equal"); + } else { + System.out.println("objects are not equal"); + } + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Polymorphism.java b/Oracle_Java_Tutorials/Inheritance/Polymorphism.java new file mode 100644 index 0000000..2345525 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Polymorphism.java @@ -0,0 +1,63 @@ +package Inheritance; + +class MountainBike3 extends Bicycle { + private String suspension; + + public MountainBike3(int startCadence, int startSpeed, int startGear, String suspensionType) { + super(startCadence, startSpeed, startGear); + this.setSuspension(suspensionType); + } + + public String getSuspension() { + return this.suspension; + } + + public void setSuspension(String suspensionType) { + this.suspension = suspensionType; + } + + public void printDescription() { + super.printDescription(); + System.out.println("The " + "MountainBike has a " + getSuspension() + " suspension."); + } +} + +class RoadBike3 extends Bicycle { + // In millimeters (mm) + private int tireWidth; + + public RoadBike3(int startCadence, int startSpeed, int startGear, int newTireWidth) { + super(startCadence, startSpeed, startGear); + this.setTireWidth(newTireWidth); + } + + public int getTireWidth() { + return this.tireWidth; + } + + public void setTireWidth(int newTireWidth) { + this.tireWidth = newTireWidth; + } + + public void printDescription() { + super.printDescription(); + System.out.println("The RoadBike" + " has " + getTireWidth() + " MM tires."); + } +} + +public class Polymorphism { + + public static void main(String[] args) { + Bicycle bike01, bike02, bike03; + + bike01 = new Bicycle(20, 10, 1); + bike02 = new MountainBike3(20, 10, 5, "Dual"); + bike03 = new RoadBike3(40, 20, 8, 23); + + bike01.printDescription(); + bike02.printDescription(); + bike03.printDescription(); + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Polymorphism2.java b/Oracle_Java_Tutorials/Inheritance/Polymorphism2.java new file mode 100644 index 0000000..70c1eab --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Polymorphism2.java @@ -0,0 +1,67 @@ +package Inheritance; + +class MountainBike2 extends Bicycle { + private String suspension; + + public MountainBike2(int startCadence, int startSpeed, int startGear, String suspensionType) { + super(startCadence, startSpeed, startGear); + + suspension = suspensionType; + } + + public String getSuspension() { + return suspension; + } + + public void setSuspension(String suspensionType) { + suspension = suspensionType; + } + + public void printDescription() { + super.printDescription(); + + System.out.println("The " + "MountainBike has a " + getSuspension() + " suspension."); + } +} + +class RoadBike2 extends Bicycle { + // In millimeters (mm) + private int tireWidth; + + public RoadBike2(int startCadence, int startSpeed, int startGear, int newTireWidth) { + super(startCadence, startSpeed, startGear); + + tireWidth = newTireWidth; + } + + public int getTireWidth() { + return this.tireWidth; + } + + public void setTireWidth(int newTireWidth) { + this.tireWidth = newTireWidth; + } + + public void printDescription() { + super.printDescription(); + + System.out.println("The RoadBike" + " has " + getTireWidth() + " MM tires."); + } +} + +public class Polymorphism2 { + + public static void main(String[] args) { + Bicycle bike01, bike02, bike03; + + bike01 = new Bicycle(20, 10, 1); + bike02 = new MountainBike2(20, 10, 5, "Dual"); + bike03 = new RoadBike2(40, 20, 8, 23); + + bike01.printDescription(); + bike02.printDescription(); + bike03.printDescription(); + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Question1.java b/Oracle_Java_Tutorials/Inheritance/Question1.java new file mode 100644 index 0000000..f503d19 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Question1.java @@ -0,0 +1,43 @@ +package Inheritance; + +class ClassA { + + public void methodOne(int i) { + + } + + public void methodTwo(int i) { + + } + + public static void methodThree(int i) { + + } + + public static void methodFour(int i) { + + } +} + +class ClassB extends ClassA { + + public static void methodOne(int i) { + + } + + public void methodTwo(int i) { + + } + + public void methodThree(int i) { + + } + + public static void methodFour(int i) { + + } +} + +public class Question1 { + +} diff --git a/Oracle_Java_Tutorials/Inheritance/RoadBike.java b/Oracle_Java_Tutorials/Inheritance/RoadBike.java new file mode 100644 index 0000000..9f820f0 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/RoadBike.java @@ -0,0 +1,39 @@ +/* Creating the RoadBike class. Because road or racing bikes have skinny tires, + * add an attribute to track the tire width. Here is the RoadBike class: + * */ + +package Inheritance; + +public class RoadBike extends Bicycle { + + // In millimeters (mm) + private int tireWidth; + + public RoadBike(int startCadence, int startSpeed, int startGear, int newTireWidth) { + super(startCadence, startSpeed, startGear); + + tireWidth = newTireWidth; + + } + + public int getTireWidth() { + return this.tireWidth; + } + + public void setTireWidth(int newTireWidth) { + this.tireWidth = newTireWidth; + } + + // Note that once again, the printDescription method has been overridden. + // This time, information about the tire width is displayed. + public void printDescription() { + super.printDescription(); + System.out.println("The RoadBike" + " has " + getTireWidth() + " MM tires."); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/TestBikes.java b/Oracle_Java_Tutorials/Inheritance/TestBikes.java new file mode 100644 index 0000000..b2eb2dc --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/TestBikes.java @@ -0,0 +1,19 @@ +package Inheritance; + +public class TestBikes { + + public static void main(String[] args) { + + Bicycle bike01, bike02, bike03; + + bike01 = new Bicycle(20, 10, 1); + bike02 = new MountainBike(20, 10, 5, "Dual"); + bike03 = new RoadBike(40, 20, 8, 23); + + bike01.printDescription(); + bike02.printDescription(); + bike03.printDescription(); + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods.java new file mode 100644 index 0000000..5d531c1 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods.java @@ -0,0 +1,42 @@ +/**Source: https://docs.oracle.com/javase/tutorial/java/IandI/final.html + * + * Use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. + * + * You might wish to make a method final if it has an implementation that should not be changed + * and it is critical to the consistent state of the object. + */ +package Inheritance; + +class ChessAlgorithm { + + // An enumeration is a list of named constants that define a new data type. + enum ChessPlayer { + White, + Black + } + + // For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final. + final ChessPlayer getFirstPlayer() { + return ChessPlayer.White; + } +} + +class Chess extends ChessAlgorithm { + + ChessPlayer getFirstPlayer() { + + + } +} + +public class Writing_final_classes_and_methods { + + public static void main(String[] args) { + + ChessAlgorithm chessAlgorithm = new ChessAlgorithm(); + + chessAlgorithm.getFirstPlayer(); + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods2.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods2.java new file mode 100644 index 0000000..ef90517 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods2.java @@ -0,0 +1,25 @@ +package Inheritance; + +class ChessAlgorithm2 { + + // An enumeration is a list of named constants that define a new data type. + enum ChessPlayer { + White, + Black + } + + // For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final. + final ChessPlayer getFirstPlayer() { + return ChessPlayer.White; + } +} + +public class Writing_final_classes_and_methods2 { + + public static void main(String[] args) { + + ChessAlgorithm2 chessAlgorithm = new ChessAlgorithm2(); + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods3.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods3.java new file mode 100644 index 0000000..daac5da --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods3.java @@ -0,0 +1,18 @@ +package Inheritance; + +class Chess_Algorithm{ + + enum ChessPlayer { + WHITE, BLACK + } + +} + +public class Writing_final_classes_and_methods3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods4.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods4.java new file mode 100644 index 0000000..2f0a683 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods4.java @@ -0,0 +1,18 @@ +package Inheritance; + +enum Chess_player{ + WHITE, BLACK +} + +class Chess_algorithm2{ + +} + +public class Writing_final_classes_and_methods4 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods5.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods5.java new file mode 100644 index 0000000..9dff5a3 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods5.java @@ -0,0 +1,20 @@ +package Inheritance; + +class ChessAlgorithm_{ + enum ChessPlayer{ + BLACK, WHITE + } + + ChessPlayer getFirstPlayer() { + return ChessPlayer.WHITE; + } +} + +public class Writing_final_classes_and_methods5 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods6.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods6.java new file mode 100644 index 0000000..81a7627 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods6.java @@ -0,0 +1,20 @@ +package Inheritance; + +class ChessAlgorithm__{ + enum ChessPlayer{ + BLACK, WHITE + } + + final ChessPlayer getFirstPlayer() { + return ChessPlayer.BLACK; + } +} + +public class Writing_final_classes_and_methods6 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods7.java b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods7.java new file mode 100644 index 0000000..a066c73 --- /dev/null +++ b/Oracle_Java_Tutorials/Inheritance/Writing_final_classes_and_methods7.java @@ -0,0 +1,28 @@ +package Inheritance; + +import Inheritance.ChessAlgorithm___.ChessPlayer; + +class ChessAlgorithm___{ + enum ChessPlayer{ + BLACK, WHITE + } + + final ChessPlayer getFirstPlayer() { + return ChessPlayer.BLACK; + } +} + +public class Writing_final_classes_and_methods7 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ChessAlgorithm___ returnType = new ChessAlgorithm___(); + + ChessPlayer symposiumChessPlayer = returnType.getFirstPlayer(); + + System.out.println(symposiumChessPlayer); + + } + +} diff --git a/Oracle_Java_Tutorials/Passing_Information_to_a_Method_or_a_Constructor/Pass_by_reference.java b/Oracle_Java_Tutorials/Passing_Information_to_a_Method_or_a_Constructor/Pass_by_reference.java new file mode 100644 index 0000000..84378a4 --- /dev/null +++ b/Oracle_Java_Tutorials/Passing_Information_to_a_Method_or_a_Constructor/Pass_by_reference.java @@ -0,0 +1,42 @@ +package Passing_Information_to_a_Method_or_a_Constructor; + +class Circle{ + + public Circle(int x, int y) { + // TODO Auto-generated constructor stub + } + + public int getX() { + // TODO Auto-generated method stub + return 0; + } + + public void setX(int i) { + // TODO Auto-generated method stub + + } + +} + +public class Pass_by_reference { + + public static void moveCircle(Circle circle, int deltaX, int deltaY) { + // code to move origin of circle to x+deltaX, y+deltaY + circle.setX(circle.getX() + deltaX); + circle.setX(circle.getX() + deltaY); + + // code to assign a new reference to circle + circle = new Circle(0, 0); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Circle myCircle = new Circle(1, 9); + + moveCircle(myCircle, 23, 56); + } + +} + +// Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html diff --git a/Oracle_Java_Tutorials/Passing_Information_to_a_Method_or_a_Constructor/Polygon.java b/Oracle_Java_Tutorials/Passing_Information_to_a_Method_or_a_Constructor/Polygon.java new file mode 100644 index 0000000..0279655 --- /dev/null +++ b/Oracle_Java_Tutorials/Passing_Information_to_a_Method_or_a_Constructor/Polygon.java @@ -0,0 +1,31 @@ +package Passing_Information_to_a_Method_or_a_Constructor; + +class Point{ + double x; + double y; + + public Point() { + // TODO Auto-generated constructor stub + } + +} + +public class Polygon { + + public Polygon() { + // TODO Auto-generated constructor stub + } + + // the constructor creates a new Polygon object and initializes it from an array of Point objects + Polygon(Point corners[]){ + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} + +// Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html diff --git a/Questions_to_ask/Inheritance.java b/Questions_to_ask/Inheritance.java new file mode 100644 index 0000000..3d1a13d --- /dev/null +++ b/Questions_to_ask/Inheritance.java @@ -0,0 +1,31 @@ + +class Super2 { + int i; + + void performative() { + System.out.println("Super2's perfomative method."); + } +} + +class Sub_class extends Super2 { + + int a = i * 10; + i = 11; + + void performative() { + System.out.println("Sub_class's performative method."); + } + + double decorative() { + return i + 1; + } + +} + +public class Inheritance { + + public static void main(String[] args) { + + } + +} diff --git a/Questions_to_ask/Inheritance2.java b/Questions_to_ask/Inheritance2.java new file mode 100644 index 0000000..3fa1cb9 --- /dev/null +++ b/Questions_to_ask/Inheritance2.java @@ -0,0 +1,27 @@ + +class Super3 { + int i = 10; + + void performative() { + System.out.println("Super3's perfomative method."); + } +} + +class Sub_class2 extends Super3 { + + int a = i * 10; + i = 11; + + void performative() { + System.out.println("Sub_class2's performative method."); + } + + double decorative() { + return i + 1; + } + +} + +public class Inheritance2 { + +} diff --git a/Questions_to_ask/Polymorphous.java b/Questions_to_ask/Polymorphous.java new file mode 100644 index 0000000..104b5fb --- /dev/null +++ b/Questions_to_ask/Polymorphous.java @@ -0,0 +1,55 @@ +// How could superclass2 holding subclass' object reference have access to method defined by the subclass? +// Isn't it that "When a reference to a subclass object is assigned to a superclass reference variable, +// you will have access only to those parts of the object defined by the superclass?" +class Superclass { + + public Superclass() { + // TODO Auto-generated constructor stub + } + + void polymorphism() { + + System.out.println("A reference variable of a superclass can be assigned an object of " + + "any subclass derived from that superclass. \n"); + + System.out.println("When a reference to a subclass object is assigned to a superclass reference variable, " + + "you will have access only to those parts of the object defined by the superclass."); + + System.out.print("It makes sense because superclass has no knowledge of what a subclass adds to it.\n"); + } +} + +class Subclass extends Superclass { + + public Subclass() { + // TODO Auto-generated constructor stub + } + + void polymorphism() { + System.out.println("When an overridden method is called through a superclass reference variable, " + + "Java determines which version of that method to execute based upon the type of the object " + + "being referred to at the time the call occurs."); + } +} + +public class Polymorphous { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Superclass superclass = new Superclass(); + Subclass subclass = new Subclass(); + + Superclass superclass2 = new Superclass(); + + superclass2 = superclass; + superclass2.polymorphism(); + + System.out.println('\n' + "A superclass reference variable can refer to a subclass object." + '\n'); + + superclass2 = subclass; + superclass2.polymorphism(); + + } + +} diff --git a/Questions_to_ask/Unresolved/How_does_TwoDShape_parameter_ob_know_width_height_and_name.java b/Questions_to_ask/Unresolved/How_does_TwoDShape_parameter_ob_know_width_height_and_name.java new file mode 100644 index 0000000..ed218f4 --- /dev/null +++ b/Questions_to_ask/Unresolved/How_does_TwoDShape_parameter_ob_know_width_height_and_name.java @@ -0,0 +1,38 @@ +package Unresolved; + +class TwoDShape { + private double width; + private double height; + private String name; + + public TwoDShape() { + width = height = 0.0; + name = "none"; + } + + TwoDShape(double w, double h, String n) { + width = w; + height = h; + name = n; + } + + TwoDShape(double x, String n) { + width = height = x; + name = n; + } + + TwoDShape(TwoDShape ob) { + width = ob.width; // How does TwoDShape parameter ob know width, height, and name without using the keyword new? + height = ob.height; + name = ob.name; + } +} + +public class How_does_TwoDShape_parameter_ob_know_width_height_and_name { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/Questions_to_ask/super_constructor.java b/Questions_to_ask/super_constructor.java new file mode 100644 index 0000000..3b9ae99 --- /dev/null +++ b/Questions_to_ask/super_constructor.java @@ -0,0 +1,38 @@ +class conceding { + int a; + int b; + int c; + + public conceding(int d, int e, int f) { + a = d; + b = e; + c = f; + } + + void performant() { + System.out.println("This is the from superclass."); + } +} + +class secret_formula extends concede{ + + int g = 10; + int h; + int i; + + public secret_formula() { + super(g, h, i); + + + } + + void performant() { + super.performant(); + + System.out.println("This is from sub-class."); + } +} + +public class super_constructor { + +} diff --git a/README.md b/README.md index 32bb8e1..0ba4dcd 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ # Example -First github attempt on Eclipse +First GitHub attempt on Eclipse + + +Chapter 4: https://github.com/ResilientSpring/Chapter-IV