0% found this document useful (0 votes)
78 views

3 Methods in Java

Here is a Java program that accepts a 2x2 array from user input and prints the array elements: ```java import java.util.Scanner; public class ArrayInput { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[][] arr = new int[2][2]; System.out.println("Enter elements of 2x2 array:"); for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { arr[i][j] = input.nextInt(); } } System.out.println("Entered array:");
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

3 Methods in Java

Here is a Java program that accepts a 2x2 array from user input and prints the array elements: ```java import java.util.Scanner; public class ArrayInput { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[][] arr = new int[2][2]; System.out.println("Enter elements of 2x2 array:"); for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { arr[i][j] = input.nextInt(); } } System.out.println("Entered array:");
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

METHODS IN JAVA

__________________________________________________________
 Modularize the tasks of the program or structure the program.

 Functions separate the concept (what is done) from the implementation (how it is
done).
Note:-( ) Denotes for creating method

Methods of Scanner class


Here, we are discussing some of the important methods of Scanner class, which are used to
design a Java program with user input. The methods are:
1) int nextInt()
It is used to read an integer value from the keyboard.
2) float nextFloat()
It is used to read a float value from the keyboard.
3) long nextLong()
It is used to read a long value from the keyboard.
4) String next()
It is used to read string value from the keyboard.

next() method in java

1. It is a method of Scanner class in java.


2. next() method can read input till the space (i.e. it will print words till the space and whenever it gets
space it stops working and give the result till the space).
3. With the help of next() method we can't read those words which contain space itself (If we do then
we will get irrelevant results).
4. In other words next() method can take input till space and ends input of getting space.
5. In next() method it places the cursor in the same line after reading the input.
6. In next() its escaping sequence is space not ('\n').
nextLine() method in java

1. It is a method of Scanner class in java.


2. nextLine() method can read input till the line change (i.e. it will print words till the line change or
press enter or '\n' and whenever it gets '\n' or press enter it stops working and give the result of
whole line until press enter or line change).
3. With the help of nextLine() method Also we can read those words which contain spaces itself .
4. In other words nextLine() method can take input till the line change or new line and ends input of
getting '\n' or press enter.
5. In nextLine() method it places the cursor in the new or next line after reading the input.
6. In nextLine() its escaping sequence is '\n' or press enter not space.

Defining a Method:
– A method definition consists of its method name, parameters, return value type, and body.
– The syntax for defining a method is:

modifier returnValueType methodName(list of parameters)


{
// Method body;
}
How to call a Java Method?

Now you defined a method, you need to use it. For that, you have to call the method.
Here's how:

myMethod();
This statement calls the myMethod() method that was declared earlier.

Java Methods with Arguments and Return Value

A Java method can have zero or more parameters. And, they may return a value.

Example: Return Value from Method

Let's take an example of method returning a value.

class SquareMain {
public static void main(String[] args) {
int result;
result = square();
System.out.println("Squared value of 10 is: " + result);
}

public static int square() {


// return statement
return 10 * 10;
}

When you run the program, the output will be:


Squared value of 10 is: 100

Exercise
__________________________________________________________
Java program which illustrates a square of any number accepted from keyboard using method.

Output
public class ArithematicMain {

public static int getIntegerSum (int i, int j) {


return i + j;
}

public static int multiplyInteger (int x, int y) {


return x * y;
}

public static void main(String[] args) {


System.out.println("10 + 20 = " + getIntegerSum(10, 20));
System.out.println("20 x 40 = " + multiplyInteger(20, 40));
}
}

When you run the program, the output will be:

10 + 20 = 30
20 x 40 = 800

Example: Get Squared Value Of Numbers from 1 to 5


public class JMethods {

// method defined
private static int getSquare(int x){
return x * x;
}

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {

// method call
result = getSquare(i)
System.out.println("Square of " + i + " is : " + result); }
}
}

When you run the program, the output will be:

Square of 1 is : 1

Square of 2 is : 4

Square of 3 is : 9

Square of 4 is : 16

Square of 5 is : 25
Example
Sum of two integer number using method

EXERCISE
Maximum of two number using method in java
Method overloading
__________________________________________________________
 Two or more METHODS can have the same name but different parameters.
 Process of using the same name for two or more METHODS.
 Used so that a programmer does not have to remember multiple METHOD names.

Array in Java
 Array is a collection of similar type of elements that have contiguous memory location.
 Java array is an object that contains elements of similar data type. We can store fixed of elements
on a java array.
 Array in java is index based, first element of the array is stored at 0 index.
 An array is a container that holds data (values) of one single type. For example, you can
create an array that can hold 100 values of int type.
 One-dimensional arrays.
How to declare an array?
Here's how you can declare an array in Java:

datatype age [ ]

How to initialize arrays in Java?


In Java, you can initialize arrays during declaration or you can initialize (or change
values) later in the program as per your requirement.

Initialize an Array During Declaration

Here's how you can initialize an array during declaration.


int age []= {12, 4, 5, 2, 5};

This statement creates an array and initializes it during declaration.

The length of the array is determined by the number of values provided which is separated by commas. In
our example, the length of age array is 5.

How to access array elements?


 Note: when initializing an array, we can provide fewer values than the array elements.
