Java parameter method return

Method Return Types and Parameters in Java

Learn what is method return types and parameters in java with code example and simple explanations.

  • how to return int and string data types in java from a method.
  • Using void keyword to prevent returning data from a method.
  • methods parameters and how to call them by supplying the values known as arguments.

Method Return Types in Java

We have learned what is method in java with Syntax and definition already in previous post and have learned basics about it. Now, lets learn about return type of a method in java.

Syntax of method in Java

modifier returnValueType methodName(list of parameters) < // Method body; //Group of statements >

Return type: void – The method returns nothing

We use “void” keyword if we want a method not to return anything but perform operations only / Execute group of statements.

public static void myMethod() < //no return statement as return type of method is void >

NOTE: if return type is anything except void, then method must have “return “statement.

Return type: int – The method returns int data type

public static int myMethod() < //return int value 5 return 2+3; >

NOTE: If you have return type “void”, then you don’t need to write “return” statement. As we have written return statement e.g. return 2+3; in above method that is returning int data type of value.

Return type: String – The method returns String data type of value

public static String myMethod() < //return String value Rakesh Singh return "Rakesh Singh"; >

Java Code Example:

Lets see how we can call a method returning int value and use them. As an example, lets call the method myMethod() in main()method of java program.

In main method, we have call the myMethod() that returns value 5. So, have created a int variable to store that value and display that using system.out.println method.

