Java - Methods

Ace your homework & exams now with Quizwiz!

The finalize( ) Method

- a method that will be called just before an object's final destruction by the garbage collector. - it can be used to ensure that an object terminates cleanly. protected void finalize( ) { // finalization code here }

The void Keyword

- create methods which do not return a value. - Call to a void method must be a statement

A constructor

- initializes an object when it is created. - has the same name as its class and is syntactically similar to a method - have no explicit return type. -Java automatically provides a default constructor // A simple constructor. class MyClass { int x; // Following is the constructor MyClass() { x = 10; } }

Method Calling : 2 ways

- method returns a value - returning nothing (no return value).

Variable Arguments(var-args)

- pass a variable number of arguments of the same type to a method. Syntax : typeName... parameterName printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); public static void printMax( double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (int i = 1; i < numbers.length; i++) if (numbers[i] > result) result = numbers[i]; System.out.println("The max value is " + result); }}

process of method calling

-When a program invokes a method, the program control gets transferred to the called method. - This called method then returns control to the caller in 2 conditions - the return statement is executed. - it reaches the method ending closing brace.

The this keyword

Used as a reference to the object of the current class, with in an instance method or a constructor. class Student { int age; Student(int age) { this.age = age; } }

Method Overloading

When a class has two or more methods by the same name but different parameters

A Java method

a collection of statements that are grouped together to perform an operation.

Parameterized Constructor

a constructor that accepts one or more parameters. // Following is the constructor MyClass(int i ) { x = i; }

Passing Parameters by Value

calling a method with a parameter.

Parameters

can be passed by value or by reference.

Creating Method

modifier returnType nameOfMethod (Parameter List) { // method body }


Related study sets

Promoting Healthy Pop ATI Violence for exam 3

View Set

OB Module 12: Change Management and Stress

View Set

ECON 200 Business Cycle, Unemployment, and Inflation

View Set

Mental Health Exam 2 NCLEX questions

View Set