0% found this document useful (0 votes)
8 views17 pages

Java Lec 4

The document provides an overview of methods in Java, including their purpose, types, and how to declare and invoke them. It also covers constructors, arrays, command-line arguments, and nested classes, detailing their usage and examples. Key concepts such as method overloading, the 'this' keyword, and array manipulation are discussed to enhance understanding of Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

Java Lec 4

The document provides an overview of methods in Java, including their purpose, types, and how to declare and invoke them. It also covers constructors, arrays, command-line arguments, and nested classes, detailing their usage and examples. Key concepts such as method overloading, the 'this' keyword, and array manipulation are discussed to enhance understanding of Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Methods

 Method is a block of code that perform a specific tasks.


 None of the methods can be declared outside the class.

 Why Use Methods?

1. To Make the Code Reusable: If you need to do the same thing many
times, methods allow you to write code once and reuse it multiple times.

2. To Parameterize the Code: It allows methods to accept input values


(parameters), making them more dynamic and flexible.

3. For Top-down Programming You can easily solve a bigger or complex


problem by breaking it into smaller parts. The entire complex problem
can be broken down into methods.

4. To Simplify the Code: Because the complex code inside a method is


hidden from other parts of the program, it prevents accidental errors or
confusion.

 Method Type

 Two types of methods:


o instance methods and
o class methods.

1. Instance methods are used to access the instance variables but can also
access class variables.
2. Class methods can access class variables but cannot access the instance
variables unless and until they use an object for that.
 Method Declaration:

 Method declaration include method name, parameters and return type


of the method.
 Below is the syntax of method declaration.

Syntax:

[access_modifier] return_typemethod_name(parameter_list) [throws_clause]


{
// Method body
}

Example:
int methodOne (int x, String y)

The method declaration includes:


1. Modifiers: There are number of modifiers that can be used with a
method declaration.

Modifier Description
public, protected, Defines the scope—which class can invoke which method.
default or private
static The method can be invoked without creating an instance of
the class.
abstract The class must be extended and the abstract method must be
overridden in the subclass.
final The method cannot be overridden in a subclass.

2. Return Type: Specifies the data type of the value returned by the
method.
3. Method Name: The method name must be a valid Java identifier.
4. ParameterList: Defines the arguments the method accepts.
5. Curly Braces: The method body is contained in a set of curly braces.
 Instance Method Invocation:

 Methods cannot run on their own, they need to be invoked.


 Instance methods will be invoked by the objects of the class.

 Data that are passed to a method are known as arguments or


parameters.
 Actual parameters are those parameters that are passed to a function.
 Formal parameters are those parameters that are declared in the called
function declaration.

Example:

package Simple_Package;
class Example {

public void sayHello()


{
System.out.println("Hello, world!");
}

public int addNumbers(int a, int b)


{
return a + b;
}

public static void main(String[] args)


{
Example example = new Example();
example.sayHello();

int result = example.addNumbers(5, 3);


System.out.println("Sum of 5 and 3 is: " + result);
}
}
 Method Overloading
 Method overloading is one way of achieving polymorphism in Java.
 Method Overloading is a feature that allows a class to have two or more
methods with the same name but each with a different parameter list.
 Overloading allows you to perform the same action on different types
of inputs.
 When a method is called, Java decides which version of it to execute
depending on the arguments given.

Example:

package Simple_Package;
public class OverloadDemo {
void addition(int a, int b)
{
int sum=a+b;
System.out.println("Sum = " + sum);
}
void addition(int a, int b,int c)
{
int sum=a+b+c;
System.out.println("Sum = " + sum);
}
void addition(int a, int b,intc,int d)
{
int sum=a+b+c+d;
System.out.println("Sum = " + sum);
}

public static void main(String[] args) {


OverloadDemo od= new OverloadDemo();
od.addition(10, 20);
od.addition(10, 20,30);
od.addition(10, 20,30,40);
}

}
this Keyword

 ‘this’ is a reference variable that is used to refer the current object of the
class.
 The most common use of this keyword is to eliminate the confusion
between instance variables and local variables with the same name.
 It can be used to access instance variables and methods of the current