E.g. int a [5] = {10, 2, 3}; in this case the compiler sets the remaining elements to zero.

You can easily access and alter array elements by using its numeric index. Let's take an
example.

class ArrayExample {
public static void main(String[] args) {

int[] age = new int[5];

age[2] = 14;

age[0] = 34;

for (int i = 0; i < 5; ++i) {


System.out.println("Element at index " + i +": " + age[i]);
}
}
}

When you run the program, the output will be:

Element at index 0: 34
Element at index 1: 0
Element at index 2: 14
Element at index 3: 0
Element at index 4: 0

 How to print elements of array.


class ArrayExample {
public static void main(String[] args) {

int age []= {12, 4, 5, 2, 5};

for (int i = 0; i < 5; ++i) {


System.out.println("Element at index " + i +": " + age[i]);
}
}
}

When you run the program, the output will be:

Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5

Example: Java arrays


The program below computes sum and average of values stored in an array of type int.
Exercise

Display the sum of 1 up to 5 in the array name of day.


#include <iostream.h>
#include<conio.h>
int day [ ] = {1, 2, 3, 4, 5}; //output is 15
int i, sum=0;
void main ()
{
for ( i=0 ; i<=4 ; i++ )
{
sum += day[i];//sum=sum+day[i];
}
cout << “result=”<<sum;
getch();
}

class SumAverage {
public static void main(String[] args) {

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};


int sum = 0;
Double average;

for (int number: numbers) {


sum += number;
}

int arrayLength = numbers.length;

// Change sum and arrayLength to double as average is in double


average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);


System.out.println("Average = " + average);
}
}

When you run the program, the output will be:

Sum = 36
Average = 3.6
Multidimensional Arrays

In Java, you can declare an array of arrays known as multidimensional array. Here's an
example to declare and initialize multidimensional array.

Double matrix [][]= {{1.2, 4.3, 4.0}, {4.1, -1.1}};

Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of
type int.

How to initialize a 2d array in Java?


Here's an example to initialize a 2d array in Java.

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

Initialize Array an integer elements of 1, 2, 3, 10, 20,30 to A[2] [3].


Or int A[2][3] ={1, 2, 3, 10, 20, 30}
Accessing Two-Dimensional Array Elements
(How to read and print elements)

Exercise
What is output the “ff” code fragment?

 Exercise

Create the 2 by 3 dimensional array elements of 1,2,8,3,3,5


Initializing arrays with input values.
__________________________________________________________

Exercise
Write a c++ program that accepts 2*2 array and print the given array Element.
The following loop initializes the array with user input values:

import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + "
columns: ");
for(int row = 0; row <matrix.length; row++){
for(int column = 0; column <matrix[0].length; column++){
matrix[row][column] = input.nextInt();
}
}
Example: Program to Add Two Matrices
public class AddMatrices {

public static void main(String[] args) {


int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };

// Adding Two matrices


int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}

// Displaying the result


System.out.println("Sum of two matrices is: ");
for(int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

When you run the program, the output will be:

Sum of two matrices is:

-2 8 7

10 8 6
Example: Program to Multiply Two Matrices using a
Function
public class MultiplyMatrices {

public static void main(String[] args) {


int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

// Mutliplying Two matrices


int[][] product = multiplyMatrices(firstMatrix, secondMatrix, r1,
c1, c2);

// Displaying the result


displayProduct(product);
}

public static int[][] multiplyMatrices(int[][] firstMatrix, int[][]


secondMatrix, int r1, int c1, int c2) {
int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] *
secondMatrix[k][j];
}
}
}
return product;
}

public static void displayProduct(int[][] product) {


System.out.println("Product of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
String Processing
• The classes String, StringBuilder, and StringBuffer, StringTokenizer are used for
processing strings.
• The String Class
– A string is a sequence of characters.
– In many languages, strings are treated as an array of characters, but in Java
a string is treated as an object.
A String object is immutable: Its content cannot be changed once the string is created.

Syntax for creating string


– You can create a string object using
• A string literal or
• An array of characters.
Using String literal
– String message = "Welcome to Java”;
Using array of characters.
– For example, the following statements create the string "Good Day”:
char wish [ ] = {'G' , 'o' , 'o' , 'd' , ' ' , 'D’ , 'a' , 'y’}
The StringBuilder and StringBuffer Classes
 The StringBuilder and StringBuffer classes are similar to the String class except that the String
class is immutable String object is fixed once the string is created
 StringBuilder and StringBuffer are more flexible than String.
 You can add, insert, or append new contents into StringBuilder and StringBuffer objects, whereas
the value of a String object is fixed once the string is createdthey are Mutable means one can
change the value of the object .
 Use StringBuffer if the class might be accessed by multiple tasks concurrently.
 Using StringBuilder is more efficient if it is accessed by just a single task.

StringTokenizer Class
• The StringTokenizer class allows an application to break a string into tokens.
• When you read a sentence, your mind breaks it into tokens—individual words and
punctuation marks that convey meaning to you.
• Tokens are separated from one another by delimiters, typically white-space characters
such as space, tab, newline and comma.
String is a class in java, which provides some of the predefined methods that
make string based problem solutions easier. We don’t need to write code for
every operation, we have to just use its methods.

You might also like