- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java Method
As already discussed, classes usually consist of the two things i.e., instance variables and methods.
In Java, a method is a collection of statements which are grouped together to perform an operation. Java gives methods, so much power and flexibility.
Create Method in Java
Following is the general form to create a method:
type name(parameter-list) { // body of the method }
Here, type specifies any valid data type (including class types that you create) returned by the method.
If the method does not return a value, its return type must be void.
The name of the method is determined by name. This can be any legal identifier other than those already used by the other items within the current scope.
The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially the variables that receive the value of the arguments passed to the method when it is called. The parameter list will be empty if the method has no parameter.
Methods that have a return type other than void will return a value to the calling routine using the following form of the return statement :
return value;
Here, value is the value returned.
Add Method to Class
Even though it is perfectly fine to create a class that contains only data, it rarely happens. Most of time, you will use methods to access the instance variables which are defined by the class. In fact, methods define the interface of most classes. This provides the class implementor to hide the specific layout of the internal data structures behind clearer method abstractions. In addition to defining the methods which provides access to the data, you can also define methods which are used internally by the class itself.
Java Method Example
Now let's begin by adding a method to Box class as already discussed. It may have occurred to you while looking at the previous example programs that the computation of the volume of a box was something that was best handled by the Box class instead than the BoxDemo class. After all, since the volume of the box is dependent upon the size of the box, it makes signified to have the Box class compute it. To do this, you must add a method to the Box, as shown below :
/* Java Program Example - Java Methods * This program includes a method inside the Box class */ class Box { double width; double height; double depth; /* display the box's volume */ void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); /* assign the values to the mybox1's instance variables */ mybox1.width = 100; mybox1.height = 200; mybox1.depth = 150; /* assign different values to the mybox2's instance variables */ mybox2.width = 30; mybox2.height = 60; mybox2.depth = 90; /* display the volume of the first box */ mybox1.volume(); /* display the volume of the second box */ mybox2.volume(); } }
When the above program is compile and executed, it will produce the following output:
Now, look closely at the following two lines of code :
mybox1.volume(); mybox2.volume();
The first line invokes the volume() method on mybox1 i.e., it calls the method volume() relative to the mybox1 object, using the object's name followed by the dot (.) operator. Thus, the call to mybox1.volume() will show the volume of the box defined by mybox1, and the call to mybox2.volume() will display the volume of the box defined by mybox2. Each time the volume() is invoked, it displays the volume for the specified box.
If you are unknown with the concept of calling a method, the following discussion will help clear things up:
When mybox1.volume() is executed, then the Java run-time system transfers the control to the code defined inside the method volume(). After
the statements inside method volume() have executed, control is returned to the calling routine, and the execution resumes with the line of
code following the call. In general sense, a method is Java's way of implementing the subroutines.
There is something very important to notice inside the volume() method i.e., the instance variables depth, width, and height are referred to directly, without preceding them with object name or the dot (.) operator. When a method uses instance variable i.e., defined by its class, it does so directly, without explicit reference to an object and without the use of the dot (.) operator. This is simple to understand if you think about it. A method is always invokes relative to some object of its class. When this invocation has occurred, the object is known. Therefore, within a method, there is no need to specify the object, second time. This means that width, height, and depth inside the volume() implicitly refer to the copies of those variables which are found in the object that invokes volume().
« Previous Tutorial Next Tutorial »