object.
 this can also be used to:
o refer to current class instance variables
o Invoke current class constructor
o Invoke current class method
o Return the current class object
o Pass an argument in the method call
o Pass an argument in the constructor call

Example:

package Simple_Package;
public class Rectangle {
double length;
double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public void displayArea() {


System.out.println("Area: " + (length * width));
System.out.println();
}

public static void main(String[] args) {

Rectangle rect = new Rectangle(3,9);

rect.displayArea();
}}
Constructors

 Whenever an object is created for a class, the instance variables of the


class need to be initialized, i.e., they need to be given initial values. It can
be done through constructors.
 Constructors are automatically called when an object of class is created.
 Constructors must have the same name as that of the class name.
 Constructors do not have any return type.

 Two types of constructors:


o No-argument constructor (Default Constructor), and
o Parameterized constructor.

 If the constructor is explicitly defined within the class, it is known as


explicit constructor.
 If there is no constructor explicitly defined within the class, java
automatically creates a default constructor as soon as the object is
created. They are known as default or no-argument constructors.
 But in case you define your own constructor within the class, the default
constructor will not be provided by Java. In that case, the constructor
defined within the class will be called.

Example:
package Simple_Package;
public class Rectangle {
double length;
double width;

public Rectangle() {
this.length = 1.0;
this.width = 1.0;
}
public void displayArea() {
double area = length * width;
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + area);
}

public static void main(String[] args) {


Rectangle rect1 = new Rectangle();
rect1.displayArea();
}
}

 Parameterized Constructors:
 Constructor that accepts parameters is known as parameterized
constructor.
 It is used to initialize the instance variables with specific values.

Example:

package Simple_Package;
public class Rectangle {
double length;
double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public void displayArea() {


System.out.println("Area: " + (length * width));
System.out.println();
}

public static void main(String[] args) {

Rectangle rect = new Rectangle(3,9);


rect.displayArea();
}
}

 Constructor Overloading:

 In Java, constructors can also be overloaded just like methods.


 Constructor Overloading is a feature that allows a class to have more
than one constructor with different parameter lists, i.e., different types
of arguments or different number of arguments.
 The compiler differentiates these constructors on the basis of arguments
passed to them.

Example:

package Simple_Package;

public class Rectangle {


double length;
double width;
public Rectangle() {
this.length = 1.0;
this.width = 1.0;
}

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public void displayArea() {


System.out.println("Area: " + (length * width));
System.out.println();
}

public static void main(String[] args) {


Rectangle rect = new Rectangle();
rect.displayArea();
}
}

Arrays:

 An array is a collection of elements of the same data type stored in a


contiguous memory location.
 Arrays can be of two types: 
1. one dimensional array 
2. multi-dimensional array

 One-dimensional Arrays:
 One-dimensional array is a linear collection of elements of the same
data type.
 Elements of an array can be accessed using their index. The index
represents the position of an element in the array.
 The indexation will start from 0 and will go up to n –1, i.e., the first
value of the array will have an index of 0 and the last value will have an
index of n –1, where n is the number of elements in the array.
Suppose, five marks to be assigned to each array element are 60, 58, 50, 78,
and 89. It will be done as follows:

Creation of Array
 Creating an array involve three steps: 
1) Declaring an array 
2) Creating memory locations 
3) Initializing/assigning values to an array

1) Declaring an Array:
 Declaring an array can be two ways:
o type arrayname[];
o type[] arrayname;

Example:
int marks[];
int[] marks;

2) Creating Memory Locations:


 Memory for the array is allocated using the new keyword. You must
specify the size of the array during this step.

Arrayname = new type [size];


Example:
marks = new int[5];

 Both Declaration of array and Creation of memory location can be


combined as one statement, for example,

type arrayname[] = new type[size];


or
type[] arrayname = new type[size];

Example:
int[] marks = new int[5];

3) Initializing/ assigning Values to an Array:


 Initialization of array, can be done as follows:

Arrayname[index] = value;
Example:

 Arrays can be assigned values at the time of declaration itself. The


