The document discusses different types of methods in Java. It defines a method as a block of code that performs a specific task. It then explains how to declare a method using access specifiers, return types, and parameters. It also provides guidelines for naming methods and describes different types of methods including predefined, user defined, static, instance, abstract, and factory methods. Key details about each type of method are given such as how they are invoked and implemented.
The Java Learning Kit Chapter 5 – Methods and Modular.docxarnoldmeredith47041
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 .....................................................................
This document discusses method overloading in Java. It defines a method as a collection of statements that perform an operation. A method has a header specifying its modifiers, return type, name, and parameters. The body contains the statements. Method overloading allows multiple methods with the same name but different signatures. Signatures can vary by parameter types, numbers, or orders. Overloaded methods use static binding at compile time. The example shows two Addition methods differentiated by an extra parameter, with the correct one called based on arguments.
Concurrency Programming in Java - 02 - Essentials of Java Part 1Sachintha Gunasena
This session discusses about the basic building blocks of java as an approach to concurrent programming in Java and include:
java, setting up the environment, common issues, building applications, application structure and elements, fields and methods, constructors, building applets, class, extending a class, building a user interface, java swing, writing servlets.
CIS 1403 lab 3 functions and methods in JavaHamad Odhabi
This lab discusses and provides examples of both built-in and user-defined functions. In Java function are referred to as methods. Therefore, in the rest of this lab, the term methods will be used to refer to functions. The lab will cover the type of methods, naming of functions, the scope of variables and recursion.
The document provides an overview of advanced class features in Java, including method overloading, overriding, and constructors. It discusses the differences between overloaded and overridden methods, and how to call parent class methods using super. It also covers enumerations, wrapper classes, autoboxing/unboxing, annotations, and inner classes.
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.
1. The document discusses the anatomy of methods and classes in Java. It explains that a Java application consists of more than one class, with the starting class containing the main method. Other classes are used to encapsulate data and functionality.
2. It describes what a method declaration is and how method control flow works. When a method is invoked, the flow jumps to the method code and returns after completion. Methods can return values.
3. The document also covers instantiating classes to create objects. Instance methods require object creation using the new operator before being called. Instance variables store data in objects and are available throughout the class.
This document discusses object-oriented programming concepts like classes, objects, methods, encapsulation, and visibility modifiers. It explains that a class defines the blueprint for an object, with data representing its state and methods representing its behavior. Methods can access instance data and parameters, while encapsulation involves hiding implementation details and controlling access via public, private, and other visibility modifiers. Getter and setter methods are used to access or modify private data.
METHODS OR FUNCTIONS IN C for dotnet.pptxArjunKhanal8
Methods in C# are blocks of code that perform specific tasks. They can take parameters and may or may not return values. The syntax for defining a method includes access modifiers, return types, names, and parameter lists. Methods are invoked by calling the method name from another method. Parameters pass data into methods while arguments are the actual values passed during a method call. Methods make programs more reusable, readable, and optimized.
The document discusses various topics related to object-oriented programming and .NET Framework development. It introduces goals of the .NET Framework like support of industry standards, extensibility, unified programming models, and improved memory and security models. It also covers topics like assemblies, namespaces, inheritance, polymorphism, exceptions, collections, and data access using ADO.NET. The document discusses Windows Presentation Foundation (WPF) and web application development concepts like controls, data binding, templates, page and control events, and data-bound web controls.
The document discusses Java methods, explaining that a method is a block of code that performs a specific task and that complex problems can be divided into smaller reusable methods. It describes two types of methods - predefined methods that are defined in Java class libraries and can be directly called, and user-defined methods that are written by programmers to meet specific needs. Examples are provided of how to declare, define, and call both predefined and user-defined methods in Java programs.
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
If you are preparing to appear for Oracle Certified Professional Java SE 8 Programmer (OCPJP 8) certification exam, this a reference card (sort of long cheat sheet) meant to help you. You may want to print this reference card for your easy and quick reference when you prepare for your exam.
Method overloading in Java allows methods within a class to have the same name but different parameters. It increases readability and allows methods to perform similar tasks with different input parameters. Method overloading is determined by Java by first matching the method name and then the number and type of parameters. It can be done based on the number of parameters, data type of parameters, or sequence of data types in parameters. The main advantage is that it performs tasks efficiently with variations in argument types or numbers under the same method name. A disadvantage is that it can be difficult for beginners and requires more design effort in the parameter architecture.
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.
An applet is a Java program that runs within a web browser. It is embedded in an HTML page using tags and runs on the client-side. Applets allow websites to be more dynamic and interactive. All applets extend the Applet class and run within a browser or applet viewer rather than as standalone programs. The code is downloaded from a web server when the page loads and output is handled using AWT methods rather than System.out. For security, applets have restricted access to client files and networks.
This document discusses new operators, methods, and classes in Java. It explains that the new operator dynamically allocates memory for a new object and returns a reference. Methods are functions defined within classes that perform specific tasks related to that class. The document provides examples of declaring classes with methods and using the dot operator to call methods on objects.
This document discusses design patterns and principles. It begins by defining design patterns as repeatable solutions to common design problems. It then covers several design patterns including Singleton, Strategy, Adapter, Template, Factory, Abstract Factory, and Observer patterns. It also discusses low-level principles like Tell Don't Ask and high-level principles like the Single Responsibility Principle. Finally, it provides examples of how to implement some of the patterns and principles in code.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
Class is a blueprint for creating object instances that share common attributes and behaviors. It defines the variables and methods that are common to all objects of that class. When an object is created from a class, it is said to be an instance of that class. Objects contain state in the form of attributes and behavior in the form of methods. Classes in Java can define access levels for variables and methods as public, private, protected, or without a specified level (default).
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.
This document discusses Java classes, objects, and constructors. It explains that a class contains instance variables and methods, and defines common behaviors for objects. An object is instantiated from a class using the new reserved word and can then access the class's instance variables and methods. The document provides an example of creating a Java class with an instance variable and method to demonstrate how objects are made from classes and can then access class members.
IT help desk outsourcing Services can assist with that by offering availability for customers and address their IT issue promptly without breaking the bank.
Technology Trends in 2025: AI and Big Data AnalyticsInData Labs
At InData Labs, we have been keeping an ear to the ground, looking out for AI-enabled digital transformation trends coming our way in 2025. Our report will provide a look into the technology landscape of the future, including:
-Artificial Intelligence Market Overview
-Strategies for AI Adoption in 2025
-Anticipated drivers of AI adoption and transformative technologies
-Benefits of AI and Big data for your business
-Tips on how to prepare your business for innovation
-AI and data privacy: Strategies for securing data privacy in AI models, etc.
Download your free copy nowand implement the key findings to improve your business.
Ad
More Related Content
Similar to Week 7 Java Programming Methods For I.T students.pdf (20)
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.
1. The document discusses the anatomy of methods and classes in Java. It explains that a Java application consists of more than one class, with the starting class containing the main method. Other classes are used to encapsulate data and functionality.
2. It describes what a method declaration is and how method control flow works. When a method is invoked, the flow jumps to the method code and returns after completion. Methods can return values.
3. The document also covers instantiating classes to create objects. Instance methods require object creation using the new operator before being called. Instance variables store data in objects and are available throughout the class.
This document discusses object-oriented programming concepts like classes, objects, methods, encapsulation, and visibility modifiers. It explains that a class defines the blueprint for an object, with data representing its state and methods representing its behavior. Methods can access instance data and parameters, while encapsulation involves hiding implementation details and controlling access via public, private, and other visibility modifiers. Getter and setter methods are used to access or modify private data.
METHODS OR FUNCTIONS IN C for dotnet.pptxArjunKhanal8
Methods in C# are blocks of code that perform specific tasks. They can take parameters and may or may not return values. The syntax for defining a method includes access modifiers, return types, names, and parameter lists. Methods are invoked by calling the method name from another method. Parameters pass data into methods while arguments are the actual values passed during a method call. Methods make programs more reusable, readable, and optimized.
The document discusses various topics related to object-oriented programming and .NET Framework development. It introduces goals of the .NET Framework like support of industry standards, extensibility, unified programming models, and improved memory and security models. It also covers topics like assemblies, namespaces, inheritance, polymorphism, exceptions, collections, and data access using ADO.NET. The document discusses Windows Presentation Foundation (WPF) and web application development concepts like controls, data binding, templates, page and control events, and data-bound web controls.
The document discusses Java methods, explaining that a method is a block of code that performs a specific task and that complex problems can be divided into smaller reusable methods. It describes two types of methods - predefined methods that are defined in Java class libraries and can be directly called, and user-defined methods that are written by programmers to meet specific needs. Examples are provided of how to declare, define, and call both predefined and user-defined methods in Java programs.
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
If you are preparing to appear for Oracle Certified Professional Java SE 8 Programmer (OCPJP 8) certification exam, this a reference card (sort of long cheat sheet) meant to help you. You may want to print this reference card for your easy and quick reference when you prepare for your exam.
Method overloading in Java allows methods within a class to have the same name but different parameters. It increases readability and allows methods to perform similar tasks with different input parameters. Method overloading is determined by Java by first matching the method name and then the number and type of parameters. It can be done based on the number of parameters, data type of parameters, or sequence of data types in parameters. The main advantage is that it performs tasks efficiently with variations in argument types or numbers under the same method name. A disadvantage is that it can be difficult for beginners and requires more design effort in the parameter architecture.
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.
An applet is a Java program that runs within a web browser. It is embedded in an HTML page using tags and runs on the client-side. Applets allow websites to be more dynamic and interactive. All applets extend the Applet class and run within a browser or applet viewer rather than as standalone programs. The code is downloaded from a web server when the page loads and output is handled using AWT methods rather than System.out. For security, applets have restricted access to client files and networks.
This document discusses new operators, methods, and classes in Java. It explains that the new operator dynamically allocates memory for a new object and returns a reference. Methods are functions defined within classes that perform specific tasks related to that class. The document provides examples of declaring classes with methods and using the dot operator to call methods on objects.
This document discusses design patterns and principles. It begins by defining design patterns as repeatable solutions to common design problems. It then covers several design patterns including Singleton, Strategy, Adapter, Template, Factory, Abstract Factory, and Observer patterns. It also discusses low-level principles like Tell Don't Ask and high-level principles like the Single Responsibility Principle. Finally, it provides examples of how to implement some of the patterns and principles in code.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
Class is a blueprint for creating object instances that share common attributes and behaviors. It defines the variables and methods that are common to all objects of that class. When an object is created from a class, it is said to be an instance of that class. Objects contain state in the form of attributes and behavior in the form of methods. Classes in Java can define access levels for variables and methods as public, private, protected, or without a specified level (default).
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.
This document discusses Java classes, objects, and constructors. It explains that a class contains instance variables and methods, and defines common behaviors for objects. An object is instantiated from a class using the new reserved word and can then access the class's instance variables and methods. The document provides an example of creating a Java class with an instance variable and method to demonstrate how objects are made from classes and can then access class members.
IT help desk outsourcing Services can assist with that by offering availability for customers and address their IT issue promptly without breaking the bank.
Technology Trends in 2025: AI and Big Data AnalyticsInData Labs
At InData Labs, we have been keeping an ear to the ground, looking out for AI-enabled digital transformation trends coming our way in 2025. Our report will provide a look into the technology landscape of the future, including:
-Artificial Intelligence Market Overview
-Strategies for AI Adoption in 2025
-Anticipated drivers of AI adoption and transformative technologies
-Benefits of AI and Big data for your business
-Tips on how to prepare your business for innovation
-AI and data privacy: Strategies for securing data privacy in AI models, etc.
Download your free copy nowand implement the key findings to improve your business.
Artificial Intelligence is providing benefits in many areas of work within the heritage sector, from image analysis, to ideas generation, and new research tools. However, it is more critical than ever for people, with analogue intelligence, to ensure the integrity and ethical use of AI. Including real people can improve the use of AI by identifying potential biases, cross-checking results, refining workflows, and providing contextual relevance to AI-driven results.
News about the impact of AI often paints a rosy picture. In practice, there are many potential pitfalls. This presentation discusses these issues and looks at the role of analogue intelligence and analogue interfaces in providing the best results to our audiences. How do we deal with factually incorrect results? How do we get content generated that better reflects the diversity of our communities? What roles are there for physical, in-person experiences in the digital world?
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Aqusag Technologies
In late April 2025, a significant portion of Europe, particularly Spain, Portugal, and parts of southern France, experienced widespread, rolling power outages that continue to affect millions of residents, businesses, and infrastructure systems.
HCL Nomad Web – Best Practices and Managing Multiuser Environmentspanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-nomad-web-best-practices-and-managing-multiuser-environments/
HCL Nomad Web is heralded as the next generation of the HCL Notes client, offering numerous advantages such as eliminating the need for packaging, distribution, and installation. Nomad Web client upgrades will be installed “automatically” in the background. This significantly reduces the administrative footprint compared to traditional HCL Notes clients. However, troubleshooting issues in Nomad Web present unique challenges compared to the Notes client.
Join Christoph and Marc as they demonstrate how to simplify the troubleshooting process in HCL Nomad Web, ensuring a smoother and more efficient user experience.
In this webinar, we will explore effective strategies for diagnosing and resolving common problems in HCL Nomad Web, including
- Accessing the console
- Locating and interpreting log files
- Accessing the data folder within the browser’s cache (using OPFS)
- Understand the difference between single- and multi-user scenarios
- Utilizing Client Clocking
Spark is a powerhouse for large datasets, but when it comes to smaller data workloads, its overhead can sometimes slow things down. What if you could achieve high performance and efficiency without the need for Spark?
At S&P Global Commodity Insights, having a complete view of global energy and commodities markets enables customers to make data-driven decisions with confidence and create long-term, sustainable value. 🌍
Explore delta-rs + CDC and how these open-source innovations power lightweight, high-performance data applications beyond Spark! 🚀
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul
Artificial intelligence is changing how businesses operate. Companies are using AI agents to automate tasks, reduce time spent on repetitive work, and focus more on high-value activities. Noah Loul, an AI strategist and entrepreneur, has helped dozens of companies streamline their operations using smart automation. He believes AI agents aren't just tools—they're workers that take on repeatable tasks so your human team can focus on what matters. If you want to reduce time waste and increase output, AI agents are the next move.
Procurement Insights Cost To Value Guide.pptxJon Hansen
Procurement Insights integrated Historic Procurement Industry Archives, serves as a powerful complement — not a competitor — to other procurement industry firms. It fills critical gaps in depth, agility, and contextual insight that most traditional analyst and association models overlook.
Learn more about this value- driven proprietary service offering here.
Train Smarter, Not Harder – Let 3D Animation Lead the Way!
Discover how 3D animation makes inductions more engaging, effective, and cost-efficient.
Check out the slides to see how you can transform your safety training process!
Slide 1: Why 3D animation changes the game
Slide 2: Site-specific induction isn’t optional—it’s essential
Slide 3: Visitors are most at risk. Keep them safe
Slide 4: Videos beat text—especially when safety is on the line
Slide 5: TechEHS makes safety engaging and consistent
Slide 6: Better retention, lower costs, safer sites
Slide 7: Ready to elevate your induction process?
Can an animated video make a difference to your site's safety? Let's talk.
Mastering Advance Window Functions in SQL.pdfSpiral Mantra
How well do you really know SQL?📊
.
.
If PARTITION BY and ROW_NUMBER() sound familiar but still confuse you, it’s time to upgrade your knowledge
And you can schedule a 1:1 call with our industry experts: https://spiralmantra.com/contact-us/ or drop us a mail at [email protected]
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...Alan Dix
Talk at the final event of Data Fusion Dynamics: A Collaborative UK-Saudi Initiative in Cybersecurity and Artificial Intelligence funded by the British Council UK-Saudi Challenge Fund 2024, Cardiff Metropolitan University, 29th April 2025
https://alandix.com/academic/talks/CMet2025-AI-Changes-Everything/
Is AI just another technology, or does it fundamentally change the way we live and think?
Every technology has a direct impact with micro-ethical consequences, some good, some bad. However more profound are the ways in which some technologies reshape the very fabric of society with macro-ethical impacts. The invention of the stirrup revolutionised mounted combat, but as a side effect gave rise to the feudal system, which still shapes politics today. The internal combustion engine offers personal freedom and creates pollution, but has also transformed the nature of urban planning and international trade. When we look at AI the micro-ethical issues, such as bias, are most obvious, but the macro-ethical challenges may be greater.
At a micro-ethical level AI has the potential to deepen social, ethnic and gender bias, issues I have warned about since the early 1990s! It is also being used increasingly on the battlefield. However, it also offers amazing opportunities in health and educations, as the recent Nobel prizes for the developers of AlphaFold illustrate. More radically, the need to encode ethics acts as a mirror to surface essential ethical problems and conflicts.
At the macro-ethical level, by the early 2000s digital technology had already begun to undermine sovereignty (e.g. gambling), market economics (through network effects and emergent monopolies), and the very meaning of money. Modern AI is the child of big data, big computation and ultimately big business, intensifying the inherent tendency of digital technology to concentrate power. AI is already unravelling the fundamentals of the social, political and economic world around us, but this is a world that needs radical reimagining to overcome the global environmental and human challenges that confront us. Our challenge is whether to let the threads fall as they may, or to use them to weave a better future.
TrsLabs - Fintech Product & Business ConsultingTrs Labs
Hybrid Growth Mandate Model with TrsLabs
Strategic Investments, Inorganic Growth, Business Model Pivoting are critical activities that business don't do/change everyday. In cases like this, it may benefit your business to choose a temporary external consultant.
An unbiased plan driven by clearcut deliverables, market dynamics and without the influence of your internal office equations empower business leaders to make right choices.
Getting things done within a budget within a timeframe is key to Growing Business - No matter whether you are a start-up or a big company
Talk to us & Unlock the competitive advantage
Quantum Computing Quick Research Guide by Arthur MorganArthur Morgan
This is a Quick Research Guide (QRG).
QRGs include the following:
- A brief, high-level overview of the QRG topic.
- A milestone timeline for the QRG topic.
- Links to various free online resource materials to provide a deeper dive into the QRG topic.
- Conclusion and a recommendation for at least two books available in the SJPL system on the QRG topic.
QRGs planned for the series:
- Artificial Intelligence QRG
- Quantum Computing QRG
- Big Data Analytics QRG
- Spacecraft Guidance, Navigation & Control QRG (coming 2026)
- UK Home Computing & The Birth of ARM QRG (coming 2027)
Any questions or comments?
- Please contact Arthur Morgan at [email protected].
100% human made.
2. What is a Method in Java?
• Is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation.
• Used to achieve a reusability of code. This means that a
method can written once and use it many times.
3. What is a Method in Java?
• Provides easy modification and readability of code by adding
or removing a chunk of code.
• It is executed only when we call or invoke it.
• The most important method in java is the main() method.
6. What is a Method in Java?
Predefined Method
Methods already written
and provided by Java
Organized as a collection
of classes (class libraries)
To use: it needs an
import package
Method Type: data type
of value returned by
method
7. Predefined Method
Are the method
that is already
defined in Java
class libraries.
Also known as
standard library
method or built-in
method.
11. Types of User-Defined Method
Ø Non – value returning method
Ø Value returning method
Ø Methods Overloading
12. • When the method returns nothing, the return
keyword at the end of the method is optional.
• It uses void keyword.
• Similar in structure to value-returning methods
Non - Value Returning Method
13. • Similar in structure to value-returning methods
• Call to method is always stand-alone statement
• Can use return statement to exit method early
Void Method
14. Syntax of Creating a method
without a return value
public static type name()
{
// method boy or method signature
}
Access Specifier
Return
Type
Method
Name
Method Header
15. Example of a
User-Defined
Method
public class Method {
public static void display()
{
System.out.println("Hi Java");
}
public static void main(String[] args) {
// call or invoke the Method
display();
} // end of main
}//end of class
16. public class Method {
public static void display()
{
System.out.println("Hi Java");
}
public static void main(String[] args) {
// call or invoke the Method
display();
} // end of main
}//end of class
18. • Calculate and return a value
• Used to save value for later calculation or print value
• Uses a return keyword.
Value Returning Method
20. public class Method {
public static int sum(int x, int y)
{
int sum = x + y;
System.out.println("Sum = "+sum);
return sum;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a, b;
System.out.print("Enter value for a:");
a = input.nextInt();
System.out.print("Enter value for b:");
b = input.nextInt();
sum(a,b);
}
}
21. Variable x, y are arguments or known as the
actual parameters;
Variable a ,b are known as format parameters;
22. Naming a Method
• remember that the method name must be a verb and start
with a lowercase letter.
• If the method name has more than two words, the first
name must be a verb followed by adjective or noun.
• In the multi-word method name, the first letter of each
word must be in uppercase except the first word.
Example:
• Single-word method name: sum(), area()
• Multi-word method name: computeCircle(),
calculateArea()
23. Naming a Method
• It is also possible that a method has the same
name as another method name in the same
class, it is known as method overloading
24. Primitive Type Wrapper Classes as
Parameters
• If a formal parameter is of the primitive data type and the corresponding actual
parameter is a variable, then the formal parameter cannot change the value of the
actual parameter
• Only reference variables can pass values outside the method (except, of course, for
the return value)
• Corresponding to each primitive data type, Java provides a class so that the values of
primitive data types can be wrapped in objects
• The class Integer does not provide a method to change the value of an existing
Integer object
• The same is true of other wrapper classes
25. Reference Variables as Parameters
• If a formal parameter is a reference variable:
• Copies value of corresponding actual parameter
• Value of actual parameter is address of the object where
actual data is stored
• Both formal and actual parameter refer to same object
26. Use Reference Variables as Parameters
• Can return more than one value from a method
• Can change the value of the actual object
• When passing address, would save memory space and time,
relative to copying large amount of data
27. Method Overloading
• Method Overloading: is creating several methods within a class,
with the same name.
• The signature of the method consists of the method name and its
formal parameter list
• Two methods have different signatures if they have either different
names or different format parameter lists
• Note that the signature of a method does not include the return type of
the method
30. Debugging: Using Drivers and Stubs
• A program may contain a number of methods. In a complex program,
usually, when a method is written, it is tested and debugged alone.
• You can write a separate program to test the method. The program that
tests a method is called a driver program.
• Before writing the complete program, you could write separate driver
programs to make sure that each method is working properly.
31. Summary
• Sometimes the results calculated by one method are needed in another
method.
• In that case, the method that depends on another method cannot be tested
alone.
• A method stub is a method that is not fully coded.
• For a void method, a method stub might consist of only a method header
and a set of empty braces, {}.
• For a value-returning method it might contain only a return statement with
a plausible return value.
32. • If the problem is large and complex, it must be broken into subproblems, and if a
subproblem is still complex, it must further be divided into subproblems.
• The subdivision of a problem should continue to the point where the solution is clear and
obvious.
• Once a subproblem is solved, we can continue with the solution of another subproblem
and if all the subproblems of a problem are solved, we can continue with the next level.
• Eventually, the overall solution of the problem must be assembled and tested to ensure that
the programming code accomplishes the required task.
33. • A Java program is a collection of classes, and a class is a collection of data members
and methods.
• Each class and each method must work properly.
• To accomplish this, as explained in the previous section, once a method is written, it
can be tested using stubs and drivers.
• Since a method can be tested in isolation, it is not necessary to code all the methods in
order.
• Once all the methods are written, the overall program must be tested.
34. • The technique to solve a problem by subdividing into smaller problems is known as divide
and conquer and top-down design approach.
• These techniques are suitable and work for many kinds of problems, including most of the
problems given in this book and the problems you will encounter as a beginning
programmer.
• To simplify the overall solution of a problem that consists of many subproblems, we write
and test the code one piece at a time.
• Typically, once a subproblem is solved and the code is tested, it is saved as the first
version or a version of the program.
• We continue to add and save the program one piece at a time. Keep in mind that a working
program with fewer features is better than a nonworking one with many features.