Java Yöntemleri (Örneklerle)

Bu eğitimde Java yöntemlerini, yöntemlerin nasıl tanımlanacağını ve Java programlarında yöntemlerin nasıl kullanılacağını örnekler yardımıyla öğreneceğiz.

Java Yöntemleri

Bir yöntem, belirli bir görevi yerine getiren bir kod bloğudur.

Bir daire oluşturmak ve renklendirmek için bir program oluşturmanız gerektiğini varsayalım. Bu sorunu çözmek için iki yöntem oluşturabilirsiniz:

  • çemberi çizmek için bir yöntem
  • daireyi renklendirmek için bir yöntem

Karmaşık bir problemi daha küçük parçalara bölmek, programınızın anlaşılmasını kolaylaştırır ve yeniden kullanılabilir hale getirir.

Java'da iki tür yöntem vardır:

  • Kullanıcı Tanımlı Yöntemler : Gereksinimlerimize göre kendi yöntemimizi oluşturabiliriz.
  • Standart Kitaplık Yöntemleri : Bunlar, Java'da kullanılabilen yerleşik yöntemlerdir.

Önce kullanıcı tanımlı yöntemleri öğrenelim.

Java Yöntemi Bildirmek

Bir yöntemi bildirmek için sözdizimi şöyledir:

 returnType methodName() ( // method body )

Buraya,

  • returnType - Bir yöntemin ne tür bir değer döndürdüğünü belirtir. Örneğin, bir yöntemin bir intdönüş türü varsa, bir tamsayı değeri döndürür.
    Yöntem bir değer döndürmezse, dönüş türü void.
  • methodName - Bir programdaki belirli bir yönteme başvurmak için kullanılan bir tanımlayıcıdır.
  • method body - Bazı görevleri gerçekleştirmek için kullanılan programlama ifadelerini içerir. Yöntem gövdesi küme parantezlerinin içine alınır ( ).

Örneğin,

 int addNumbers() ( // code )

Yukarıdaki örnekte, yöntemin adı adddNumbers(). Ve dönüş türü int. Bu eğitimde daha sonra iade türleri hakkında daha fazla bilgi edineceğiz.

Bu, bir yöntemi bildirmenin basit sözdizimidir. Ancak, bir yöntemi bildirmenin tam sözdizimi şöyledir:

 modifier static returnType nameOfMethod (parameter1, parameter2,… ) ( // method body )

Buraya,

  • değiştirici - Yöntemin genel, özel, vb. olup olmadığına ilişkin erişim türlerini tanımlar. Daha fazla bilgi edinmek için Java Access Specifier'ı ziyaret edin.
  • statik - staticAnahtar kelimeyi kullanırsak, nesneler oluşturmadan erişilebilir.
    Örneğin, sqrt()standart Math sınıfının yöntemi statiktir. Bu nedenle, Math.sqrt()bir Mathsınıf örneği oluşturmadan doğrudan arayabiliriz .
  • parametre1 / parametre2 - Bunlar bir yönteme iletilen değerlerdir. Bir yönteme herhangi bir sayıda argüman aktarabiliriz.

Java'da Bir Yöntemi Çağırma

Yukarıdaki örnekte, adında bir yöntem bildirdik addNumbers(). Şimdi, yöntemi kullanmak için onu çağırmamız gerekiyor.

addNumbers()Yöntemi şu şekilde çağırabiliriz .

 // calls the method addNumbers();
Java Yöntem Çağrısının Çalışması

Örnek 1: Java Yöntemleri

 class Main ( // create a method public int addNumbers(int a, int b) ( int sum = a + b; // return value return sum; ) public static void main(String() args) ( int num1 = 25; int num2 = 15; // create an object of Main Main obj = new Main(); // calling method int result = obj.addNumbers(num1, num2); System.out.println("Sum is: " + result); ) )

Çıktı

 Toplam: 40

Yukarıdaki örnekte, adlı bir yöntem oluşturduk addNumbers(). Yöntem, a ve b olmak üzere iki parametre alır. Çizgiye dikkat edin,

 int result = obj.addNumbers(num1, num2);

Burada, num1 ve num2 argümanlarını ileterek yöntemi çağırdık. Yöntem bir değer döndürdüğünden, değeri sonuç değişkeninde sakladık.

Not : Yöntem statik değildir. Bu nedenle, sınıfın nesnesini kullanarak yöntemi çağırıyoruz.

Java Yöntemi İade Türü

Bir Java yöntemi, işlev çağrısına bir değer döndürebilir veya dönmeyebilir. Herhangi bir değeri döndürmek için return ifadesini kullanırız. Örneğin,

 int addNumbers() (… return sum; )

Burada, değişken toplamını döndürüyoruz. İşlevin dönüş türü olduğundan int. Toplam değişkeni inttürde olmalıdır . Aksi takdirde, bir hata oluşturacaktır.

Örnek 2: Yöntem İade Türü

 class Main ( // create a method public static int square(int num) ( // return statement return num * num; ) public static void main(String() args) ( int result; // call the method // store returned value to result result = square(10); System.out.println("Squared value of 10 is: " + result); ) )

Çıktı :

 10'un kare değeri: 100

Yukarıdaki programda adında bir yöntem oluşturduk square(). Yöntem, parametresi olarak bir sayıyı alır ve sayının karesini döndürür.

Burada yöntemin dönüş tipinden olarak bahsettik int. Bu nedenle, yöntem her zaman bir tamsayı değeri döndürmelidir.

Bir değer döndüren Java yönteminin temsili

Note: If the method does not return any value, we use the void keyword as the return type of the method. For example,

 public void square(int a) ( int square = a * a; System.out.println("Square is: " + a); )

Method Parameters in Java

A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any number of parameters. For example,

 // method with two parameters int addNumbers(int a, int b) ( // code ) // method with no parameter int addNumbers()( // code )

If a method is created with parameters, we need to pass the corresponding values while calling the method. For example,

 // calling the method with two parameters addNumbers(25, 15); // calling the method with no parameters addNumbers()

Example 3: Method Parameters

 class Main ( // method with no parameter public void display1() ( System.out.println("Method without parameter"); ) // method with single parameter public void display2(int a) ( System.out.println("Method with a single parameter: " + a); ) public static void main(String() args) ( // create an object of Main Main obj = new Main(); // calling method with no parameter obj.display1(); // calling method with the single parameter obj.display2(24); ) )

Output

 Method without parameter Method with a single parameter: 24

Here, the parameter of the method is int. Hence, if we pass any other data type instead of int, the compiler will throw an error. It is because Java is a strongly typed language.

Note: The argument 24 passed to the display2() method during the method call is called the actual argument.

The parameter num accepted by the method definition is known as a formal argument. We need to specify the type of formal arguments. And, the type of actual arguments and formal arguments should always match.

Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

For example,

  • print() is a method of java.io.PrintSteam. The print("… ") method prints the string inside quotation marks.
  • sqrt() is a method of Math class. It returns the square root of a number.

Here's a working example:

Example 4: Java Standard Library Method

 public class Main ( public static void main(String() args) ( // using the sqrt() method System.out.print("Square root of 4 is: " + Math.sqrt(4)); ) )

Output:

 Square root of 4 is: 2.0

To learn more about standard library methods, visit Java Library Methods.

What are the advantages of using methods?

1. The main advantage is code reusability. We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times".

Example 5: Java Method for Code Reusability

 public class Main ( // 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 int result = getSquare(i); System.out.println("Square of " + i + " is: " + result); ) ) )

Output:

 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

In the above program, we have created the method named getSquare() to calculate the square of a number. Here, the method is used to calculate the square of numbers less than 6.

Hence, the same method is used again and again.

2. Yöntemler, kodu daha okunaklı ve daha kolay hata ayıklama yapar. Burada getSquare()yöntem, bir bloktaki kareyi hesaplamak için kodu tutar. Dolayısıyla daha okunaklı hale getirir.

Ilginç makaleler...