public class Sample < public static void main(String[] args) < int value = myMethod(); System.out.println("Value returned from method myMethod() wp-block-code">public class JavaMethods < public static void main(String[] args) < //call the method. the method will return // string value //Store that in a variable of string type String name = myMethod(); System.out.println("My name is :" + name); >public static String myMethod() < String name = "Rakesh Singh"; return name; >> 

Output:
My name is :Rakesh Singh

NOTE: methods in java must have a return type. if not returning use return type “void”

Method Parameters in Java

If you look at the syntax of method, we have learned return type. Now, we will learn about method parameters in java i.e. methodName(list of parameters).

Syntax of method

modifier returnValueType methodName(list of parameters) < // Method body; //Group of statements >

A method receives value via parameter from where the method is called. It can have one or more parameters.
In below examples, the add method takes two int type of parameter i.e. int first and int second.
print method is taking one parameter of String type.

public static int add(int first, int second)<> public static int print(String msg) <> 

How to call methods with arguments in Java?

Let’s see a complete simple example.

In this example, we have an add method with two int type parameters i.e. int add(int first, int second), that will calculate sum using both parameters first and second and return the sum.

In main() method, we are calling add method by supplying two int values, also, known as agreements. method add, will receives these two arguments in its 2 parameters first and second and return the sum to main() method.

public class Sample < public static void main(String[] args) < // call the method add by supplying value int result = add(10, 20); System.out.println("Sum returned wp-block-heading">Method Parameter Vs Method Arguments in java 

In method declaration e.g. add(int first, int second), variable first and second are known as method parameter list that we write them during declaration of a method.

When we call a method by supplying values e.g. int result = add(10, 20); in above program, then these values are known as method arguments.

Exercises on Method Return Types and Parameters in Java

Exercise-1: Create a method named “print”. The method have 1 parameter of String type. It does not return anything. Call print method from main() method with string value and Display the message inside print method.

Solution to Exercise-1:

public class Sample < public static void main(String[] args) < print("Hello World"); >public static void print(String msg) < System.out.println(msg); >> 

Источник

Passing and Returning Objects in Java

Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-reference.
Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it.

  • While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
  • This effectively means that objects act as if they are passed to methods by use of call-by-reference.
  • Changes to the object inside the method do reflect the object used as an argument.

Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

Passing Objects as Parameters and Returning Objects

From the method side, a reference of type Foo with a name a is declared and it’s initially assigned to null.

boolean equalTo(ObjectPassDemo o);

Passing Objects as Parameters and Returning Objects

As we call the method equalTo, the reference ‘o’ will be assigned to the object which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.

System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Passing Objects as Parameters and Returning Objects

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean true will be return.

Again ‘o’ will reassign to ‘ob3’ as the following statement execute.

System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

Passing Objects as Parameters and Returning Objects

  • Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since values of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so else block will execute, and false will be returned.

In Java we can pass objects to methods as one can perceive from the below program as follows:

Источник

Оператор return в Java

Java-университет

Оператор return в Java - 1

Как мы знаем, язык Java является объектно-ориентированным языком программирования. То есть базовая концепция, т.к. сказать основа основ, заключается в том, что всё есть объект. Объекты описываются при помощи классов. В свою очередь у классов есть состояние и поведение. Например, банковский счёт может иметь состояние в виде количестве денег на счету и иметь поведения увеличение и уменьшение баланса. Поведение в Java реализуется при помощи методов. То, каким образом описывать методы, приводится в самом начале пути изучения Java. Например, в официальном tutorial от Oracle: «Defining Methods». Тут можно выделить два важных аспекта:

  • Каждый метод имеет сигнатуру. Сигнатура состоит из имени метода и его входных параметров;
  • Для методов должно быть указан тип возвращаемого значения (return type);
  • Тип возвращаемого значения не входит в сигнатуру метода.

Опять же, это следствие того, что Java язык строго типизированный и компилятор хочет заранее понимать, какие типы и где используются на столько, на сколько это возможно. Опять же, чтобы уберечь нас от ошибок. В общем, всё во благо. Ну и нам это лишний раз прививает культуру обращения с данными, как мне кажется. Итак, для методов указывается тип значения. А чтобы вернуть это самое значение из методов используется ключевое слово return .

Ключевое слово оператор return в Java

Ключевое слово оператор return относится к выражениям «управления ходом выполнения», о чём указано в oracle tutorial «Control Flow Statements». О том, как нужно возвращать значения можно так же прочитать в официальном tutorial: «Returning a Value from a Method». Компилятор тщательно следит, на сколько у него хватает сил, за тем, чтобы возвращаемое из метода значение соответствовало указанному у метода типу возвращаемого значения. Воспользуемся для примера Online IDE от tutorialspoint. Посмотрим на изначальный пример:

Как мы видим, здесь выполняется main метод, который является точкой входа в программу. Строчки кода выполняются сверху вниз. Наш main метод не может возвращать значения, иначе мы получим ошибку: « Error: Main method must return a value of type void ». Поэтому, метод просто выполнит вывод на экран. Давайте теперь вынесем получение строки в отдельный метод получения сообщения:

 public class HelloWorld < public static void main(String []args) < System.out.println(getHelloMessage()); >public static String getHelloMessage() < return "Hello World"; >> 

Как мы видим, при помощи ключевого слова return мы указали возвращаемое значение, которое использовали далее в методе println . В описании (определении) метода getHelloMessage мы указали, что он вернёт нам String . Это позволяет компилятору проверить, что действия метода согласуются с тем, каким образом он объявлен. Естественно, тип возвращаемого значения, указанного в определении метода, может быть более широким чем тип возвращаемого из кода значения, т.е. главное чтобы типы приводились друг к другу. В противном случае мы получим ошибку во время компиляции: « error: incompatible types ». Кстати, наверно сразу появился вопрос: Почему return относится к операторам управления ходом выполнения программы. А потому, что он может нарушать обычный ход выполнения программы "сверху вниз". Например:

 public class HelloWorld < public static void main(String []args)< if (args.length == 0) < return; >for (String arg : args) < System.out.println(arg); >> > 

Как видно из примера, мы прерываем выполнение метода main в том случае, если java программа наша вызвана без параметров. Важно помнить, что если у вас после return есть код, он становится недоступным. И это заметит наш умный компилятор и не даст вам запустить такую программу. Например, данный код не скомпилируется:

 public static void main(String []args)

Есть один «грязный хак» для обхода такого. Например, для целей отладки или ещё почему-то. Выше указанный код можно починить обернув return в if блок:

Оператор Return при обработке ошибок

Есть одно очень хитрое обстоятельство – мы можем использовать return совместно с обработкой ошибок. Сразу хочется сказать, что использование return в catch блоке это очень и очень плохой тон, поэтому стоит этого избегать. Но нам ведь нужен пример? Вот он:

 public class HelloWorld < public static void main(String []args) < System.out.println("Value is: " + getIntValue()); >public static int getIntValue() < int value = 1; try < System.out.println("Something terrible happens"); throw new Exception(); >catch (Exception e) < System.out.println("Catched value: " + value); return value; >finally < value++; System.out.println("New value: " + value); >> > 

На первый взгляд кажется, что должно вернуться 2, ведь finally выполняется всегда. Но нет, значение будет 1, а изменение переменной в finally будет проигнорировано. Более того, если бы value содержала бы объект и мы в finally сказали бы value = null , то из catch вернулась бы всё равно ссылка на объект, а не null . А вот из блока finally оператор return сработал бы правильно. Коллеги за такой подарок явно не скажут спасибо.

void.class

Ну и напоследок. Можно написать странную конструкцию вида void.class . Казалось бы, зачем и в чём смысл? На самом деле, в различных фрэймворках и хитрых случаях, когда используется Java Reflection API, это может очень понадобится. Например, можно проверять, какой тип возвращает метод:

 import java.lang.reflect.Method; public class HelloWorld < public void getVoidValue() < >public static void main(String[] args) < for (Method method : HelloWorld.class.getDeclaredMethods()) < System.out.println(method.getReturnType() == void.class); >> > 

Это может быть полезно в тестовых фрэймворках, где необходимо подменять реальный код методов. Но для этого нужно понимать, как этот метод себя ведёт (т.е. какие типы возвращает). Есть ещё второй способ реализации метода main из кода выше:

 public static void main (String[] args) < for (Method method : HelloWorld.class.getDeclaredMethods()) < System.out.println(method.getReturnType() == Void.TYPE); >> 

Довольно интересное обсуждение разницы между ними можно прочитать на stackoverflow: What is the difference between java.lang.Void and void? #Viacheslav

Источник

Читайте также:  Twig to php online
Оцените статью