syntax for the same can be,
type arrayname[] = {list of values};
Example:
int marks[] = {60, 58, 50, 78, 89};
int[] marks = {60, 58, 50, 78, 89};
How to Use for Loops with Arrays?
 The for loops can be used to assign and access values from an array.
 length property is used to obtain the number of elements in an array.

Example:

 Two-dimensionalArrays:

 Two-dimensional array is an array of arrays.


 Two-dimensional arrays are used to store data in the form of a table,
that is in the form of rows and columns.
 Two-dimensional array, the additional index has to be specified using
another set of square brackets.
 The following statements create a two-dimensional array, named as
marks, which would have 4 rows and 5 columns, as shown in Table 4.4.

int marks[][]; //declaration of a two-dimensional array


marks = new int[4][5]; //Memory Allocation

The two statements can be merged into one as,


int marks[][] = new int[4][5];
or
int[][] marks = new int[4][5];
 Like a one-dimensional array, two-dimensional arrays may be initialized
with values at the time of their creation.

For example:

int marks[][] = {{2, 3, 6, 0}, {9, 3, 3, 2}};

 Using for-each with Arrays:

 The for-each loop also called the enhanced for loop was introduced in
Java 5 to provide a simpler way to iterate through all the elements of an
array or a collection.
 A for-each loop directly accesses elements without using index.
Syntax:

for (type var : array)


{
statements using var;
}

Parameters:
type: The data type of the elements in the array or collection.
var: The variable that holds the current element during each iteration.
array: The array or collection being iterated over.

 Passing Arrays to Methods:


 Arrays can be passed to methods as well. The following example shows
an array being passed to a method.

Example:
package First_Package;
public class First_Program {
void printArray(int[] arr) {
for (int i = 0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
First_Program fp = new First_Program();
int[] numbers = {10, 20, 30, 40, 50};
fp.printArray(numbers);
}
}

 Returning Arrays from Methods:


 Arrays can be used as return value from methods. The following
example shows an array being returned from a method.

Example:

package First_Package;
public class First_Program {

int[] createArray()
{
int[] arr = {10, 20, 30, 40, 500};
return arr; // Return the array
}

public static void main(String[] args) {

First_Programfp = new First_Program();


int[] arr = fp.createArray();

for (int i = 0; i<arr.length; i++)


{
System.out.println(arr[i]);
}

}
}

Command-line Arguments
 Command-line argument in Java is a way to pass data to a program
when it is executed.
 These arguments are supplied at runtime and are accessible in the
program through the String[] args parameter of the main method.
 Command-line arguments are stored in the args array.
 Each argument is a string, and the first argument is at args[0], the
second at args[1], and so on.

Example:
package First_Package;
public class First_Program {

public static void main(String[] args) {

int x = args.length;
for (int i = 0; i< x; i++)
System.out.println(args[i]);

}
}

Nested Classes.

 In Java, a nested class is a class defined inside another class. Nested


classes are of the following types:
o Non-static inner classes
o Static nested classes
o Local classes

1. Non-Static Inner Classes:


A non-static inner class is a class defined inside another class without
the static keyword. It has access to the outer class's members, including
private members.
public class OuterClass {
private int x = 10;
public class InnerClass {
public void printX() {
System.out.println("Value of x: " + x);
}
}

public static void main(String[] args) {


OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.printX(); // Output: Value of x: 10
}
}

2. Static Nested Classes:


A static nested class is a class defined inside another class with
the static keyword. It does not have access to the outer class's non-static
members.
public class OuterClass {
private static int x = 10;

public static class NestedClass {


public static void printX() {
System.out.println("Value of x: " + x);
}
}

public static void main(String[] args) {


OuterClass.NestedClass.printX(); // Output: Value of x: 10
}
}

3. Local Classes:
A local class is a class defined inside a method or a block. It has access to the
local variables of the method or block.
public class OuterClass {
public void myMethod()
{
int x = 10;

class LocalClass
{
public void printX()
{
System.out.println("Value of x: " + x);
}
}
LocalClass local = new LocalClass();
local.printX(); // Output: Value of x: 10
}

public static void main(String[] args) {


OuterClass outer = new OuterClass();
outer.myMethod();
}
}

You might also like