The Java Learning Kit: Chapter 5 – Methods and Modularity
Copyright 2015 by C. Herbert, all rights reserved.
Last edited January, 2015 by C. Herbert
This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig
Nelson, Christopher Quinones, Matthew Staley, and Daphne Herbert. It is available free of charge for students in Computer
Science courses at Community College of Philadelphia during the Spring 2015 semester.
This material is protected by United States and international copyright law and may not be reproduced, distributed,
transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter
or remove any trademark, copyright or other notice from copies of the material.
The Java Learning Kit:
Chapter 5
Methods and Modularity
Lesson 5.1 – User Created Methods in Java
Lesson 5.2 – Method Parameters
Lab 5A – Examining code with Several Methods
Lesson 5.3 – Top-Down Design and Modular Development
Lab 5B – Methods and Parameter Passing
JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 2
Contents
Chapter 5 Learning Outcomes .................................................................................................................... 3
User Created Methods in Java ......................................................................................... 4
Method Modifiers ............................................................................................................................... 4
Return Type ........................................................................................................................................ 6
Other method modifiers ..................................................................................................................... 7
Method Parameters ............................................................................................................................ 7
Invoking a Method and Parameter Passing ......................................................................................... 7
Method Documentation ..................................................................................................................... 9
CheckPoint 5.1 .................................................................................................................................. 10
Lab 5A – Examining code with Several Methods ................................................................................... 11
Top-Down Design and Modular Development .............................................................. 13
CheckPoint 5.2 .................................................................................................................................. 15
Lab 5B – Methods and Parameter Passing .....................................................................
The document outlines a Java training program offered by SUGA Consulting Services. The 10-day program covers topics like OOP concepts, data types, strings, packages, threads, exceptions, access modifiers, methods, JDBC, log4j, and includes 3 mini projects. It provides details on each topic's duration and describes concepts like abstraction, encapsulation, polymorphism, inheritance, primitive types and wrapper classes, strings and string buffers, the util and IO packages, exception handling, access modifiers, methods and constructors, coding standards, JUnit and more. Contact details for SUGA Consulting are also included.
The document discusses various programming paradigms including procedural programming, object-oriented programming, modular programming, and generic programming. It provides details on each paradigm such as concepts, languages used, advantages etc. It also discusses Java basics including its creation, data types, variables, operators, control statements and classes. Key object-oriented programming concepts like class, object, encapsulation, inheritance and polymorphism are explained.
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
I have been writing a lot about advanced topics like MVC, Entity Framework, Repository Patterns etc., my priority always remains to cover the topic as a whole, so that a reader do not have to search for missing links anywhere else. My this article will cover almost every OOPS concept that a novice/beginner developer hunt for, and not only beginners, the article’s purpose is to be helpful to experience professionals also who need to sometimes brush-up their concepts or who prepare for interviews .
This document provides an overview of key concepts in Java, including:
- Java uses keywords and grammar rules. Keywords cannot name variables.
- Java code is compiled into bytecode that can run on any device with a Java Virtual Machine.
- There are two types of data types in Java: primitive types and abstract types. The eight primitive types are used for variables and literals.
- Variables must be declared with a name and data type. Names follow specific rules.
- Classes contain methods that define behavior. The main() method is required to run a program.
The document discusses reflection in programming, specifically in Java. It provides an overview of reflection, its advantages like enabling polymorphism and creating adaptable code, and its disadvantages like reduced performance and increased complexity. It also discusses proper uses of reflection, like in development tools, and misuses, like when interfaces could enable the same functionality more cleanly. An example is provided to demonstrate how to use reflection in Java to inspect class details at runtime.
Dear students get fully solved assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
This document discusses different programming paradigms and compares procedural and object-oriented programming. It defines procedural programming as breaking a program into small subroutines or functions, while object-oriented programming breaks a program into objects that contain both data and code. Some key differences highlighted include objects having both data and methods while functions are separate, OOP following a bottom-up design and having features like inheritance and polymorphism. Examples of languages for each paradigm are provided.
The document discusses scoping in programming languages. It defines scoping as the visibility of variables, parameters, and functions in different parts of a program. There are four types of variable scope: local, global, enclosed, and built-in. The LEGB rule defines the order these scopes are searched. Modules are parts of a program that can be developed independently and integrated. Modular programming divides programs into separate, reusable modules. Access control regulates who can view and use resources by making class members private, protected, or public.
The document outlines a Java training program offered by SUGA Consulting Services. The 10-day program covers topics like OOP concepts, data types, strings, packages, threads, exceptions, access modifiers, methods, JDBC, log4j, and includes 3 mini projects. It provides details on each topic's duration and describes concepts like abstraction, encapsulation, polymorphism, inheritance, primitive types and wrapper classes, strings and string buffers, the util and IO packages, exception handling, access modifiers, methods and constructors, coding standards, JUnit and more. Contact details for SUGA Consulting are also included.
The document discusses various programming paradigms including procedural programming, object-oriented programming, modular programming, and generic programming. It provides details on each paradigm such as concepts, languages used, advantages etc. It also discusses Java basics including its creation, data types, variables, operators, control statements and classes. Key object-oriented programming concepts like class, object, encapsulation, inheritance and polymorphism are explained.
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
I have been writing a lot about advanced topics like MVC, Entity Framework, Repository Patterns etc., my priority always remains to cover the topic as a whole, so that a reader do not have to search for missing links anywhere else. My this article will cover almost every OOPS concept that a novice/beginner developer hunt for, and not only beginners, the article’s purpose is to be helpful to experience professionals also who need to sometimes brush-up their concepts or who prepare for interviews .
This document provides an overview of key concepts in Java, including:
- Java uses keywords and grammar rules. Keywords cannot name variables.
- Java code is compiled into bytecode that can run on any device with a Java Virtual Machine.
- There are two types of data types in Java: primitive types and abstract types. The eight primitive types are used for variables and literals.
- Variables must be declared with a name and data type. Names follow specific rules.
- Classes contain methods that define behavior. The main() method is required to run a program.
The document discusses reflection in programming, specifically in Java. It provides an overview of reflection, its advantages like enabling polymorphism and creating adaptable code, and its disadvantages like reduced performance and increased complexity. It also discusses proper uses of reflection, like in development tools, and misuses, like when interfaces could enable the same functionality more cleanly. An example is provided to demonstrate how to use reflection in Java to inspect class details at runtime.
Dear students get fully solved assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
This document discusses different programming paradigms and compares procedural and object-oriented programming. It defines procedural programming as breaking a program into small subroutines or functions, while object-oriented programming breaks a program into objects that contain both data and code. Some key differences highlighted include objects having both data and methods while functions are separate, OOP following a bottom-up design and having features like inheritance and polymorphism. Examples of languages for each paradigm are provided.
The document discusses scoping in programming languages. It defines scoping as the visibility of variables, parameters, and functions in different parts of a program. There are four types of variable scope: local, global, enclosed, and built-in. The LEGB rule defines the order these scopes are searched. Modules are parts of a program that can be developed independently and integrated. Modular programming divides programs into separate, reusable modules. Access control regulates who can view and use resources by making class members private, protected, or public.
Dear students get fully solved assignments by professionals
Send your semester & Specialization name to our mail id :
stuffstudy5@gmail.com
or
call us at : 098153-33456
Dear students get fully solved assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
Dear students get fully solved SMU MBA Fall 2014 assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
This document discusses methods in C#, including how they are declared, invoked, and used. It covers key concepts like the main method, passing parameters by value and reference, output parameters, variable argument lists, and method overloading. Methods are declared inside classes and give objects their behavioral characteristics by allowing processing of data and responses to messages from other objects. The main method is the starting point of all C# programs and must be static. Parameters can be passed by value or reference, and output parameters pass results back using the out keyword. Variable argument lists use params arrays, and overloading methods have the same name but different parameters.
This document provides an overview of key concepts covered in the Sun Certified Java Programmer (SCJP) 1.4 exam, including:
- Arrays in Java - how to declare, construct, initialize, and access array elements.
- Class modifiers like public, private, protected that restrict access, and final that prevents subclassing. Method and variable modifiers like static, abstract, synchronized are also discussed.
- Constructors - how they are invoked using this() and super(), default constructors, and cases where a default constructor is not provided by the compiler.
The document gives examples of each concept and is intended to help readers prepare for the SCJP certification exam by learning about its main objectives
This document contains 20 interview questions related to Java. It covers topics such as:
- The differences between constructors and methods, final and static keywords, and the purpose of the Void class.
- Details about finalize methods, just-in-time compilation, abstraction, encapsulation, inheritance, polymorphism, and method overloading and overriding.
- Questions about byte code, class vs instance variables, local variables, and class vs instance methods.
- Definitions of interfaces, abstract classes, access specifiers, identifiers, and literals.
- Questions about the name Java, calling 'sun' packages, Java releases, constructors vs methods, static vs non-static variables, while
The document discusses using local variables in methods. Local variables are created when a method begins, are private to the method, and are destroyed when the method exits. While local variables are private to each method, class variables can be used to share data between methods. The compiler will not warn about naming conflicts between local and class variables with the same name.
This document discusses object-oriented programming concepts in Kotlin such as classes, objects, methods, and static methods. It provides examples of defining classes that represent real-world entities like cars. Objects are defined as instances of classes that contain an address and occupy memory. Methods are functions that are part of a class and can be invoked by objects. Static methods belong to a class rather than individual objects.
This document provides an overview of object-oriented programming concepts in Java, including naming conventions, data types, variables, data hiding, abstraction, encapsulation, inheritance relationships, method signatures, polymorphism, constructors, and wrapper classes. It defines each concept and provides examples. For instance, it explains that naming conventions establish readability rules for identifiers, abstraction hides unnecessary details while exposing essential features, encapsulation allows objects to contain related properties and methods, and inheritance allows objects to acquire properties of other objects.
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsGaruda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
We, Garuda Trainings are provide SAP ABAP Online Training over globe.
For More:
http://garudatrainings.com/
Mail: garudatrainings@gmail.com
Phone: +1(508)841-6144
Lecture5_Method_overloading_Final power point presentationbhargavi804095
The document discusses method overloading and the final keyword in Java. It provides examples of overloading methods by changing the number and type of parameters. Method overloading allows writing methods with the same name but different signatures. The final keyword can be applied to variables, methods, and classes. It prevents modification of final variables, overriding of final methods, and extending of final classes. Blank final variables must be initialized in the constructor.
Lecture4_Method_overloading power point presentaionbhargavi804095
The document discusses method overloading and the final keyword in Java. It provides examples of overloading methods by changing the number and type of parameters. Method overloading allows writing methods with the same name but different signatures. The final keyword can be applied to variables, methods, and classes. It prevents modification of final variables, overriding of final methods, and extending of final classes. Blank final variables must be initialized in the constructor.
This document provides an overview of key concepts in Java programming including:
- Creating, compiling, and running Java programs and understanding program anatomy such as comments, packages, classes, and methods.
- Using basic programming constructs like data types, control statements, and arrays to write simple Java programs.
- Establishing a foundation in Java concepts such as Object Oriented Programming (OOP) and establishing a firm understanding of how Java code is structured and executed.
- Learning how to use core Java APIs and frameworks like I/O, Collections, Threads, Reflection, Serialization, Networking, RMI, and JDBC.
This document provides information about Java programming questions that are commonly asked in interviews and exams. It lists 30 Java programming questions and their answers on topics like OOPs concepts, multithreading, exceptions, JDBC, serialization and more. The document also provides links to connect with the authors on social media and messaging platforms like WhatsApp, Telegram, Facebook, Twitter etc. for any doubts or feedback. It reminds the reader to practice all the questions well to build a clear understanding of concepts and score well in exams.
Vibrant Technologies is headquarted in Mumbai,India.We are the best Java training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Java classes in Mumbai according to our students and corporators
Polymorphism in Java allows an object to take on multiple forms. There are two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Method overloading involves methods with the same name but different parameters, while method overriding involves subclasses providing their own implementation of a superclass method. Runtime polymorphism determines which version of a method to call based on the object's actual type at runtime. Abstraction in Java allows hiding implementation details and showing only essential functionality through the use of abstract classes and methods.
This document provides an overview of object-oriented programming concepts and Java programming. It discusses key OOP concepts like classes, objects, encapsulation, inheritance, and polymorphism. It then covers the history and development of Java, describing how it was initially created at Sun Microsystems in the 1990s to be a platform-independent language for programming consumer electronics. The document outlines some of Java's key features like being simple, secure, portable, robust, and architecture-neutral. It also discusses Java's object-oriented nature and support for multithreading.
This document discusses methods in Java. It begins with an introduction that defines methods as collections of statements that perform specific tasks and may return results. It then covers method syntax, declaration, types (predefined and user-defined), ways to create methods (instance and static), method signatures, naming conventions, calling methods, creating static methods, applying instance methods, memory allocation for method calls, and advantages of using methods such as reusability and improved readability. The presentation concludes with an acknowledgement slide thanking faculty, parents, and fellow students for their assistance and support.
Polymorphism in Java allows an object to take on multiple forms. There are two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Method overloading involves methods with the same name but different parameters, while method overriding involves subclasses providing their own implementation of a superclass method. Abstract classes allow defining methods without implementation, requiring subclasses to implement them, while interfaces only define method signatures that implementing classes must then define.
Write a scholarly paper in which you apply the concepts of epide.docxarnoldmeredith47041
This document provides requirements for an epidemiology paper that analyzes a communicable disease. Students must choose a communicable disease, describe it thoroughly including causes, transmission, symptoms, treatment and complications. They must discuss the population most affected by the disease and the determinants of health related to it. Students must also identify the epidemiologic triad of host, agent, and environmental factors for the disease and discuss the role of public health nurses in finding, reporting, collecting, analyzing data, and following up on the disease. The paper requires a minimum of three references and 1250 words in APA format.
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docxarnoldmeredith47041
This document outlines a goal to improve the ability to seek first to understand others rather than be understood according to Habit 5. The author acknowledges they are able to communicate but struggles with listening skills. The goal is to practice actively listening and understanding what people are saying rather than being focused on themselves.
More Related Content
Similar to The Java Learning Kit Chapter 5 – Methods and Modular.docx
Dear students get fully solved assignments by professionals
Send your semester & Specialization name to our mail id :
stuffstudy5@gmail.com
or
call us at : 098153-33456
Dear students get fully solved assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
Dear students get fully solved SMU MBA Fall 2014 assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
This document discusses methods in C#, including how they are declared, invoked, and used. It covers key concepts like the main method, passing parameters by value and reference, output parameters, variable argument lists, and method overloading. Methods are declared inside classes and give objects their behavioral characteristics by allowing processing of data and responses to messages from other objects. The main method is the starting point of all C# programs and must be static. Parameters can be passed by value or reference, and output parameters pass results back using the out keyword. Variable argument lists use params arrays, and overloading methods have the same name but different parameters.
This document provides an overview of key concepts covered in the Sun Certified Java Programmer (SCJP) 1.4 exam, including:
- Arrays in Java - how to declare, construct, initialize, and access array elements.
- Class modifiers like public, private, protected that restrict access, and final that prevents subclassing. Method and variable modifiers like static, abstract, synchronized are also discussed.
- Constructors - how they are invoked using this() and super(), default constructors, and cases where a default constructor is not provided by the compiler.
The document gives examples of each concept and is intended to help readers prepare for the SCJP certification exam by learning about its main objectives
This document contains 20 interview questions related to Java. It covers topics such as:
- The differences between constructors and methods, final and static keywords, and the purpose of the Void class.
- Details about finalize methods, just-in-time compilation, abstraction, encapsulation, inheritance, polymorphism, and method overloading and overriding.
- Questions about byte code, class vs instance variables, local variables, and class vs instance methods.
- Definitions of interfaces, abstract classes, access specifiers, identifiers, and literals.
- Questions about the name Java, calling 'sun' packages, Java releases, constructors vs methods, static vs non-static variables, while
The document discusses using local variables in methods. Local variables are created when a method begins, are private to the method, and are destroyed when the method exits. While local variables are private to each method, class variables can be used to share data between methods. The compiler will not warn about naming conflicts between local and class variables with the same name.
This document discusses object-oriented programming concepts in Kotlin such as classes, objects, methods, and static methods. It provides examples of defining classes that represent real-world entities like cars. Objects are defined as instances of classes that contain an address and occupy memory. Methods are functions that are part of a class and can be invoked by objects. Static methods belong to a class rather than individual objects.
This document provides an overview of object-oriented programming concepts in Java, including naming conventions, data types, variables, data hiding, abstraction, encapsulation, inheritance relationships, method signatures, polymorphism, constructors, and wrapper classes. It defines each concept and provides examples. For instance, it explains that naming conventions establish readability rules for identifiers, abstraction hides unnecessary details while exposing essential features, encapsulation allows objects to contain related properties and methods, and inheritance allows objects to acquire properties of other objects.
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsGaruda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
We, Garuda Trainings are provide SAP ABAP Online Training over globe.
For More:
http://garudatrainings.com/
Mail: garudatrainings@gmail.com
Phone: +1(508)841-6144
Lecture5_Method_overloading_Final power point presentationbhargavi804095
The document discusses method overloading and the final keyword in Java. It provides examples of overloading methods by changing the number and type of parameters. Method overloading allows writing methods with the same name but different signatures. The final keyword can be applied to variables, methods, and classes. It prevents modification of final variables, overriding of final methods, and extending of final classes. Blank final variables must be initialized in the constructor.
Lecture4_Method_overloading power point presentaionbhargavi804095
The document discusses method overloading and the final keyword in Java. It provides examples of overloading methods by changing the number and type of parameters. Method overloading allows writing methods with the same name but different signatures. The final keyword can be applied to variables, methods, and classes. It prevents modification of final variables, overriding of final methods, and extending of final classes. Blank final variables must be initialized in the constructor.
This document provides an overview of key concepts in Java programming including:
- Creating, compiling, and running Java programs and understanding program anatomy such as comments, packages, classes, and methods.
- Using basic programming constructs like data types, control statements, and arrays to write simple Java programs.
- Establishing a foundation in Java concepts such as Object Oriented Programming (OOP) and establishing a firm understanding of how Java code is structured and executed.
- Learning how to use core Java APIs and frameworks like I/O, Collections, Threads, Reflection, Serialization, Networking, RMI, and JDBC.
This document provides information about Java programming questions that are commonly asked in interviews and exams. It lists 30 Java programming questions and their answers on topics like OOPs concepts, multithreading, exceptions, JDBC, serialization and more. The document also provides links to connect with the authors on social media and messaging platforms like WhatsApp, Telegram, Facebook, Twitter etc. for any doubts or feedback. It reminds the reader to practice all the questions well to build a clear understanding of concepts and score well in exams.
Vibrant Technologies is headquarted in Mumbai,India.We are the best Java training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Java classes in Mumbai according to our students and corporators
Polymorphism in Java allows an object to take on multiple forms. There are two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Method overloading involves methods with the same name but different parameters, while method overriding involves subclasses providing their own implementation of a superclass method. Runtime polymorphism determines which version of a method to call based on the object's actual type at runtime. Abstraction in Java allows hiding implementation details and showing only essential functionality through the use of abstract classes and methods.
This document provides an overview of object-oriented programming concepts and Java programming. It discusses key OOP concepts like classes, objects, encapsulation, inheritance, and polymorphism. It then covers the history and development of Java, describing how it was initially created at Sun Microsystems in the 1990s to be a platform-independent language for programming consumer electronics. The document outlines some of Java's key features like being simple, secure, portable, robust, and architecture-neutral. It also discusses Java's object-oriented nature and support for multithreading.
This document discusses methods in Java. It begins with an introduction that defines methods as collections of statements that perform specific tasks and may return results. It then covers method syntax, declaration, types (predefined and user-defined), ways to create methods (instance and static), method signatures, naming conventions, calling methods, creating static methods, applying instance methods, memory allocation for method calls, and advantages of using methods such as reusability and improved readability. The presentation concludes with an acknowledgement slide thanking faculty, parents, and fellow students for their assistance and support.
Polymorphism in Java allows an object to take on multiple forms. There are two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Method overloading involves methods with the same name but different parameters, while method overriding involves subclasses providing their own implementation of a superclass method. Abstract classes allow defining methods without implementation, requiring subclasses to implement them, while interfaces only define method signatures that implementing classes must then define.
Similar to The Java Learning Kit Chapter 5 – Methods and Modular.docx (20)
Write a scholarly paper in which you apply the concepts of epide.docxarnoldmeredith47041
This document provides requirements for an epidemiology paper that analyzes a communicable disease. Students must choose a communicable disease, describe it thoroughly including causes, transmission, symptoms, treatment and complications. They must discuss the population most affected by the disease and the determinants of health related to it. Students must also identify the epidemiologic triad of host, agent, and environmental factors for the disease and discuss the role of public health nurses in finding, reporting, collecting, analyzing data, and following up on the disease. The paper requires a minimum of three references and 1250 words in APA format.
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docxarnoldmeredith47041
This document outlines a goal to improve the ability to seek first to understand others rather than be understood according to Habit 5. The author acknowledges they are able to communicate but struggles with listening skills. The goal is to practice actively listening and understanding what people are saying rather than being focused on themselves.
Write a Risk Management Plan for a School FacilityInclude th.docxarnoldmeredith47041
Write a Risk Management Plan for a School Facility
Include the following topics listed below
Write at least one page per topic, double spaced, Times Roman, Font Size 12
Provide References.
Use the APA Format
·
Personnel Management
·
Indemnification Waiver
·
General Supervisory Practices
·
Crowd Management Plan
.
Write a review that 750 - 1000 words in length about one chapter in .docxarnoldmeredith47041
Write a review that 750 - 1000 words in length about one chapter in the Niebuhr textbook. Half will be a summary and half will be the student’s personal reflection. The reflection should include points that the student agrees and disagrees with Niebuhr about and why.
Niebuhr, H. Richard. (2001).
Christ and Culture
. New York: Harper and Row.
.
write a resume using the example belowCONTACT INFOFirs.docxarnoldmeredith47041
write a resume using the example below
CONTACT INFO
First and Last Name
City, State (Optional) | Best Phone Number to Reach You | Appropriate Email Address
SUMMARY OF QUALIFICATIONS
· 3-5 sentences describing why you would be a great fit for the position.
· Describe your relevant accomplishments, strengths, knowledge, experience, skillsets, and languages.
· This is the “preview to the movie.” Highlight your best qualifications so they choose to read the rest of the resume.
· Use bullet points to distinguish each sentence if more aesthetically pleasing.
PROFESSIONAL EXPERIENCE
· List jobs you have held in the past 10 years; only list older jobs if they are directly related to desired job.
· Do NOT list a job if you worked at a place of employment for less than 3 months.
· If you have some jobs that are related to your desired position/field and others that are not, only list the related jobs in this section. Create an “Additional Work History” section at the end of the resume for the non-related jobs.
· Use bullet points to list achievements, results, recognitions, and duties for each job.
Company Name - City, State
Job Title
Start Year - End Year or Present
3-5 achievements, results, recognitions, and duties
INTERNSHIP / EXTERNSHIP / CLINICAL EXPERIENCE
· This section should take priority over others unless you have previous work history in exact field.
Company Name - City, State
Title or Role
Month Year - Month Year
2-3 Main Responsibilities/Duties
CERTIFICATIONS and LICENSURES
Name of Certification/License
Issuing Company or Organization
Certification/License Number
Expiration Month Year
EDUCATION
· Only include schools that you received a degree or relevant certifications from, or are currently attending.
· Do NOT include your high school.
School Name - City, State
Major/Area of Study
Degree Earned
Graduation Year/Estimated Graduation Month Year
CORE COMPETENCIES
· List 6-9 competencies, skills, traits, and/or areas of proficiency that directly relate to the job.
· Utilize the job description to find the types of preferred and/or required skills and traits.
· This is a great area to match keywords from the job description that may not otherwise be easily listed in your resume.
· Use bullet points and columns to make this section more aesthetically pleasing and organized.
RELEVANT COURSEWORK
· List the core courses you have already completed and are currently in.
· Use bullet points to list each course.
VOLUNTEER WORK / AFFILIATIONS
Organization
City, State
example of resume
SHARKLY BRUCE, COTA/L
Amity Island, FL | (975) 206-1120 |
[email protected]
SUMMARY OF QUALIFICATIONS
· Certified Occupational Therapy Assistant with two 8-week rotations of Level II OTA fieldwork, as well as 3 years of previous healthcare experience in a hospital setting.
· Extensive direct care experience assisting patients after treatment of traumatic wounds from local wildlife attacks.
· Proven track record o.
Write a resume and cover letter for the following positionOnline.docxarnoldmeredith47041
Write a resume and cover letter for the following position
Online Marketing Strategist
Riverside, CA 92507
Full-time, Contract
Raincross is seeking a full time marketing rockstar to manage client accounts, devise and implement strategies and craft winning content daily. Candidates must be extremely motivated, possess excellent research and writing skills and pay very close attention to detail.
Requirements
Master the art of creating content: blog articles, updates on social sites, press releases, infographics (or at least the concepts behind them for our design team to create) are all part of the ideal candidates daily tasks
Research and analyze the latest data to uncover gaps; stay up to date on the latest trends and be quick enough to jump on them before they pass
Convert through compelling CTA’s: Create copy for signage, newsletters, email campaigns, online promotions, ads, etc to help brand reach their goals
A/B test: Do you know what works and what doesn’t?
Craft brand strategies: Figure out what they’re doing right, what they’re doing wrong and create strategies to implement. Research to include competitor marketing, trends, etc. Come up with creative new ways to help clients grow and become more successful
Social advertising: Run ads on Facebook, Instagram, Twitter, LinkedIn and any other social platform that allows us to
Responsibilities
Bachelors Degree in Communications, Marketing or similar
Excellent written and verbal communication and customer service skills
Must take initiative, possess creativity, be hands on and a team player
Should be open-minded, a fast learner, enthusiastic, and adaptable
Experience in writing, copy-writing, researching trends, analyzing data, a/b testing, brand strategies and running social ads and campaigns a huge plus
.
Write a response to the peers post based on the readings. Origi.docxarnoldmeredith47041
Write a response to the peer's post based on the readings.
Original Prompt:
Compare Carroll's strategies for creating sound in
Jabberwocky
with those used by Swenson in
A Nosty
Fright.
Pay attention to connotative and denotative meanings of the words and how the poet plays with sound.
Edilzon Ramirez
Response to Prompt:
In both poems there is a common element. And that is a wordplay to make nonsense poetry. The effect of this, is that we must think more in depth to figure out the real meaning behind the works of literature. In Jabberwocky, the writer begins by setting up the mood giving us the background of the events that are about to occur. The use of exclamation marks throughout the poem afterwards, are what in my opinion, give it the sound. For example, “O frabjous day! Callooh! Callay!” suggests sort of a proud/relived cry. Which is furthered backed up by the whimsical words that have a positive connation to them due to the slaying of the jabberwocky, who terrorized the people.
While in “A Nosty Fright” another poem with nonsense words or portmanteau the mood is sad, and it only becomes gloomier. Like Miss Brill, the poet describes things together, in the first stanza “roldengod and the soneyhuckle” and jumps to a lonely chipmunk, suggesting that it has lost its companion. There is hope for it when it meets the grasshopper. Ultimately, it comes to an end “Here we part,” said the hassgropper. “Pere we hart,” mipchunk, too”. All hope is lost for the chipmunk and is waiting for the winter to come. This symbolizes death because during the months of October, November, and December many mammals including the chipmunks hibernate and its almost like it wanted to go to sleep permanently remarking things like “Will it ever be morning, Nofember virst”.
Some say, that the chipmunk is a representation of the author and her sexuality. She like the chipmunk, was alone and the typhoon that was mentioned earlier, was her losing her mind. The words and the sounds they make, further makes this evident because it is gibberish written by someone who is broken.
(Your response to your peer should add or extend the point given by your peer.)
.
Write a response to the following prompt.Analyze the characteriz.docxarnoldmeredith47041
Write a response to the following prompt.
Analyze the characterization Shakespeare employed in
Julius Caesar
, paying particular attention to the role of women. (50 pts) Remember, as you write, to use the language of characterization as we have discussed in class.
.
Write a response to a peers post that adds or extends to the discus.docxarnoldmeredith47041
Write a response to a peer's post that adds or extends to the discussion point of your peer by Friday 07/24/2020.
This week's discussion prompt:
Explain how Faith in "Young Goodman Brown," Georgiana in "The Birthmark," and Elizabeth in "The Black Minister's Veil" are use to reveal some truth about the central male characters in each story. Describe the similarities that you see among these women characters.
Peer's Post:
-Emily Seide
In each of the three short stories, the female characters play a large role in the character development of the three male protagonists (Goodman, Aylmer, and Hooper). Throughout each story, the women leave a lasting impact on their significant other’s mentality of the world and perception of others. In “Young Goodman Brown”, Brown is faced with troubling sights that make him alter his point of view on his town and the townspeople. Brown was introduced to the true form of some nasty people, including his wife, Faith. When he returns home the next morning from a place of sinister evil, his encounter with Faith and his townspeople has made him a hardcore skeptic of anyone and everyone around him. Goodman Brown never trusted a soul after that night because he was forced to believe that evil resides in everyone. In “The Birthmark”, Aylmer goes insane trying to remove his wife, Georgiana’s, birthmark. Even after hearing how beautiful and well liked she is, Georgiana agrees to get her birthmark removed. Rather than seeing this as a perfect part of her, Aylmer sees the birthmark as a flaw that gives her an imperfect complexion. Later in the story, as the birthmark fades and she wakes up, she states that he should’ve admired what he had in the first place, then dies. This made Aylmer realize that he took time for granted, and now he lives a life without Georgiana due to his impatience with her already beautiful complexion. And finally, in “The Minister’s Black Veil”, Reverend Hooper consistently wears a black veil that covers the majority of his face. Several people were afraid and intimidated by it, except for his fiancée, Elizabeth. After further questioning, she begins to fear the veil due to what it symbolizes- the sin in all human beings. Hooper’s plea for Elizabeth to stay reveals the extent of which he is willing to sacrifice, and the decision for him to continue to wear the veil reveals great sorrow; “Do not leave me in this miserable obscurity forever!” (Hawthorne, 36). In each of the short stories, each female character, always a love interest, is first skeptical of the main character’s choice of actions, then later comply. In each short story, a life lesson is learned for each male character.
Readings are attached!
.
Write a response mini-essay of at least 150 to 300 words on the dis.docxarnoldmeredith47041
Write a response mini-essay of at least 150 to 300 words on the discussion topic identified below. Take a position and defend it. (Specify a thesis and support it very briefly with evidence)
The response essay should provide one example from the contemporary world to support your
Position. Ideally you have a source reference for your example. You must have a source reference if you
Refer to any material which is neither common knowledge nor personal experience. essay should be typed using
APA style
feature with a title page and list of references if any are used.
Topic:
Technology changes education
Postman argues that television technology substantively changes aspects of culture such as news, politics, religion, and education in ways that suit the technology, not the human culture that uses the technology. It is a point others have made as well, though it is still contested by many other philosophers and social critics. One excellent example of technological change is on-line course delivery. While there are some who say that the new medium does not provide an education, others (such as your instructor) believe they can accomplish a better education in some subject areas. What have you noticed? What differences are there in on-line education that are due to the way it is technologically mediated? What differences do they make in the education you are receiving? Do you think this is a better or worse education? Why might your instructor think it can be better (and not just because he manages the class while in his pajamas)?
.
Write a response for each document.Instructions Your post sho.docxarnoldmeredith47041
Write a response for each document.
Instructions:
Your post should be a thoughtful response and should include outside reference material from the internet or primary literature. That reference should be referred to specifically with an in-text citation (author, year) and your post should have a bibliography with those outside sources you used cited in APA format.
.
write a resonse paper mla styleHAIRHair deeply affects people,.docxarnoldmeredith47041
write a resonse paper mla style
HAIR
Hair deeply affects people, can transfigure or repulse them. Symbolic of life, hair bolts from our head. Like the earth, it can be harvested, but it will rise again. We can change its color and texture when the mood strikes us, but in time it will return to its original form, just as Nature will in time turn our precisely laid-out cities into a weed-way. Giving one's lover a lock of hair to wear in a small locket [3] around his neck used to be a moving and tender gesture, but also a dangerous one, since to spell-casters, magicians, voodoo-ers, and necromancers of all sorts, a tuft of someone's hair could be used to cast a spell against them. In a variation on this theme, a medieval knight wore a lock of his lady's pubic hair into battle. Since one of the arch-tenets of courtly love was secrecy, choosing this tiny memento instead of a lock of hair from her head may have been more of a practical choice than a philosophical one, but it still symbolized her life-force, which he was carrying with him. Ancient male leaders wore long flowing tresses as a sign of virility (in fact,
"kaiser" and "tsar" both mean "long-haired"
). In the biblical story of Samson, the hero's loss of hair brings on his weakness and downfall, just as it did for the hero Gilgamesh before him. In Europe in more recent times, women who collaborated with the enemy in World War II were humiliated by having their hair cut short. Among some orthodox Jews, a young woman must cut off her hair when she marries, lest her husband find her too attractive and wish to have sex with her out of desire rather than for procreation. Rastafarians regard their dreadlocks as "high-tension cables to heaven." These days, to shock the bourgeoisie and establish their own identity, as every generation must, many young men and women wear their hair as freeform sculpture, with lacquered spikes, close-cropped patterns that resemble a formal garden maze, and colors borrowed from an aviary or spray-painted alley. The first time a student walked into my classroom wearing a "blue jay," it did startle me. Royal-blue slabs of hair were brushed and sprayed straight up along the sides of his head, a long jelly roll of white hair fell forward over his eyebrows, and the back was shiny black, brushed straight up and plastered close to the head. I didn't dislike it, it just seemed like a lot to fuss with each day. I'm sure my grandmother felt that way about my mother's "beehive," and I know my mother feels that way about the curly weather system which is my own mane of long thick hair. One's hairstyle can be the badge of a group, as we've always known -- look at the military's crew cut, or the hairstyles worn by some nuns and monks. In the sixties, wearing long hair, especially if you were a man, often fetched a vitriolic outburst from parents, which is why the musical Hair summed up a generation so beautifully. The police, who seemed so clean-cut and cropped then, were succee.
Write a response about the topic in the reading (see attached) and m.docxarnoldmeredith47041
Write a response about the topic in the reading (see attached) and make sure you include the following:
1. Brief summary of the reading
2. What was intersting?
3. The main points highlighted and what do you think of the reading?
( 2 page response)
.
Write a research report based on a hypothetical research study. Con.docxarnoldmeredith47041
Write a research report based on a hypothetical research study. Conducting research and writing a report is common practice for many students and practitioners in any of the behavioral sciences fields.
A research report, which is based on scientific method, is typically composed of the different sections listed below:
Introduction:
The introduction states a specific hypothesis and how that hypothesis was derived by connecting it to previous research.
Methods:
The methods section describes the details of how the hypothesis was tested and clarifies why the study was conducted in that particular way.
Results:
The results section is where the raw uninterpreted data is presented.
Discussion:
The discussion section is where an argument is presented on whether or not the data supports the hypothesis, the possible implications and limitations of the study, as well as possible future directions for this type of research.
Together, these sections should tell the reader what was done, how it was done, and what was learned through the research. You will create a research report based on a
hypothetical
problem, sample, results, and literature review. Organize your data by creating meaningful sections within your report. Make sure that you:
Apply key concepts of inferential hypothesis tests.
Interpret the research findings of the study.
Examine the assumptions and limitations of inferential tests.
Develop a practical application of the research principles covered in this course.
Focus of the Research Report
To begin, create a hypothetical research study (you do not have to carry out the study; you will just have to describe it) that is based on the three pieces of information listed below. Once you have your hypothetical study created, write a three- to four-page research report (excluding title and reference pages) that outlines the study. You are encouraged to be creative with your research study, but be sure to follow the format outlined below and adhere to APA formatting as outlined in the Ashford Writing Center.
Your hypothetical research study should be based on the following information:
Recent research has indicated that eating chocolate can improve memory. Jones and Wilson (2011) found that eating chocolate two hours before taking math tests improved scores significantly. Wong, Hideki, Anderson, and Skaarsgard (2009) found that women are better than men on memory tests after eating chocolate.
There were 50 men and 50 women who were randomly selected from a larger population.
A
t
-test was conducted to compare men and women’s performance on an assessment after eating chocolate. The results showed an independent
t
-test value of
t
.05(99) = 3.43;
p
< .05
Your research study must contain the following:
Title Page
Title of your report
Your name
The course
Instructor
Date
Introduction
Introduce the research topic, explain why it is important, and present the purpose of the paper and the resea.
Write a Research Paper with the topic Pregnancy in the adolesce.docxarnoldmeredith47041
Write a Research Paper with the topic: Pregnancy in the adolescent life.
The conditions are:
APA format
Double space
One inch margin on all sides
All paragraph in the body are indented
The title is centered on the page with your name and school institution
Paragraph 2, 3, and 4 need another inch more
All pages should be numbered and with citation
Apart of the Research paper write the topic sentence (a question or a statement) & the THESIS of the Research Paper. Write 3 citations for your Research Paper.
.
Write a Research Paper with the topic Autism a major problem. T.docxarnoldmeredith47041
Write a Research Paper with the topic: Autism a major problem.
The conditions are:
APA format
Double space
One inch margin on all sides
All paragraph in the body are indented
The title is centered on the page with your name and school institution
Paragraph 2, 3, and 4 need another inch more
All pages should be numbered and with citation
Apart of the Research paper write the topic sentence (a question or a statement) & the THESIS of the Research Paper.
Write 3 citations for your Research Paper.
.
Write a research paper that explains how Information Technology (IT).docxarnoldmeredith47041
Write a research paper that explains how Information Technology (IT) promotes getting people who are affected by policies involved in the policy-making process. Cite specific examples.
1000- 1200 words APA format and
Create a powerpoint presentation using 5 slides on the main points covered in your research paper. You may use a title slide and a reference slide.
Please find the attached text book.
.
Write a research paper outlining possible career paths in the field .docxarnoldmeredith47041
Write a research paper outlining possible career paths in the field of Human Resources Management (HRM) and based upon independent research discuss how different organizations might develop and implement a strategic HRM plan.
Research Paper Instructions:
IMPORTANT!!
Submit your work as an MS WORD ATTACHMENT in either a .doc, .docx, or .rtf format.
Please support your ideas, arguments, and opinions with independent research, include at least three (3) supporting references or sources (NOT Wikipedia, unknown, or anonymous sources), format your work in proper APA format, include a cover page, an abstract, an introduction and a labeled conclusion in accordance with the course rubric, a minimum of 3 FULL pages of written content, and a reference section. Double space all work and cite all listed references properly in text in accordance with the 6th edition of the APA manual, chapters 6 & 7.
.
Write a Research paper on the Legal issues associated with pentestin.docxarnoldmeredith47041
Write a Research paper on the Legal issues associated with pentesting.
Paper Specifics
3000 words (not counting citations)
APA format
Max team size of two
Minimum 5 academic sources
Provides clear summary and introduction to project scope; includes coherent discussion of key concepts, principles, and problem statement; develops clear context between project tasks and performing security testing in a virtual environment
Provides a thorough and concise summary of the project by listing the purpose and results of each test conducted; or research summary; clearly links the results with recommendations/research, which are supported by test data and external references
.
Write a research paper on one of the following topics .docxarnoldmeredith47041
Write a research paper on
one
of the following topics:
1. What are the effects of corruption on capitalism and foreign investment? (Unit II)
Be sure to include at least the following points in your paper:
What are the types of corruption?
What are effects of corruption on MNCs?
How can MNCs deal effectively with these problems?
2. How can MNCs effectively negotiate with local employees, local suppliers, and local governments in the Middle East? (Unit IV)
Be sure to include at least the following points in your paper:
What are some examples of negotiation cases in the Middle East?
How do MNCs use negotiation to solve problems?
What roles do different cultures have in negotiation?
3. Discuss the problems MNCs face when assigning expatriates to an Eastern European country and how they should support the expatriates. (Unit VII)
Be sure to include at least the following points in your paper:
What are problems for international assignments in Eastern Europe?
What are solutions for the problems?
What are strategies MNCs can implement to support their expatriates?
Directions:
The paper should be at least 750 words in length.
You are required to use a minimum of three scholarly sources for the paper.
All sources used must be referenced; paraphrased and quoted material must have accompanying APA citations.
.
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐄𝐏𝐏 𝐂𝐮𝐫𝐫𝐢𝐜𝐮𝐥𝐮𝐦 𝐢𝐧 𝐭𝐡𝐞 𝐏𝐡𝐢𝐥𝐢𝐩𝐩𝐢𝐧𝐞𝐬:
- Understand the goals and objectives of the Edukasyong Pantahanan at Pangkabuhayan (EPP) curriculum, recognizing its importance in fostering practical life skills and values among students. Students will also be able to identify the key components and subjects covered, such as agriculture, home economics, industrial arts, and information and communication technology.
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐍𝐚𝐭𝐮𝐫𝐞 𝐚𝐧𝐝 𝐒𝐜𝐨𝐩𝐞 𝐨𝐟 𝐚𝐧 𝐄𝐧𝐭𝐫𝐞𝐩𝐫𝐞𝐧𝐞𝐮𝐫:
-Define entrepreneurship, distinguishing it from general business activities by emphasizing its focus on innovation, risk-taking, and value creation. Students will describe the characteristics and traits of successful entrepreneurs, including their roles and responsibilities, and discuss the broader economic and social impacts of entrepreneurial activities on both local and global scales.
A Visual Guide to 1 Samuel | A Tale of Two HeartsSteve Thomason
These slides walk through the story of 1 Samuel. Samuel is the last judge of Israel. The people reject God and want a king. Saul is anointed as the first king, but he is not a good king. David, the shepherd boy is anointed and Saul is envious of him. David shows honor while Saul continues to self destruct.
This presentation was provided by Rebecca Benner, Ph.D., of the American Society of Anesthesiologists, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
Leveraging Generative AI to Drive Nonprofit InnovationTechSoup
In this webinar, participants learned how to utilize Generative AI to streamline operations and elevate member engagement. Amazon Web Service experts provided a customer specific use cases and dived into low/no-code tools that are quick and easy to deploy through Amazon Web Service (AWS.)
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
Gender and Mental Health - Counselling and Family Therapy Applications and In...
The Java Learning Kit Chapter 5 – Methods and Modular.docx
1. The Java Learning Kit: Chapter 5 – Methods and Modularity
Copyright 2015 by C. Herbert, all rights reserved.
Last edited January, 2015 by C. Herbert
This document is a chapter from a draft of the Java Learning
Kit, written by Charles Herbert, with editorial input from Craig
Nelson, Christopher Quinones, Matthew Staley, and Daphne
Herbert. It is available free of charge for students in Computer
Science courses at Community College of Philadelphia during
the Spring 2015 semester.
This material is protected by United States and international
copyright law and may not be reproduced, distributed,
transmitted, displayed, published or broadcast without the prior
written permission of the copyright holder. You may not alter
or remove any trademark, copyright or other notice from copies
of the material.
The Java Learning Kit:
Chapter 5
Methods and Modularity
2. Lesson 5.1 – User Created Methods in Java
Lesson 5.2 – Method Parameters
Lab 5A – Examining code with Several Methods
Lesson 5.3 – Top-Down Design and Modular Development
Lab 5B – Methods and Parameter Passing
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 2
Contents
Chapter 5 Learning Outcomes
...............................................................................................
..................... 3
User Created Methods in Java
......................................................................................... 4
Method Modifiers
...............................................................................................
................................ 4
Return Type
...............................................................................................
......................................... 6
Other method modifiers
...............................................................................................
...................... 7
3. Method Parameters
...............................................................................................
............................. 7
Invoking a Method and Parameter Passing
......................................................................................... 7
Method Documentation
...............................................................................................
...................... 9
CheckPoint 5.1
...............................................................................................
................................... 10
Lab 5A – Examining code with Several Methods
................................................................................... 11
Top-Down Design and Modular Development
.............................................................. 13
CheckPoint 5.2
...............................................................................................
................................... 15
Lab 5B – Methods and Parameter Passing
............................................................................................
16
Key Terms
...............................................................................................
.............................................. 21
Chapter Questions
...............................................................................................
................................. 21
4. Chapter Exercises
...............................................................................................
................................... 22
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 3
The Java Learning Kit: Chapter 2
Reading, Writing, and Arithmetic
This chapter introduces user-created methods in Java, along
with the accompanying
techniques of modular development and top-down design, also
known as structured
decomposition or functional decomposition.
Parameter passing between methods and polymorphic method
overloading are also
discussed.
Chapter 5 Learning Outcomes
Upon completion of this chapter students should be able to:
5. Oracle’s Java
Tutorials.
the difference
between a formal parameter list and an actual parameter list.
-down design of an algorithm, also
known as
structured decomposition or functional decomposition.
and several
advantages of
developing software in smaller modules.
demonstrating good
modular design and the proper use of parameter passing
between methods.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 4
User Created Methods in Java
So far we have only created software with a single method, the
6. main method in the single class in each
Java application we created. We have invoked other methods
from other classes, such as the Math class
and the Scanner class, but we have only created one method at a
time in our applications. Now we will
begin to work with multiple methods of our own.
The code for each method in Java software is defined in a
method declaration within a class. A method
declaration defines a method, with a method header, followed
by a block of code marked by braces.
According to Oracle’s Java tutorials, a method declaration has
six components – the five parts of the
method header and the method’s block of code1. A Java method
header includes method modifiers
(such as public and static), the return type of the method, the
method name, a set of parentheses which
contains the method’s parameters, and an exception list. The
parentheses are blank if there are no
parameters. In general the parts of a method header look like
this:
[modifiers] [return type] method name(formal parameter list)
[exception list]
Here is an example. This method has no exception list after the
parameter list. If you do see the word
7. throws after a parameter list, then that is the beginning of the
exception list, which is also known as a
thrown exception clause. We will learn about exceptions later in
the course.
public double overTime(double hours, double rate) {
double overtimeHours;
double overtimePay;
overtimeHours = hours - 40;
overtimePay = overtimeHours *rate * 1.5;
return overtimePay;
} // end (overtime(( double hours, double rate)
Method Modifiers
Method modifiers provide the compiler with information about
the nature of the method. The most
common method modifier is called the access modifier, which
8. sets the access level for the method. Java
methods may have public, private, or protected access.
any other software.
within the class which contains the
method.
1 See:
http://docs.oracle.com/javase/tutorial/java/javaOO/methods.htm
l
method header
parameter list return type access modifier method name
Figure 1 – parts of a
method header
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 5
subclasses of a class may invoke protected
9. methods. We learn about subclasses later in the semester when
we learn about inheritance.
Why Java Applications Need a Public Static Void Main()
Method
Every java application must start somewhere.
A Java application can contain many methods in many different
classes and can also import
methods from classes that are not part of the application’s own
source code, but that are defined
elsewhere.
At least one class in a Java application must have the same
name as the application’s software
package. This class must contain a method named main, which
will be the method that is executed
when the software application runs. The main method will
contain any calls or references to other
methods used within the application.
A Java application’s main method must be public, which means
it is available to be run from outside
of its own software package. This is necessary so that the
operating system can start the application
by running the main method. This means that the access
modifier public must be included in a main
10. method’s header.
An application’s main method is a class-level method,
associated with the overall application’s and
not with an instance of a class, therefore its header must have
the access modifier static, which
identifies class-level methods, variables, and so on.
The main method for a java application does not return any
values. Hence it must be marked with
the access modifier void in the method’s header, which
indicates it does not return any user defined
values. Actually, when a java application terminates it will
send a code to the operating system to
indicate whether or not the application terminated normally.
However, this message passing
happens automatically, and we do not need to be concerned
about it, at least not for now.)
Putting all of this together, the modifiers public, static and void
must come before the method name
in the method header for a main method. For example, a
payroll application whose application
software package is named Payroll, must have a payroll class
with the following method:
public static void main( String[] args) {
11. . . . method block of code follows . . .
} // end main()
The parameter for the main method is a String array of
arguments, which is why main methods
have the default parameter String[] args. (The terms parameter
and argument mean almost the
same thing, and are often used interchangeably.) Often this
parameter goes unused, but it is there
to enable operating system and the method to communicate with
one another.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 6
Another common method modifier is the static modifier.
According to the JLS, a method that is declared
static is called a class method. A static method is associated
with the class and not with an instance of
the class. It is invoked by using the class name, and not the
instance name, as part of its qualified name.
The main methods in the software we have written so far have
12. been declared public static void main(…).
We have also seen static methods in the Math class. Methods
such as Math.sqrt() and Math.random()
are class level methods that have been invoked using the name
of the class – the Math class.
The Scanner class methods we have used were not class level
methods. They were invoked using the
name of an instance of the class. We had to declare a new
instance of the Scanner class associated with
a particular input stream before we could use methods such as
nextLIne() in the example below. If the
static modifier is missing, then the method is an instance
method. If the static modifier is present, it is a
class method.
public static void main(String args[]) {
String name;
Scanner kb = new Scanner(System.in);
// say hello to the user and ask for the user’s name
System.out.println("Hello, please enter your name: ");
name = kb.nextLine();
13. . . . // the method continues . . .
Return Type
The return type in a method header declares the data type of the
value the method returns, or uses the
keyword void to indicate that the method does not return a
value. A method that does not return a
value is often called a void method. A void method is invoked
from another method by using the void
method’s name as if it is a new Java instruction.
A method that returns a value can called from anyplace in
another Java method where a variable or
literal of the same data type can be used. For example, the
Math.sqrt() method returns a value of data
type double. Therefore, it can be called from any place that a
variable type double or a double literal can
be used, such as in a math expression.
Methods that return a value, such as the
Math.sqrt() method, are often called inline
methods, because they can be invoked in a
Java statement “inline”, as shown on the left.
double result;
14. double num1;
result = 3 * num1 + 4;
result = 3 * Math.sqrt(10) + 4;
The nextLine() method that is invoked from the main() method
in Figure 2, above, has a return type of
String, so it can be used in a Java statement anyplace that a
String value can be used. In this example,
the value returned by the method is assigned to the String
variable name.
Figure 2 – part of
a main() method
The static modifier identifies the main()
method as a class-level method.
The nextLine() method is a instance method,
invoked using the name of the instance of
the Scanner class to which it applies, kb.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 7
15. Other method modifiers
There are several other modifiers, such as abstract, native,
strictfp, and synchronized, that can be used
in Java methods headers in addition to modifiers and return
types discussed here. They are beyond what
we need to use for now, but are listed and described online at:
http://docs.oracle.com/javase/tutorial/reflect/member/methodMo
difiers.html
Method Parameters
The list of variable declarations in parentheses following the
name of the method is the formal
parameter list. Formal parameters are local variables that will
hold the values passed to the method
when the method is invoked. They are declared in the method
header by listing the data types and
names of the variables. They may be used in the method just as
any other local variables may be used.
The scope of the variables declared in a formal parameter list is
the body of the method in whose
header the list appears.
In the overtime example shown again in Figure 3, the double
variables hours and rate are formal
parameters, which are used as local variables within the method.
16. Values will be passed to initialize
these variables when the method is invoked from another
method. The parameters that are passed to a
method are also called the arguments of a method.
/****************************************************
*************************/
/* The overtime method calculates the total overtime pay
following the time
* and a half for overtime rule. The result is to be added to the
regular pay
* for 40 hours.
*
* method parameters:
* double hours -- hours worked this week – usually close to
40.0
* double rate -- employee's pay rate a decimal values usually
less than 100
*
* The method returns the total overtime pay for hours above 40
as a double.
*/
public double overTime( double hours, double rate) {
17. double overtimeHours; // hours worked beyond 40
double overtimePay; // pay for overtime hours
// calculate overtime hours and pay
overtimeHours = hours - 40;
overtimePay = overtimeHours *rate * 1.5;
return overtimePay;
} // end overtime (double hours, double rate)
/****************************************************
*************************/
Invoking a Method and Parameter Passing
There are two ways a method may be invoked from another
method:
a Java statement;
user-created instruction in the
Java language.
The following examples show how to invoke methods.
Figure 3 – a user-
18. defined method
http://docs.oracle.com/javase/tutorial/reflect/member/methodMo
difiers.html
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 8
Example 1 - is a declaration for a method that returns a value.
We can see from the method header that
its return type is int. It also takes two integer parameters, a and
b.
// this method returns the lesser of two integer values
public int lesser( int a, int b) {
if ( b < a)
return b;
else
return a;
} // end lesser()
The method may be used anyplace in a Java expression where an
integer value can be used, such as in
the following statement in another method:
19. sum = grade 1 + grade2 + lesser(grade3, grade4);
In Java, parameters can be passed by value. Parameter passing
by value means that the values
specified in the actual parameter list are passed to the variables
declared in the formal parameter list.
When a method is invoked, the data types of the actual
parameters must match those of the formal
parameters and the actual parameters must be in the same order
as the formal parameters.
In this case, the values of the variables grade3 and grade4 are
the actual parameters for this invocation
of the method. They are passed to the variables a and b in the
method lesser(). The values of the
variables grade3 and grade4 are used to initialize the variables a
and b in the method lesser().
91
93
grade3
grade4
91
93
20. a
b
memory space for main() memory space for lesser()
94
87
grade1
grade2
If grade3 = 91 and grade4 = 93, then 91 is passed to a and 93 is
passed to b. There is no connection
between the variables in the two methods – the values from one
are simply passed to the other.
Example 2 - a value returning method named square
// this method returns the square of a double value
public double square( double x) {
return x * x;
} // end square()
The square() method is invoked in each of the following
statements:
dist = Math.sqrt( square(dx) + square(dy) );
21. area = square(s);
area = square(2.5);
actual parameters
type
Figure 4 – a method that
returns an int value
Figure 5 – parameter
passing by value
Figure 6 – a method that
returns a double value
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 9
The square() method is called four times, twice in the first
statement, once in the second statement.,
and once in the third statement. Notice that the third statement
uses the value 2.5 as an actual
22. parameter – no variable is used. This is perfectly acceptable
when passing by value, as Java does.
In the first statement, the value of dx is passed to square() and
the return value is used in place of the
method call square(dx), then the value of dy is passed to
square() and the return value is used in place of
the method call square(dy).
In the second statement, the value of s is passed to the square()
method and the formal parameter x is
initialized to the value of s. Area will be equal to s2.
In the third statement, the value 2.5 is passed to square and the
formal parameter x is initialized to 2.5.
Area will be equal to 2.52, which is 6.25.
*****************************************************
********************************
Example 3 - a void method
public void printCheck(String name, double netPay) {
System.out.println("Pay to the order of " + name);
System.out.printf("%8.2f”, netPay )
} // end printCheck()
A void method is used as if it is a new instruction in the Java
language:
23. printCheck(name, netPay);
printCheck(“Mary Jones”, 371.28);
printCheck( (fname + “ “ + lname), net);
In each case, the program will invoke printCheck(), passing the
values to the method. The method uses
the data to print the checks, but no value is returned to the
calling method.
The parameter passing works the same with void methods as
with value returning methods: the values
in the actual parameter list are used to initialize the variables in
the formal parameter list. In the first
statement above, the values of the variables name and netPay in
the calling method are used to
initialize empName and netPay in the printCheck() method.
Even though the two variables netPay have
the same name, they are still different variables not connected
to one another in any way. The value of
one is simply used to initialize the other.
In the second printCheck() statements above, literal values are
specified. These values will be used to
initialize name and netPay when printCheck() is invoked.
Method Documentation
24. The version of the overtime method shown in Figure 3 is
reasonably well-documented. Documentation
is an important part of programming. Method documentation is
an important part of object-oriented
programming.
Information in a comment describing each method should
include the method’s:
nctions
Figure 7 – a void method
– used “inline” as if it is
a new Java instruction
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 10
A method’s entry conditions include information about the
variables in the formal parameter list – such
as the range of values for each parameter – along with any other
special conditions that must be set
25. before the method runs. In the case of the overTime method in
Figure 3, the expected values of the
variables hours and rate are listed, but no special conditions are
mentioned.
The method documentation should briefly describe what the
method does and how the method
functions. It should tell the reader if any new or unusual
techniques are used in the method. If there
are several different way to do something, then the
documentation should be clear about which way is
used in this method. The documentation for the overTime()
method in Figure 3 makes it clear that the
“time and a half for overtime” rule was applied, and that the
method returns the total pay for all
overtime hours, not just the added half.
A method’s exit conditions should describe what value, if any, a
method returns and anything else the
method does that has an effect outside of the method. Does it
open a new I/O stream? Does it turn a
hardware device on or off? If it does anything with an effect
that will be present after the method runs,
then the exit conditions should say so. In the case of the
overtime method in Figure 3, the only exit
26. condition is that it returns a value. The data type and meaning
of the value returned should be clearly
described.
You should also do something with the documentation to clearly
separate one method from another in
a class. Programming styles differ, so there are many ways to
do this. In the case of the overtime
method, a line of stars and then a blank line are immediately
placed at the end of the method. This
makes it easier for a reader to distinguish between methods.
Remember, the documentation will be stripped from the code
when the software is compiled. It’s there
to make it easier for people to read and understand the code,
including you as the author of the code
who may need to come back to a method months or years later
and will need to understand how it
works. All documentation should be clear and reasonably
concise, but ease of understanding is the
most important factor. It is worth the time to make sure that
readers can understand your code.
CheckPoint 5.1
1. What are the six parts of a method declaration in Java,
according to Oracle’s Java Tutorials?
27. 2. What do the method modifiers public, private, and static each
mean in a method declaration?
3. What is a void method and how is it invoked form another
method?
4. How is a value returning method invoked from another
method?
5. What is a formal parameter list and how does it correspond to
an actual parameter list?
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 11
Lab 5A – Examining code with Several Methods
The following source code is in the NetBeans project
PayMethods, included in the file payMethods.zip in
the files for Week 5 in Canvas. It demonstrates the use of a
value returning method and a void method.
Your task is to download the file, unzip the NetBeans project,
then open it in NetBeans and examine the
code. You should be able to see how the a value returning
method and a voids method are invoked from
main, and how parameters are passed from the main method to
calculateGross() and to payrollReport().
28. Notice that calculateGross() and payrollReport() are both static
methods. This is because main() is a
static method, and static methods cannot call instance methods.
You should run the program to see how it works, then perhaps
try changing some of the actual
parameters to specific values to see how that works.
Notice the modularity of the program – we could change the
print report formats, for example, without
messing with the main() method. We could also modify the way
overtime is calculated without
changing any other methods.
package paymethods;
import java.util.Scanner;
/* CSCI 111 Fall 2013
* Sample program - payroll methods
* This program has an example of a value returning method and
a void method
*/
public class PayMethods {
29. public static void main(String[] args) {
String fname; // employee's first name
String lname; // employee's last name
double hours; // hours worked in the week
double rate; // hourly pay rate
double gross; // gross pay (hours * rate) + overtime
// set up input stream from the keyboard
Scanner keyboard = new Scanner(System.in);
// get employee's first name
System.out.print("Please enter the employee's first name: " );
fname = keyboard.next();
// get employee's last name
System.out.print("Please enter the employee's last name: " );
lname = keyboard.next();
// get employee's hours
System.out.print("Please enter the hours for " + fname +" " +
30. lname+ ": ");
hours = keyboard.nextDouble();
// get employee's rate
System.out.print("Please enter the pay rate for " + fname +" "
+ lname+ ": ");
rate = keyboard.nextDouble();
Figure 8 – a payroll
program composed
of several methods
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 12
// call method to calculate gross
// This value returning method is used inline, gross is set to
the value it returns
gross = calculateGross(hours, rate);
// call method to print payroll report
// this void method is used as if it is a new instruction in Java
31. // the actual parameters must correspond with the method's
formal parameter list
payrollReport(fname, lname, hours, rate, gross );
} // end main()
/****************************************************
*************************/
/* This method calculates gross pay using the time and a half
for overtime rule.
* it has two parameters,
* the hours worked during the week double hrs
* the pay rate double rt
*
* it returns the gross pay
*/
public static double calculateGross(double hrs, double rt ) {
double gr; // gross pay
double ot; // overtime pay
32. gr = hrs * rt;
if (hrs > 40)
ot = (hrs-40) * .5 * rt; // overtime bonus
else
ot = 0;
gr = gr + ot;
return gr;
} // end calculateGross
/****************************************************
*************************/
/* this method prints a payroll report
* it takes four parameters,
* employeee's first name String fname
* employee's last name String lname
* the hours worked during the week double hrs
* the pay rate double rate
*/
33. public static void payrollReport(String fname, String lname,
double hrs, double rt, double gross ) {
// print the payroll report
System.out.printf("%n%-12s%-12s%8s%8s%9s%n", "first",
"last",
"Hours", "Rate", "Gross");
System.out.printf("%-12s%-12s%8.2f%8.2f%,9.2f%n", fname,
lname,
hrs,rt, gross);
} // end payrollReport()
} // end class
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 13
Top-Down Design and Modular Development
It’s hard to solve big problems.
It’s easier to solve small problems than it is to solve big ones.
34. Computer programmers use a divide and conquer approach to
problem solving:
This process is a combination of techniques known as top-down
design and modular development.
Top-down design is the process of designing a solution to a
problem by systematically breaking a
problem into smaller, more manageable parts.
First, start with a clear statement of the problem or concept – a
single big idea. Next, break it down into
several parts. If any of those parts can be further broken down,
then the process continues until you
have a collection of parts that each do one thing.
The final design might look something like this organizational
chart, showing the overall structure of
separate units that form a single complex entity.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
35. Edition pg. 14
An organizational chart is like an upside down tree, with nodes
representing each process. The leaf
nodes are those at the end of each branch of the tree. The leaf
nodes represent modules that need to
be developed and then recombined to create the overall solution
to the original problem.
Top-down design leads to modular development.Modular
development is the process of developing
software modules individually, then combining the modules to
form a solution to an overall problem.
Figure 9 – an organizational chart showing
units that form a single complex entity
Figure 10 the leaf nodes of
an organizational chart
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 15
Modular development facilitates production of computer
36. software because it:
… makes a large project more manageable.
Smaller and less complex tasks are easier to understand than
larger ones and are less
demanding of resources.
… is faster for large projects.
Different people can work on different modules, and then put
their work together. This means
that different modules can be developed at the same time, which
speeds up the overall project.
… leads to a higher quality product.
Programmers with knowledge and skills in a specific area, such
as graphics, accounting, or data
communications, can be assigned to the parts of the project that
require those skills.
…makes it easier to find and correct errors.
Often, the hardest part of correcting an error in computer
software is finding out exactly what is
causing the error. Modular development makes it easier to
isolate the part of the software that
is causing trouble.
… increases the reusability of solutions.
37. Solution
s to smaller problems are more likely to be useful elsewhere
than solutions to bigger
problems. They are more likely to be reusable code. Reusable
code is code that can be written
once, then called upon again in similar situations. It makes
programming easier because you
only need to develop the solution to a problem once; then you
can call up that code whenever
you need it. Modules developed as part of one project, can be
reused later as parts of other
projects, modified if necessary to fit new situations. Over time,
libraries of software modules for
different tasks can be created. Libraries of objects can be
created using object-oriented
38. programming languages.
Most computer systems are filled with layers of short
programming modules that are constantly reused
in different situations. Our challenge as programmers is to
decide what the modules should be. Each
module should carry out one clearly defined process. It should
be easy to understand what the module
does. Each module should form a single complete process that
makes sense all by itself.
Top-down development is used to figure out what the modules
are needed in a software development
project and how they should be organized. Modular
development involves building those modules as
separate methods, then combining them to form a complete
software solution for the project.
CheckPoint 5.2
39. 1. What are Java’s nine built-in data types and how do they fit
into four major categories?
2. Which Java built-in data type is not a primitive data type?
3. How do each of Java’s integer data types differ from one
another?
4. What is a literal and how are literals represented for different
built-in data types?
5. Describe the formats used to store floating point data in
memory.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 16
Lab 5B – Methods and Parameter Passing
In this example we will develop a modular solution for a
40. problem that is similar to the homework
assignment from chapter 3.
We wish to input the x and y coordinates for two points in the
Cartesian plane, and find the distance
between the two, then print a report telling the user the distance
between the two points and the
quadrant that each point is in.
The distance between two points whose coordinates are (x1,y1)
and (x2, y2) is √��2 + ��2 where Δx
is the difference between the two x coordinates (x1- x2)and Δy
is the difference between the y
coordinates (y1- y2).
The example on the right also shows us
that the quadrants of a Cartesian plane
are numbered I through IV, with the
following properties:
41. -negative,
the point is in Quadrant I.
f x is negative and y is non-negative,
the point is in Quadrant II
the point is in Quadrant III.
-negative and y is negative,
the point is in Quadrant IV.
Y axis
X axis
(4,4)
Δy = 8
(0,0)
Quadrant IQuadrant II
Quadrant III Quadrant IV
42. (-2,-4) Δx = 6
Once we understand the specifications, we can make an outline
of what our software should do:
1. get the coordinates of two points: (x1, y1) and (x2, y2)
2. calculate the distance between the two points:
-x2; deltaY = y1-y2;
3. determine which quadrant (x1, y1) is in:
drant III
4. determine which quadrant (x2, y2) is in:
43. 5. print results
Figure 11 – two points
in a Cartesian plane
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 17
The similarity of steps 3 and 4 indicate that this would be good
place for reusable code – one method
44. that can be used twice, but each time with different values
passed to the method. Step 2 is also a good
place for a method, with the details of the calculation in the
method.
Step 1 might seem like a good place for a method – we get four
numbers from the user, each in the
same manner. However, remember that methods can only return
one value, so we really don’t gain
much by making this a separate method. It is a judgment call
and a matter of programming style – it
could be done with four calls to one method, but in this case we
will use four different sets of
statements in the main method.
Here in the design of our software, listing descriptions of the
methods with return types and formal
parameters:
46. X >=0) && (Y<0) Q =“Quadrant IV”
The code in Figure 12 starting on the next page was developed
from these specifications.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 18
/*
* program to calculate the distance between two points
* CSCI 111 Fall 2103
* last edited Sept 24, 2013 by C. Herbert
47. */
package twopoints;
import java.util.Scanner;
public class TwoPoints {
// The main method gets x and y for two points
// Calls methods to calculate the distance between the two
// and to determine the quadrant of each point
// then outputs the result
public static void main(String[] args) {
//declare variables
double x1,y1,x2,y2; // coordinates of (x1,y1) and
48. (x2,y2)
double dist; // distance between (x1,y1) and
(x2,y2)
String Q1, Q2; // quadrant containing (x1,y1) and
(x2,y2)
// set up instacne of Scanner for input
Scanner kb = new Scanner(System.in);
// get input in prompt & capture pairs
System.out.print("Enter the x coordinate of point 1 :");
x1 = kb.nextDouble();
System.out.print("Enter the y coordinate of point 1 :");
y1 = kb.nextDouble();
49. System.out.print("Enter the x coordinate of point 2 :");
x2 = kb.nextDouble();
System.out.print("Enter the y coordinate of point 2 :");
y2 = kb.nextDouble();
// call calcDistance()
dist = calcDistance( x1, y1, x2, y2);
// call findQuadrant(point1)
Q1 = findQuadrant(x1, y1);
// call findQuadrant(point2)
Q2 = findQuadrant(x2, y2);
50. // output results
System.out.println("nPoint 1 is ("+ x1 + "," + y1 + ")");
System.out.println("Point 2 is ("+ x2 + "," + y2 + ")n");
System.out.printf("The distance between the two points
is: %-8.2f%n", dist );
System.out.println("Point 1 is in " + Q1);
System.out.println("Point 2 is in " + Q2);
} // end main()
/****************************************************
************************/
Figure 12 – a program
organized as 3 methods
51. JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 19
// this method calculates and returns the distance between
two points
public static double calcDistance(double x1,double
y1,double x2,double y2) {
double deltaX; // difference in x coordinates
double deltaY; // difference in x coordinates
double dist; // distance between (x1,y1) and (x2,y2)
deltaX = (x1-x2);
deltaY = (y1-y2);
52. dist = Math.hypot(deltaX, deltaY);
return dist;
/* this whole method could be one line:
* return Math.hypot( (x1-x2), (y1-y2) );
*/
} // end calcDistance() {
/****************************************************
************************/
// this method returns the quadrant that contains the point
public static String findQuadrant(double x,double y) {
String Q; //quadrant message
53. if ( (x >= 0.0) && (y >= 0.0) )
Q = "Quadrant I";
else if ( (x < 0.0 ) && ( y >= 0.0) )
Q = "Quadrant II";
else if ( (x < 0) && (y < 0.0) )
Q ="Quadrant III";
else // ( (x >= 0) && (y < 0.0) )
Q = "Quadrant IV";
return Q;
} // end findQuadrant
} // end class
Here is sample output from the program:
54. Enter the x coordinate of point 1 :3
Enter the y coordinate of point 1 :4
Enter the x coordinate of point 2 :-3
Enter the y coordinate of point 2 :-4
Point 1 is (3.0,4.0)
Point 2 is (-3.0,-4.0)
The distance between the two points is: 10.00
Point 1 is in Quadrant I
Point 2 is in Quadrant III
The code in Figure 13 on the next page contains an alternative
version of the same program as Figure
12. To the user, the two programs look the same. They have
55. identical input and output. They are in the
Week 5 Canvas files. These two Java applications are the
topic of the Week 5 class discussion.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 20
/* distance between two points - alternative programming style
* CSCI 111 Spring 2015 last edited Sept 24, 2013 by C.
Herbert
*/
package twopointsb;
import java.util.Scanner;
public class TwoPointsB {
56. // The main method calls a methods to calculate the distance
between
// two points, then prints that distance and the quadrant of
each point
public static void main(String[] args) {
double x1,y1,x2,y2;
double dist;
// input coordinates
x1 = inCor("x", "1");
y1 = inCor("y", "1");
x2 = inCor("x", "2");
y2 = inCor("y", "2");
57. dist = Math.hypot( (x1-x2), (y1-y2) );
System.out.println("nPoint 1 is ("+ x1 + "," + y1 + ")");
System.out.println("Point 2 is ("+ x2 + "," + y2 + ")n");
System.out.printf("The distance between the two points
is: %-8.2f%n", dist );
printQuadrant("1", x1 , y1);
printQuadrant("2", x2 , y2);
} // end main()
/****************************************************
************************/
// this method gets as input a single coordinate of a point
public static double inCor(String axis, String point) {
58. // set up instance of Scanner for input
Scanner kb = new Scanner(System.in);
// get coordinate with prompt
System.out.print("Enter the " + axis + " coordinate of point
" + point + " :");
return kb.nextDouble();
} // end inCor()
/****************************************************
************************/
// this method prints the quadrant a point is in
public static void printQuadrant(String P, double x,double y)
{
59. if ( (x >= 0.0) && (y >= 0.00) )
System.out.println( "Point "+ P + " is in Quadrant I");
else if ( (x < 0.0 ) && ( y >= 0) )
System.out.println( "Point "+ P + " is in Quadrant II");
else if ( (x < 0) && (y < 0) )
System.out.println( "Point "+ P + " is in Quadrant III");
else // ( (x >= 0) && (y < 0) )
System.out.println( "Point "+ P + " is in Quadrant IV");
} // end printQuadrant
} // end class
Figure 13 –Figure 12’s
program reorganized.
62. Chapter Questions
1. So far this semester we have only created one method at a
time in our applications, but what are some
examples of methods from other classes that we have invoked in
our source code?
2. What is included in a method declaration?
3. What are the parts of a method header?
4. What is in the parentheses that follow the name of the method
in a method header? What does it
mean if the parentheses are blank?
5. What does it mean if the word throws follows a method
header?
6. Where does the return type belong in a method header?
7. What are the three access modifiers used in Java? What does
63. the private access modifier do?
8. When do we need a main method in a class? What modifiers
should be used with this method?
9. What does the JLS tell us about a method with the modifier
static? How is a static method invoked?
10. What methods that we have previously used were static
methods? What methods that we have
previously used were associated with an instance of a class?
11. What do we call a method that does not return as value?
What return type does it have?
12. Where can we use a method that returns a double value?
13. What is a method that can be invoked in a Java expression
often called?
14. What is the difference between the formal parameter list and
the actual parameters? Which of the two
declares new variables for a method? Which contains values
64. used to initialize variables?
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 22
15. What should be included in a comment describing each
method? What happens to this documentation
when a method is compiled?
16. What should be described as part of a method’s entry
conditions? What should be described as part of a
method’s exit conditions?
17. In what two ways can a method be invoked from another
method? How is a value returning method
invoked? How is a void method invoked?
18. How are parameters passed in Java? How must the values of
the actual parameters be organized when a
65. method is invoked?
19. When breaking a method down into parts using top-down
design, which nodes on an organizational
chart need to be developed and then recombined to create the
overall solution to the original problem?
20. What are five of the ways in which modular development
facilitates production of computer software?
Chapter Exercises
1. Match the actual parameters on the left with the correct
formal parameter list on the right.
(3,4)
(2.0,3.0)
(“Jones”, 97.5)
(“J00123453”, “B”)
(42, 10.50)
(double hours, double rate)
(String name, double pay)
67. 8 8 16 24 32 40 48 56 64 72
9 9 18 27 36 45 54 63 72 81
Write a program to print such a multiplication table, using a
method to print each row, which is invoked
from the method that prints the overall multiplication table.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 23
3. Printing Patterns
Nested for loops can print patterns of stars, such as the example
below:
for(i=1; i<=5; i++)
68. {
for(j=1; j<=10; j++)
{
System.out.print(“*”);
} // end for j
System.out.println();
} // end for i
Output from this program:
**********
**********
**********
**********
**********
Write a program with a main method which asks the user for the
number of rows and for the number of
columns, then calls a method which uses that information to
print a rectangle of stars.
69. 4. Celsius to Fahrenheit Table
Write a program to print a Celsius to Fahrenheit conversion
table that invokes a method to calculate
Fahrenheit temperature using formula is F = ( 9.0
5.0
C) + 32.0. The main method should have a loop to
print the table, calling the conversion method from within the
loop.
The table should include integer Celsius degrees from 0 to 40.
You program does not need to use
integers, but the table should display the Celsius temperature,
then the Fahrenheit accurate to one-
tenth of a degree. The first few entries from the table are
shown below:
Celsius Fahrenheit
0 32.0
1 33.8
70. 2 35.6
3 37.4
5. We wish to write a modular program that can be used to
calculate monthly payments on a car loan. The
formula is: payment =
������ ����∗ ������
1−(1+������ ����)−����ℎ�
The program will be composed of several methods – a main
method, a monthly interest rate method, a
monthly payment method, and an output method.
The main method should:
1. ask the user for
- the loan amount
71. - the annual interest rate ( as a decimal, 7.5% is 0.075 )
- the number of months
2. call a method to calculate and return the monthly payment
(Note: The formula uses monthly rate. Annual rate is input.
monthly rate = annual rate/12)
3. call a method to print a loan statement showing the amount
borrowed, the annual interest
rate, the number of months, and the monthly payment
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 24
6. International Gymnastics Scoring
72. We wish to write a program to quickly calculate gymnastics
scores for an international competition. Six
judges are judging the competition, numbered 1 through 6 for
anonymity. The program should have a
loop that:
1. calls a method asking for the score from a single judge, The
method should print the judge
number and score and return the judges score
2. adds the returned score to a total score.
After the loop is done, your program should call a method that
calculates and displays the average
score.
Scores are in the range 0 to 10 with one decimal place, such as
8.5. The average should be displayed
with two decimal places.
73. Here is a sample of the output:
Score for Judge 1: 8.5
Score for Judge 2: 8.7
Score for Judge 3: 8.4
Score for Judge 4: 9.1
Score for Judge 5: 8.9
Score for Judge 6: 9.0
The average score is: 8.77
7. Test for Divisibility
If the remainder from dividing A by B is zero, then A is a
multiple of B ( A is evenly divisible by B ).
For example, the remainder from dividing 6, 9, or 12 by 3 is 0,
which means 6, 9, and 12 are all multiples
74. of 3.
Write a program with a loop to to print the numbers from 1 to
25, and within the loop, invokes a
method to see if the number is a multiple of 2, a method to see
if the number is a multiple of 3, and a
method to see if the number is a multiple of 5. The methods
should each print a message if the number
is a multiple of the value for which they are testing.
Here is a sample of part of the output:
1
2 multiple of 2
3 multiple of 3
4 multiple of 2
5 multiple of 5
75. 6 multiple of 2 multiple of 3
7
8 multiple of 2
9 multiple of 3
10 multiple of 2 multiple of 5
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 25
8. Estimate of a Definite Integral
Write the program to estimate a definite integral with
rectangles, with a loop that calls a method to
calculate the height and area of each rectangle.
76. A loop in a computer program can be used to approximate the
value of a definite integral. We can
break the integral into rectangles, find the area of each
rectangle then add the areas together to get the
total area, as shown in the accompanying diagram. In practice,
we could make the width small enough
to achieved the desired accuracy in estimating the area under
the curve.
y = 9-x2
area under the curve
estimated by rectangles
As the width of the rectangles gets progressively smaller, their
total area gets closer to the total area
under the curve. This is an old method that predates Calculus.
Both Leibnitz and Newton used this
77. method, eventually developing calculus from the concept of
infinitesimals, which, in the case of our
rectangles, would amount to asking, what would the total area
be if we had very many rectangles with
very small width?
This was tedious by hand, but we now have computers. We can
set the width of the rectangle. The
height of the rectangle is the y value at point x. So for example,
if we need to solve:
∫ 9 − �2 ��
−3
+3
The starting point is -3, the ending point is +3, and the height of
the rectangle at each value of x in
between the two is 9 − �2 ; Y at each x is the is the height of
the rectangle at that x. We can use a width
78. of 0.001, and write a loop like this:
for x = -3 to +3 step 0.0001 // x is -3.00, then -2.9, then -2.8,
etc.
{
y = 9 − �2 ; // the height is the y value at each x
area = y * .01; // the width is the increment, in this case 0.1
totalArea = totalArea + area;
}
In this version of the program, the statements in the box above
should be in a separate method, invoked
from within the loop. When the loop is finished, totalArea is
the total area of the rectangles, which is
an approximation of the area under the curve.
79. Your lab report should explain what you did, and the result of
your work.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 26
9. Supermarket Checkout
Design a program for a terminal in a checkout line at a
supermarket. What are the tasks that are
included as part of checking out at a register? We must consider
things like the cost of each item,
weighing produce and looking up produce codes, the total cost
of the order, bonus card discounts, and
sales tax on taxable items only. You do not need to write the
program, but you should design the
methods using top down development and modular design.
Submit a description of the methods
80. needed for the program, a brief description of what each method
does, and a description of how the
methods are related to one another in terms of parameter
passing and return types.
10. We wish to write a program to draw the scene below. We
can create methods to draw primitive shapes,
as follows:
circle() takes x and y coordinates of center point, the radius,
and the color
triangle() takes x and y coordinates of each of three endpoints
and the color
rectangle() takes x and y coordinates of each of four corner
points and the color
Create a modular design for software to draw the scene using
the methods above. The software should
be layered. For example, a house() method should use the
81. primitive graphics methods to draw the
house.
Your design document should list and briefly describe each
method, including and what it does,
parameters, and any methods the method calls. Your list should
start with the main method.
— End of Chapter 5 —
The Java Learning Kit: Chapter 6 – Arrays
82. Copyright 2015 by C. Herbert, all rights reserved.
Last edited January, 2015 by C. Herbert
This document is a chapter from a draft of the Java Learning
Kit, written by Charles Herbert, with editorial input from Craig
Nelson, Christopher Quinones, Matthew Staley, and Daphne
Herbert. It is available free of charge for students in Computer
Science courses at Community College of Philadelphia during
the Spring 2015 semester.
This material is protected by United States and international
copyright law and may not be reproduced, distributed,
transmitted, displayed, published or broadcast without the prior
written permission of the copyright holder. You may not alter
or remove any trademark, copyright or other notice from copies
of the material.
The Java Learning Kit:
Chapter 6
83. Arrays
Lesson 6.1 – Arrays
Lesson 6.2 – One Dimensional Arrays in Java
Lesson 6.3 – Operations on Numeric Arrays
Lesson 6.4 – Searching and Sorting Arrays
Lesson 6.5 – Text File Input and Output in Java
Lab 6 – Programming Example: Moving Data between Arrays
and Files
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 2
Contents
Chapter 6 Learning Outcomes
...............................................................................................
..................... 3
Arrays
84. ...............................................................................................
............................... 4
Array Storage in Computer Memory
...............................................................................................
.... 5
CheckPoint 6.1
...............................................................................................
..................................... 6
One Dimensional Arrays in Java
...................................................................................... 7
What is actually in an array in Java?
...............................................................................................
.... 7
Assigning Values to Array Elements
...............................................................................................
... 10
The Array length Property; Iterating an Array
................................................................................... 11
85. The Enhanced for Statement
...............................................................................................
............. 12
Copying an Array
...............................................................................................
................................ 13
Arrays as Method Parameters in Java
...............................................................................................
13
Passing an Array Element as a Method Parameter
........................................................................... 15
CheckPoint 6.2
...............................................................................................
................................... 15
Operations on Numeric Arrays
...................................................................................... 16
Sum, Average, and Count of Values in an Array
................................................................................ 16
86. The Minimum and Maximum Values in an Array
.............................................................................. 17
Searching and Sorting Arrays
........................................................................................ 18
Comparing Strings
...............................................................................................
.............................. 18
Linear Search of an Array
...............................................................................................
................... 18
Sorting an Array
............................................................................................ ...
................................. 21
Swapping the Values of Two Variables
.............................................................................................
22
CheckPoint 6.4
...............................................................................................
................................... 24
87. Text File Input and Output in Java
................................................................................. 25
Handling Data File Exceptions like Hot Potatoes
............................................................................... 26
A Technique for Writing Text Data Files using Java
........................................................................... 27
A Technique for Reading Text Data Files using Java
.......................................................................... 28
CheckPoint 6.5
...............................................................................................
................................... 29
Lab 6 – Programming Example: Moving Data between Arrays
and Files ............................................. 30
Key Terms
...............................................................................................
.............................................. 35
Chapter Questions
89. how arrays are stored in memory.
Lesson 2 shows how to implement arrays for Java’s built-in data
types.
Lesson 3 discusses simple statistical processing of numeric
arrays — finding the sum, average
minimum, and maximum in an array of numbers.
Lesson 4 looks at simple techniques for searching and sorting
arrays.
Lesson 5 introduces simple text file I/O in Java.
Chapter 6 Learning Outcomes
Upon completion of this chapter students should be able to:
stored in a
computer’s memory.
an array in Java; and how to declare an
90. array, initialize
an array, and iterate an array in Java.
parameter in Java;
and how to pass an individual array element as a method
parameter in Java.
iterate an array;
and pass both references to arrays and individual array elements
as
parameters.
operations on
numeric arrays, including counting array elements, and finding
the sum,
average, minimum and maximum of values in an array.
91. sum, average,
minimum and maximum of values in an array.
algorithm for a linear to search of an array.
two variables,
search an array, and sort an array.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 4
Arrays
Until now we have been using single variables in our Java
programs. Java, like most other programming
92. languages, Java also supports arrays. An array is a set of
indexed variables, all of the same data type.
Instead of just having individual variables such as x, y, or
empName, we can have a set of indexed
variables such as x1, x2, x3, … and so on, where the value of
the index identifies an element of an array.
Each element of an array is an individual data item in the array,
such as:
empName0, empName1, empName2, … empNamen-1
In mathematics, such an array is also referred to as a set of
subscripted variables, because the index is
written as a subscript. In Java, they may also be called
subscripted variables, but instead of using
subscripts, Java uses square brackets following the variable
name to indicate an array or an element in
an array. empName0, empName1, employname2… from
93. mathematics would be written as empName[0] ,
empName[1], empName [2] … empName [n-1] in Java.
empName is the name of the array; whereas
empName[i], where i is an integer, is an element in the array
empName. The index values in an array
start at zero for reasons we will see later in this chapter.
empName[0] , empName[1], empName[2] … empName[n-1]
Arrays are very useful for storing and working with sets of
similar data items, such as lists of test scores.
We will see how to set up an array to hold a set of numbers,
such as test scores, then write code to find
the sum, the average, the minimum or the maximum of the
numbers. Once data has been established in
the computer’s memory as an array, we can do many things with
the data, including conducting a full
statistical analysis of the data, searching the data for specific
94. items, or sorting the data. Later, when we
learn to work with objects, we can set up an array of objects,
such an array of student records with
properties like student number, first name, last name, address,
and major, then we can sort or search
through the data according to any of the object’s properties.
But for now, we will only work with arrays
of primitive data types and Strings.
Most high-level programming languages support using arrays of
data. They generally have two different
type of arrays, single-dimensional arrays and mutli-dimensional
arrays. A single dimensional array, also
called a linear array, is an array with only one index variable,
forming what can be thought of as a line of
data items. The above example of empName[0] , empName[1],
empName [2] … empName [n-1] is a one
95. dimensional linear array.
Multi-dimensional arrays have multiple index variables, such as
the two-dimensional array shown here:
a0,0 a0,1 a0,2 . . . a0,n
a1,0 a1,1 a1,2 . . . a1,n
a2,0 a2,1 a2,2 . . . a2,n
am,0 am,1 am,2 . . . am,n
This is a two dimensional array from the world of mathematics,
forming a table with m rows and n
columns. In Java, the array would look like this:
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 5
a[0,0] a[0,1] a[0,2 ]. . . a[0,n]
a[1,0] a[1,1] a[1,2 ]. . . a[1,n]
96. a[2,0] a[2,1] a[2,2 ]. . . a[2,n]
a[m,0] a[m,1] a[m,2] . . . a[m,n]
Two dimensional arrays can be used to represent tables of data
with rows and columns of information,
similar to an electronic spreadsheet. They are often used for
matrices in linear algebra problems.
Multi-dimensional arrays can have more than two dimensions.
A three dimensional array could, for
example, represent a three-dimensional matrix for solving
problems related to three-dimensional
Euclidean space with x, y, and z coordinates. However, for the
remainder of this chapter we will stick
with simple single dimensional arrays, leaving the more
complex problems for another day.
Array Storage in Computer Memory
97. The values for variables in a computer program are stored in a
computer’s internal memory while the
program runs. Hence, each variable name is associated with a
specific address in the computer’s
memory. This matching of variables to memory addresses is
usually managed by the computer’s
operating system with a symbol table. A symbol table is a list
of symbolic names, such as the names of
methods, classes, and variables, mapped to specific addresses in
a computer’s internal memory.
Almost all modern computer systems have byte addressable
memory, meaning that bytes in a
computer’s memory are sequentially numbered, regardless of
the word length of a particular processing
unit. There are many advantages to this, which are discussed in
computer architecture and organization
courses such as CSCI 213– Computer Organization at
98. Community College of Philadelphia.
The following example shows how an operating system keeps
track of the values of variables using a
symbol table. The memory map shows us how space is allocated
in the computer’s memory.
variables symbol table memory map
int score; score 4000 4000 score
double velocity; velocity 4004 4001
int colorDepth; colorDepth 400C 4002
boolean transparent; transparent 4010 4003
4004 velocity
4005
Memory is allocated according to how variables are declared.
4006
99. Space is allocated based on data types, as described back in
chapter 2, for example:
int 32 bits (4 bytes)
double 64 bits (8 bytes)
boolean (1 byte in this system)
The symbol table records where variables are stored
in the internal memory. Memory addresses are hexadecimal
(base 16).
4007
4008
4009
400A
400B
400C color depth
400D
400E
100. 400F
4010 transparent
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 6
When an array is declared, the operating system only keeps
track of array’s base address, which is the
location where the array starts in memory. Here is an example:
CheckPoint 6.1
1. What is the relationship among the terms array, indexed
variables, and subscripted variables?
2. What is a linear array?
3. What does it mean to say that most computers use byte-
addressable memory?
101. 4. If array begins at memory address 5000 and each array
element requires 16 bits of storage
space, where will the array element with index 3 be stored in
memory?
5. How can arrays be used to represent tables of data with rows
and columns, similar to an
electronic spreadsheet?
variables symbol table memory map
priority = new int [6]; priority 4000 4000 priority [0]
int score; score 4018 4001
4002
The symbol table only contains the base address of an
array. Since all of the elements of the array are the
same data type, they will all use the same number of
bytes in memory. So, the computer calculates the
address of an element in an array using the formula:
102. memory address = base address + (index * size)
In this example, the base address for the array priority
is 4000. The size of each element is 4 bytes, since it is
an array of integers. So, the address of priority[2] is:
address of priority[2] = 4000 + 2 * 4
which equals 4008.
(Remember, addresses are base 16 – hexadecimal).
This scheme works because the index of the first
element in the array is 0, not 1. In fact, this is why
array index values start at 0.
Notice that the highest index is one less than the size of
the array, because the array index numbering starts at
zero. In this example priority has 6 elements,
priority[0] through priority[5].
4003
4004 priority [1]
105. One Dimensional Arrays in Java
A one-dimensional array in Java is a indexed fixed-length
homogeneous data structure. In other words,
it is a set of sequentially numbered data elements, in which all
of the data must be of the same data
type, and with a number of elements that cannot be changed. In
Java, an array is an object.
There are two parts to declaring an array in Java, unlike
primitive data types, which have a one-step
declaration. First, the array must be named; second, the size
must be declared.
step 1 – Declare a name for the array. There are two styles for
doing this, which both assign a name to
an array, but do not create the array in memory: (The first style
is preferred.)
int[] score; // declares score to be the name of an int array, it
106. has no elements
int score[]; // declares score to be the name of an int array, it
has no elements
step 2 – Declare the size of the array.
score = new int[10]; // declares the array score to have 10
integer elements
The number in brackets is the number of elements or size of the
array, also known as the array length.
The indexes in Java arrays must be non-negative and always
start at zero. The highest index will be one
less than the size of the array. If the array length is n, then the
highest index will be n-1.
The statement that declares the array length actually creates the
array.
The two statements naming an array and declaring an array must
both be used to create the array:
107. int[] score;
score = new int[10];
The name and size declarations for an array can be put together
in one Java statement, which is the
easiest and most common way to create an array in Java:
int[] score = new int[10]; // score is the name of an integer
array with 10 elements
The keyword new is necessary when declaring objects. An
array is an object in Java. This statement
declares an array named score and sets the size to 10 elements.
What is actually in an array in Java?
Each element in an array is an individual variable of the data
type declared for the array. For example, if
empName is declared as:
String[] empName = new String[10];
108. then each of the array elements, such as empName[3], is a
String variable.
If the data type of an array is a primitive data type, then each
element of the array contains a value of
that data type. If the data type of an array is a class of objects,
then each element in the array contains
a memory address referring to where an object of the correct
data type is stored in memory. A memory
address referring to where an object is stored is called a
reference to an object. Java Strings are objects,
so each element in a String array holds a reference to a String,
not the String itself.
Example 1 – an integer array
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 8
109. An array of integers contains the actual values of integers, since
int is a primitive data type.
int[] score = new int[5];
This statement creates an array of integers named score with 5
elements. The actual values of integers
would be stored in the each element in the array, such as:
memory
address
variable name for
this address
value stored
at this address
4000 score[0] 93
4004 score[1] 87
4008 score[2] 91
110. 400C score[3] 95
4010 score[4] 88
We can think of an array as a set of empty boxes. In the integer
array score, each box holds an integer:
Score[]
93 87 91 95 88
Example 2 – A String array
With any array of objects, including a String array, the elements
of the array actually contain references
to the objects, not the objects themselves. So, an array of
Strings would contain references to where
the Strings themselves are stored in memory, like this:
String[] empName = new String[5];
memory
111. address
variable name for
this address
value stored
at this address
4000 empName[0] ….4184
4004 empName[1] ….4210
4008 empName[2] ….4258
400C empName[3] ….510C
4010 empName[4] ….4412
This example assumes that each memory address is 32 bits (4
bytes)
long, but only the last 4 hexadecimal digits are shown.
The Strings are actually stored in the memory locations
referenced by the values in the array.
112. If we think of an array as a set of empty boxes, then each box in
the String array empName, holds a
reference to where a String value is actually stored in memory:
empName[]
….4184 ….4210 ….4258 ….510C ….4412
“Jones” “Goldschneider” “Brown” (and so on…)
Why does Java store arrays of objects this way? Remember, an
array is a fixed length data structure, but
Strings and many other objects are not fixed length, their sizes
can change. This method for storing
objects in memory allows variable length objects to be store in
fixed length arrays. It also has several
advantages that are beyond the scope of what we cover in this
chapter.
113. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 9
Even though the elements of a String array actually contain
references to Strings, if we use a variable
from the array in our Java code, we will get the String, not the
reference. For the example above:
System.out.println( empName[2] ); //prints the name Brown,
not the reference ….4258
Once we learn to work with objects, we will see that we can
have an array for any type of object, just as
with Strings, using references to the objects stored in memory,
such as an array of images:
Example 3 – an Array of Images
JPGimage[] orientation = new JPGimage[5];
orientation[]
114. 4100 6404 7820 880C B204
… and so on. Each element in the array contains a reference
to a stored image.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 10
Assigning Values to Array Elements
There are two ways to assign values to array elements:
1. using assignment statements
For example:
score[3] = 98; // an int value is assigned to the fourth
element in score
115. empName[0] = “Jones”; // a String value is assigned to
the first element in empName
a[4] = x; // a[4] is set to the value of x (data types
must match)
2. by listing values in an alternate array declaration
Arrays may be declared in a statement that lists their values:
int[] score = {93, 87, 91, 95, 88};
This method is sometimes called an explicit array declaration.
The values listed in braces,
separated by commas, are assigned in order to the array
elements. The length of the array is
determined by the number of values in the list. The keyword
new is not needed in an explicit
array declaration.
An explicit array declaration like the one just shown above
works well for small arrays, but can be
116. awkward for large arrays.
One common way to initialize the values in an array is with a
count controlled loop. Here are a few
examples:
Example 4 – Initializing all of the elements in an Array to Zero
The following code initializes the values of an array of data
type double all to the same value, zero:
double[] cost = new double[100]; // an array of 100 numbers
for(int i=0; i<100; i++)
cost[i] = 0.0;
Example 5 – Initializing an Array with User Input
The following code initializes the values of an array of data
type String with user input. Inside the array
117. the names are numbered starting with 0, but to the user they are
numbered starting with 1. This
assumes that the code is encapsulated, meaning that the user
does not see the code.
String[] student = new String[10]; // an array of 10 student
names
for( int i= 0; i < 10; i++)
{
// Ask the user for a student name, then get the name from the
keyboard
System.out.print("Please enter the name of student number"
+ (i+1) + “:” );
student[i] = x.nextLine();
} // end for
118. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 11
Example 6 – Initializing an Array with random numbers
The following code initializes the values of an int array with
random numbers between 1 and 100. An
array of random numbers is often used in game or simulation
programming, or to test other software.
int [] num = new int[100]; // an array of 100 integers
for( int i= 0; i < 100; i++)
num[i] = 1+(int)(Math.random()*100); // random, 1 <= num[i]
<= 100
Math.random() yields a value between 0 and 1; the arithmetic
converts it to a integer between 1 and 100.
The Array length Property; Iterating an Array
x.length, where x is the name of an array, is a method for
119. instances of array objects that returns the
length of the array as an integer. For example, if the array
score[] has 10 elements, then score.length
returns the value 10.
The length property can be used to iterate an array. To iterate an
array means to go through each of the
elements in the array on at a time. The three examples above
each iterate an array, and could be
written to use the length property. Here is the code from
example 4, above, re-written using the length
property for the cost array.
Example 7 – Initializing an Array using the length method
double[] cost = new double[100]; // an array of 100 numbers
for(int i = 0; i < cost.length; i++)
cost[i] = 0.0;
120. There are many different reasons to iterate an array – to
initialize the array as above, or to print the
elements of the array, for example.
Example 8 – Printing the Elements of an Array
// the following assumes student is a String array that has
been initialized
for( int i= 0; i < student.length; i++)
System.out.print("Student number " + ( i+1) + “ is ” +
student[i]);
Example 9 – Printing the Fibonacci numbers
The Fibonacci sequence is a sequence of numbers that starts
with 0 and 1, then each successive term in
the sequence determined by adding the previous two terms.
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
…
121. Such a pattern is very common in the natural world. The
following diagrams help us to understand why
that is so. On the left, we see a set of rectangles composed by
adding squares whose sides are
successively larger Fibonacci numbers. The next square to be
added will have a side of length 13, and
will be added above the existing rectangle. On the right we see
a spiral drawn by connecting the corners
of Fibonacci squares. The growth of branches on a tree, the
shape of a spiral sea shell, the pattern of
seeds on a sunflower, the growth of a population of rabbits, and
many other patterns in the real world
fit the Fibonacci sequence.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 12
122. In this example, we will store the first 10 Fibonacci numbers in
an array named fib[], then print the
array. We will declare the array using a set of values.
int[] fib = {0,1,1,2,3,5,8,13,21,34}; // an array initialized with
Fibonacci numbers
int i;// used as an array index
System.out.println(“The first ten Fibonacci numbers” );
// this loop prints the values in the array
for( i= 0; i < fib.length; i++)
System.out.print(fib[i] + “ “);
System.out.println(); // go to a newline after printing the array
values
The output looks like this:
123. The first ten Fibonacci numbers
0 1 1 2 3 4 5 8 13 21 34
The Enhanced for Statement
The for statement we have been using so far is the basic for
statement. Java also has a special version of
the for statement, called the enhanced for statement. The
enhanced for statement iterates an entire
array. It may only be used with an array or an object that can be
iterated like an array.
The enhanced for statement has a loop header with the keyword
for, followed by parentheses that
contain an integer declaration and the name of an array. The
statement or block of code following the
loop header will be executed once for each element in the array.
Within the statement or block of code, the integer declared in
the loop header refers to each element in
124. the array. The syntax within an enhanced for loop can be
tricky, so be careful. We do not use the name
of the array within the loop, only the integer variable declared
in the header. This variable refers to an
element of the array, sequentially incremented each time
through the loop. Here is the syntax of the
enhanced for loop:
for ( integer declaration : name of an array)
block of code
Here is the same code from above to print the array with the
first 10 Fibonacci numbers, using an
enhanced for loop instead of a basic for loop:
125. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 13
Example 10 – the enhanced for loop
int[] fib = {0,1,1,2,3,5,8,13,21,34} // an array initialized with
Fibonacci numbers
System.out.println(“The first ten Fibonacci numbers” );
// this loop prints the values in the array using the enhanced for
statement
for(int i : fib)
System.out.print(i + “ “); // i refers to fib[i] in this enhanced
for loop
System.out.println(); // go to a newline after printing the array
values
The output looks like this:
The first ten Fibonacci numbers
126. 0 1 1 2 3 4 5 8 13 21 34
Although it is convenient, the enhanced for loop has limited
applications. It can only be used to iterate
an entire array, not part of an array, and the declared integer
variable cannot be used as an integer
variable within the loop, only to refer to each element of the
array.
Copying an Array
An assignment statement such as second = first; will not copy
an array; it copies the reference to the
array, creating two variables referencing the same array. To
copy an array in Java, we must create
another array of the same data type and size, then copy each
value from the original array into the new
array. The actual copying can be done with a for loop or with
an enhanced for loop.
127. Example 11 – copying an array
// an array initialized with ten prime numbers
int[] first = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
// To copy an array, we need to create another array of the
same data type and size.
int[] second = new int[10];
// Then, we copy each element from the first array into the
second array.
for(int i : i < first.length; i++)
second[i] = first[i];
// This could also be done with an enhanced for loop
for(int i : first)
128. second[i] = first[i];
Arrays as Method Parameters in Java
An entire array can be passed as a method parameter, but
remember, the name of the array by itself is a
reference to the base address where the array is stored in
memory. It is this reference, and not the
values in the array, that is passed to another method when an
array is passed in Java. We end up with
two different reference variables pointing to the same array in
memory, not two different arrays, as
shown in example 12 on the next page.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 14
Example 12 – Passing an Array as a Parameter
129. In this example, an entire array is passed from the main method
to the method printJob(). However, the
array is not really passed; it is the value of the reference
variable that points to the array’s location in
memory that is really passed. Java always passes values. In this
case the value is the address of the array
in memory, so we end up with two different variables, priority –
the original name for the array – and
category – the copied name – both referring to the original
array.
variables symbol table memory map
priority = new int [6]; priority 4000 4000 priority [0]
int score; score 4018 4001
. . . 4002
130. int[] category; category 4000 4003
int i; i 4054 4004 priority [1]
int[] priority = new int[6];
. . .
// call method printJob()
printJob(priority);
. . .
public static void printJob(int[] category){
for( int i=0; i < category.length; i++) {
System.out.printl(“Job” + i + “is in category “ + category[i]);
. . .
}
The method header for the printJob() method establishes a
reference variable to
refer to an array, category, but category has no value until the
method is invoked
131. from another method.
When printJob() is invoked from the main method, the value of
the array reference
variable priority is passed to array reference variable category
in the formal
parameter list. Now both priority and category have the same
value, the address
of the same array. This means they refer to the same array –
priority and category
have become two names for the same array – whatever we do to
one we do to the
other. If we change the value of an element in category we also
change the value
of that element in priority. category[3], for example, is
priority[3].
Java always passes a value, not a reference to a value, but that
value may be an
address of an object, such as the address of the array passed in
this case.
4005
4006
134. 4020
The value of the actual
parameter priority is passed
to the formal parameter
category, but that value is a
reference to an array.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 15
Passing an Array Element as a Method Parameter
Each element in an array is an individual variable that is treated
like any other any variable with the
element’s data type. It may be used like any other variable of
135. that data type, including as an actual
parameter for a method.
Example 13 – passing an array element as a parameter
In this example, price[] is an array of double values. price[3] in
the main method is used as an actual
parameter. The value of the variable price[3] is passed to the
formal parameter cost when the
method is invoked.
double[] price = { 1.99, 3.87, 4.95, 2.99, 2.57};
. . . // all of the code is not shown
currentSale(price[3]);
. . . // all of the code is not shown
/****************************************************
******************/
136. public static void currentSale(double cost) {
System.out.printl(The cost of the item is: “ + cost);
. . . // all of the code is not shown
}
The value of price[3] is copied to cost in the method
currentSale(). Any change that is later made to
cost has no effect on the original value in price[3].
CheckPoint 6.2
1. A one-dimensional array in Java is defined as an indexed
fixed-length homogeneous data
structure. What does this mean?
2. What is actually in an array if the array’s data type is a
primitive data type and how does this
137. differ from what is in an array if the array’s data type is class of
objects?
3. What are the two ways that a value can be assigned to an
array element?
4. Create an example showing how the enhanced for statement
can be used to iterate an array.
5. How is an entire array passed as a method parameter and
what happens in the original array if a
value is changed in an array within a method that has received
the array as a parameter?
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 16
Operations on Numeric Arrays
Once we have a set of numbers stored in an array, we can
138. perform numerical analysis of the data.
Common operations on numerical arrays include finding the
sum, the average, the minimum and the
maximum of the values in an array.
The following examples show how to do each of these things for
a set of values in a double array.
Sum, Average, and Count of Values in an Array
To find the sum of a set numbers in an array we need a variable
to hold the sum. It should have the
same data type as the elements of the array, and it should be
initialized to zero. Then, we iterate the
loop, adding each value in the array to the sum, as in the
following code. After the loop to iterate the
array is finished, then the variable will hold the sum.
The average is simply the sum divided by the number of
elements in the array. The array length
139. property is the number of elements in the array.
Example 14 – finding the sum and average of values in an array
double[] cost = new double[100]; // an array of 100 numbers
double sum = 0;
// the statements that give values to the elements in the array are
not shown
for(int i= 0; i < cost.length ; i++)
sum = sum + cost[i];
System.out.println("the total cost is " + sum);
System.out.println( "the average cost is " + sum/cost.length );
In this example, the average is calculated as part of the print
statement. We could also have a variable
to hold the average if we need to use it later.
140. Counting Elements in an Array
Sometimes we wish to count all of the values in an array that
meet a certain condition. To do so, we
simply initialize a counter to zero, then increment the counter
for each element that meets the
condition.
Example 15 – counting the elements in an array
In this we will again use the first ten Fibonacci numbers.
Instead of printing each of the numbers, we
will only print the even Fibonacci numbers and we will count
them as well.
The variable countEven is first initialized to zero, then, as we
iterate the array, we will increment the
count for each even Fibonacci number. To test for even
numbers, we will use the Java’s remaindering
141. operation (%), which returns the remainder of an integer
division operation. If the remainder is zero
when we divide by two, then the number is an even number.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 17
int[] fib = {0,1,1,2,3,5,8,13,21,34}; // an array initialized with
Fibonacci numbers
int i;// used as an array index
int countEven = 0;// used to count how many of the first 10
Fibonacci numbers are even
System.out.println(“Even Fibonacci numbers” );
// this loop prints the values in the array
142. for( i= 0; i < fib.length ; i++)
if (fib[i] % 2 == 0) {
countEven++;
System.out.println( fib[i] + “ is even”);
}
System.out.println ( countEven + “ of the first 10 Fibonacci
numbers are even”);
The output looks like this:
Even Fibonacci numbers
0 is even
2 is even
8 is even
34 is even
143. 4 of the first 10 Fibonacci numbers are even.
The Minimum and Maximum Values in an Array
To find the minimum value in an array, we start with a variable
to hold the minimum. We initialize the
minimum to the first value in the array, then go through the rest
of the values in the array, testing each
to see if it is less than the minimum. If a value is less than the
minimum, it becomes the new minimum.
After going through the entire array, the variable will hold the
minimum value from the array.
The maximum is calculated in almost the same way, setting the
first value to be the maximum, except
we then check to see if each value is greater than the maximum.
Example 16 – finding the minimum value in an array
double[] cost = new double[100]; // an array of 100 numbers
144. int i;
double minimum;
// the statements that give values to the elements in the array are
not shown
minimum = a[i];
for( i= 1; i < cost.length ; i++) // iterate starting at the second
element
if ( cost[i] > minimum )
minimum = cost[i];
System.out.println("the minimum cost is " + minimum);
Example 17 – finding the maximum value in an array
double[] cost = new double[100]; // an array of 100 numbers
int i;
145. double maximum;
// the statements that give values to the elements in the array are
not shown
maximum = a[i];
for( i= 1; i < cost.length ; i++) // iterate starting at the second
element
if ( cost[i] < maximum)
maximum = cost[i];
System.out.println("the maximum cost is " + maximum);
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 18
Searching and Sorting Arrays
Comparing Strings
146. In order to search or sort an array of Strings we need to be able
to compare String values. This is easy for
integers and floating point data, but when it comes to Strings,
there is a complication.
The Boolean condition (a == b) will work if a and b are Strings,
but it doesn’t work the way most people
think it does. Strings are objects, and a comparison of two
objects using the == operators compares the
reference values stored in the two variables, not the values of
the objects themselves. In other words,
(a==b) will be true only if a and b refer to the same object, not
equal objects. We have a similar
problem with the < and > operators.
Java has a number of different ways to compare objects in
general and Strings in particular. Here we
will look at two different methods from the String class that can
147. be used to compare Strings:
1. the a.matches(b) method. The String matches() method
returns a true value if the String
variable a is equal to the String expression b, otherwise, it
returns a false value. The String
expression may be a variable, a String literal, or anything that
evaluates to or returns a String.
2. the a.compareTo(b) method. The String compareTo() method
compares two Strings
lexicographically. A lexicographic comparison compares two
text items character-by-character
using a predefined collating sequence. In the case of Java
Strings, the collating sequence is the
UTF-16 version of Unicode. This is similar to the way a person
might compare two names to see
which one comes first alphabetically. The method returns an
integer value,
148. a. If the two Strings are the same, then the compareTo() method
returns the integer 0.
b. If a is less than b, then the method returns an integer less
than 0 (a negative integer).
c. If a is greater than b then the method returns an integer
greater than 0 (a positive
integer).
The String matches() method is an easy way to see if two
Strings are the same. The String compareTo()
method is useful for when we are trying to see which String
comes before the other, such as when we
are sorting a list of String values.
String handling is covered more in detail later in this course,
and in subsequent courses. The matches()
and compareTo() methods are used in the rest of this section.
149. Linear Search of an Array
Sometimes we wish to search an array to see if it contains a
certain value. We can do this many
different ways, but the simplest and most straightforward is a
linear search. In a linear search of an
array, we look at each value in the array one at a time to see if
the value we are seeking is in the array.
If we find the value, then we are done. If we get to the end of
the array without finding the value, then
the value is not in the array.
There are several different ways to implement a linear search.
We will use a loop with a compound
condition and a Boolean variable to keep track of whether or not
the value we are seeking is in the
array. In the following example, we first look at the
pseudocode for the array then see the final program
150. built from that pseudocode.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 19
Example 18 – linear search of an array
In this example, an array contains a list of cities that have
professional football teams. The user enters
the name of a city to see if it is in the list. The program will
perform a linear search of the array. First, a
boolean variable named found is set to false. The continuation
condition in the for loop to iterate the
array will contain a compound condition, continuing while
found is false and while the end of the array
has not been reached. If the city is found, a message is printed
and a boolean variable is set to true to
terminate the loop. If the found variable is still false after the
151. loop, a not found message is printed.
Using the found variable in the compound condition provides an
advantage by making the search more
efficient. With it, the loop will stop as soon as the value is
found. Without it, the loop always goes
through the entire array. Consider, for example what happens
if the value being sought is in the first
element in an array of 100 elements. With the compound
condition, the loop stops after looking at the
first element. Without the compound condition the loop iterates
all 100 times.
The efficiency of algorithms is important, especially as data
sets grow larger. Algorithmic efficiency is
studied in detail CSCI 112 and 211.
Pseudocode for a linear search of a String array
/* in the search, n is the loop counter -- the continuation
152. condition is:
( n less than NFLcities.length )and (target city not found)
*/
String[] NFLcities; // an array holding the names of cities
with NFL teams
n int; // loop counter
boolean found = false; // will be set to true if the city is found
in the list
print intro message
get the target name of the city from the user
for ( i=0; not (found) AND n < NFLcities.length ; n++)
if ( target matches NFLcities[n] ) // if the name entered
matches this entry in the list.
print NFLcity[n] has an NFL team
set found to true
153. after the loop – if not(found) print “ [target] is not in the list of
cities with an NFL team.”
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 20
/* CSCI 111 - Fall 2013
* NFL City Search Program
* This program performs a linear search of a String array with
* the names of cities that have NFL teams
* last editied Sept. 28, 2013 by C. Herbert
*/
package nflcities;
import java.util.Scanner;
154. public class NFLcities {
public static void main(String[] args) {
// an array holding the names of cities with NFL teams.
String[] NFLcities = {"Buffalo", "Miami", "Boston", "New
York", "Baltimore",
"Cincinnati", "Cleveland", "Pittsburgh", "Houston",
"Indianapolis",
"Jacksonville", "Tennessee", "Denver", "Kansas City",
"Oakland",
"San Diego", "Dallas", "New York", "Philadelphia",
"Washington", "Chicago",
"Detroit", "Green Bay", "Minnesota", "Atlanta", "Charlotte",
"New Orleans",
"Tampa", "Arizona", "St. Louis", "San Francisco",
"Seattle"};
155. String target; // the city for which we are searching
int n; // loop counter
boolean found = false; // true if the target city is found in the
array
// set up input stream from the keyboard
Scanner keyboard = new Scanner(System.in);
// print intro message
System.out.print("This program will tell you if a city has an
NFL team.nn");
// get the target name of the city from the user
System.out.print("Please enter the name of a city: " );
156. target = keyboard.nextLine();
// search array of NFL cities for target city
// the loop coninues to the end of the array if the city is not
found
for (n=0 ; (!found) && (n < NFLcities.length) ; n++)
{
if (NFLcities[n].matches(target) ) // uses the String class
matches() method
{
//print found message and set found to true
System.out.println(target + " has an NFL team.n");
found = true;
} // end if
157. } // for loop
// after the loop – if not(found) print not found message
if (!found)
System.out.println(target + " is not in the list of cities with an
NFL team.n");
} // end main()
} // end class
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 21
Sorting an Array
It is useful to be able to sort an array. There are many different
158. ways to do so, which are studied in
detail in CSCI 112 and CSCI 211. We will look at a simple
sorting method called a bubble sort.
In a bubble sort, we go through an array of data comparing each
data item to the next item. If they are
out of order, then we swap them; if they are in the correct order,
then we leave them alone. We
compare each item to the next item until we reach the end of the
array. Each time we go through the
entire array is called a pass through the array. We continue to
make passes until we can make one pass
all the way through the array without swapping anything. The
bubble sort is based on the transitive
property of equality and inequality (if A≤B and B≤C, then A≤B)
If we can make a pass without swapping
anything, then we know the array is in the correct order and
we’re done – the array is sorted.
159. We can use a boolean variable named swapped to keep track of
whether or not we needed to swap
anything in each pass through the array. Before we go through
the array, we set swapped to false. If we
swap anything, we also set swapped to true. When we finish a
pass, if swapped is true, then something
was swapped, and another pass is needed. If swapped is still
false after making a pass through the array,
then nothing needed to be swapped in that pass, and the array is
in the correct order; the sort is done.
Here is pseudocode for a bubble sort of an array. Notice that
each pass through the array only goes to
the second-to-last element in the array, since we are comparing
each element to the one that follows it.
The last comparison will then be between the second-to-last
element in the array and the last element.