Unit 2
Unit 2
METHODS:
• Methods are subroutines that manipulate the data defined by class and in some cases,
control access to that data
• The only required elements of a method declaration are the method's return type, name,
a pair of parentheses, (), and a body between braces, {}.
• Two of the components of a method declaration comprise the method signature—the
method's name and the parameter types.
• Method declarations have six components, in order:
1. Modifiers—such as public, private
2. The return type—the data type of the value returned by the method, or void if
the method does not return a value.
3. The method name—the rules for field names apply to method names as well,
but the convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses, (). If there are no
parameters, you must use empty parentheses.
5. The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
• General Form:
type name(parameter-list) {
// body of method
}
• The type of data returned by a method must be compatible with the return type specified
by the method.
• The variable receiving the value returned by a method must also be compatible with the
return type specified for the method.
return value; //Here, value is the value returned.
void sample( ){
for(int i=0; i<10; i++){
if(i==5)
return; //stop at 5
System.out.println(i);
}
}
• The for loop will only run from 0 to 5 because once i equals 5, the method returns.
Returning a Value:
• Methods return a value to the calling routing using this form of return:
return value;
• This from can be used only with methods that have a non-void return type.
OUTPUT:
Using Parameters:
• Value passed to a method is called an argument. Variable that receives the argument is
called a parameter.
• Parameters are declared inside the parentheses that follow the method’s name.
For ex:
class ckNum{
//return true if x is even
boolean isEven(int x){
if((x%2)==0) return true;
else return false;
}
}
Class Demo{
public static void main(String[ ] args){
ckNum e=new ckNum();
if(e.isEven(10))
System.out.println(“10 is even”);
if(e.isEven(9))
System.out.println(“9 is even”);
}
}
OUTPUT:
10 is even
• In the program isEven( ) is called twice, each time a different value is passed.
• When isEven( ) is called the first time, it is passed the value 10. Thus, when isEven( )
begins executing, the parameter x receives the value 10.
• In the second call, it is passed the value 9. Thus, when isEven( ) begins executing, the
parameter x receives the value 9.
Constructors
• It can be tedious to initialize all of the variables in a class each time an instance is
created.
• Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through a special type of method called Constructor which
is used to initialize the object
• A constructor initializes an object immediately upon creation
Rules for creating java constructor:
o It has the same name as the class in which it resides and is syntactically similar
to a method.
o They have no explicit return type.
Types of java constructors:
• There are two types of constructors:
o Default constructor (no-arg constructor)
o Parameterized constructor
Default Constructor:
• Constructor which does not take any argument is called default constructor.
• All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor.
• However, once you define your own constructor, the default constructor is no longer
used
Parameterized Constructors:
• Constructor which takes one or more arguments is called parameterized constructor.
The finalize( ) Method
• By using finalization, you can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
• To add a finalizer to a class, you simply define the finalize( ) method.
• The Java run time calls that method whenever it is about to recycle an object of that
class. Inside the finalize( ) method, actions that must be performed before an object is
destroyed will be specified.
• The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects
• The keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class
• It is important to understand that finalize( ) is only called just prior to garbage
collection.
• It is not called when an object goes out-of-scope, for example. This means that you
cannot know when—or even if—finalize( ) will be executed
• Member c is given private access. This means that it cannot be accessed by code outside
of its class. So, inside the AccessTest class, c cannot be used directly. It must be
accessed through its public methods: setc( ) and getc( )
Pass Objects to Methods
• So far, we have only been using primitive types such as int as parameters to methods.
However, it is both correct and common to pass objects to methods.
For example,
• The equals( ) method inside Test compares two objects for equality and returns the
result. That is, it compares the invoking object with the one that it is passed. If they
contain the same values, then the method returns true. Otherwise, it returns false
Returning Objects
• A method can return any type of data, including class types that you create.
• For example
Method Overloading
• In Java it is possible to define two or more methods within the same class that share the
• same name, as long as their parameter declarations are different.
• When this is the case, the methods are said to be overloaded, and the process is referred
to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism
• When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call
• Thus, overloaded methods must differ in the type and/or number of their parameters.
• When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.
Example,
• test( ) is overloaded four times
• In some cases, Java’s automatic type conversions can play a role in overload
resolution.
Example,
• This version of OverloadDemo does not define test(int). Therefore, when test( )
is called with an integer argument inside Overload, no matching method is found.
• Java can automatically convert an integer into a double
• Java will employ its automatic type conversions only if no exact match is found.
• Overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
Example,
Overloading Constructors
• Like methods, constructors can also be overloaded
For example,
• The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N.
• When fact( ) is called with an argument of 1, the function returns 1; otherwise, it returns
the product of fact(n–1)*n. To evaluate this expression, fact( ) is called with n–1. This
process repeats until n equals 1 and the calls to the method begin returning.
Understanding static
• Normally, a class member must be accessed only in conjunction with an object of its
class. However, it is possible to create a member that can be used by itself, without
reference to a specific instance.
• To create such a member, precede its declaration with the keyword static. When a
member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object.
• You can declare both methods and variables to be static.
• The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
static Variables
• Variables declared as static are, essentially, global variables. When objects of its class
are declared, no copy of a static variable is made. Instead, all instances of the class share
the same static variable.
• General form of accessing static variable is
Classname.static_variablename;
• For example,
MyTimer.count = 10;
• Example 1 shows differences between a static variable and an instance variable
• y is accessed through its class name
Example 2
static Methods
• Methods declared as static are, essentially, global methods.
• They are called independently of any object. A static method is called through its class
name
• For example,
// use a static method.
class StaticMeth {
static int val = 1024; // a static variable
• Methods declared as static have several restrictions:
o They can only call other static methods.
o They must only access static data.
o They cannot refer to this or super in any way.
static Blocks
• Java allows to declare a static block.
• A static block is executed when the class is first loaded.
• Thus, it is executed before the class can be used for any other purpose
For example,
Varargs: Variable Length Arguments
• Java has included a feature that simplifies the creation of methods that need to take
a variable number of arguments. This feature is called varargs and it is short for
variable-length arguments.
• A method that takes a variable number of arguments is called a variable-arity
method, or simply a varargs method
• A variable-length argument is specified by three periods (...). For example, here is
how vaTest( ) is written using a vararg:
static void vaTest(int ... v) {
• This syntax tells the compiler that vaTest( ) can be called with zero or more arguments.
As a result, v is implicitly declared as an array of type int[ ]
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
• Here, there is an attempt to declare a regular parameter after the varargs parameter,
which is illegal.
• There is one more restriction to be aware of: there must be only one varargs parameter.
• For example, this declaration is also invalid:
int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!
• The attempt to declare the second varargs parameter is illegal.
• Although the parameter lists of vaTest( ) differ, there is no way for the compiler to
resolve the following call:
vaTest(1)
• Does this translate into a call to vaTest(int ...), with one varargs argument, or into a
call to vaTest(int, int ...) with no varargs arguments? There is no way for the compiler
to answer this question. Thus, the situation is ambiguous.
• Class Inner is defined within the scope of class Outer. Therefore, any code in class
Inner can directly access the variable outer_x
• An instance method display( ) is defined inside Inner. This method displays outer_x
• The main( ) method of InnerClassDemo creates an instance of class Outer and
invokes its test( ) method. That method creates an instance of class Inner and the
display( ) method is called.
• An instance of Inner can be created only within the scope of class Outer. The compiler
generates an error message if any code outside of class Outer attempts to instantiate
class Inner
• However, its possible to create an instance of Inner outside of Outer by qualifying its
name with Outer, as in Outer.Inner.
• An inner class has access to all of the members of its enclosing class, but the reverse is
not true.
• Members of the inner class are known only within the scope of theinner class and may
not be used by the outer class.
For example
• It is possible to define inner classes within any block scope.