Get value method java

Field get() method in Java with Examples

The get() method of java.lang.reflect.Field used to get the value of the field object. If Field has a primitive type then the value of the field is automatically wrapped in an object. If the field is a static field, the argument of obj is ignored; it may be null Otherwise, the underlying field is an instance field. This method throws a NullPointerException if the specified obj argument is null and an IllegalArgumentException If the specified object is not an instance of the class or interface declaring the underlying field. If the field is hidden in the type of obj, the field’s value is obtained according to the preceding rules. Syntax:

public double get(Object obj) throws IllegalArgumentException, IllegalAccessException

Parameters: This method accepts a single parameter obj which is the object to extract the field value from. Return value: This method returns the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned. Exception: This method throws following Exception:

  1. IllegalAccessException– if this Field object is enforcing Java language access control and the underlying field is inaccessible.
  2. IllegalArgumentException– if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementer thereof).
  3. NullPointerException– if the specified object is null and the field is an instance field.
  4. ExceptionInInitializerError– if the initialization provoked by this method fails.
Читайте также:  Css margin auto text align

Below programs illustrate get() method: Program 1:

Источник

Returning a Value from a Method

You declare a method’s return type in its method declaration. Within the body of the method, you use the return statement to return the value.

Any method declared void doesn’t return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

If you try to return a value from a method that is declared void , you will get a compiler error.

Any method that is not declared void must contain a return statement with a corresponding return value, like this:

The data type of the return value must match the method’s declared return type; you can’t return an integer value from a method declared to return a boolean.

The getArea() method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:

// a method for computing the area of the rectangle public int getArea()

This method returns the integer that the expression width*height evaluates to.

The getArea method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:

public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) < Bicycle fastest; // code to calculate which bike is // faster, given each bike's gear // and cadence and given the // environment (terrain and wind) return fastest; >

Returning a Class or Interface

If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.

When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number , which is in turn a subclass of Object , as illustrated in the following figure .

The class hierarchy for ImaginaryNumber

Now suppose that you have a method declared to return a Number :

public Number returnANumber()

The returnANumber method can return an ImaginaryNumber but not an Object . ImaginaryNumber is a Number because it’s a subclass of Number . However, an Object is not necessarily a Number — it could be a String or another type.

You can override a method and define it to return a subclass of the original method, like this:

public ImaginaryNumber returnANumber()

This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Источник

Getting a Value from a Method in Java

Book image

The things in parentheses are parameters. Each time you call your goToTheSupermarketAndBuySome method, you put a different value in the method’s parameter list.

Now what happens when your friend returns from the supermarket? “Here’s the bread you asked me to buy,” says your friend. As a result of carrying out your wishes, your friend returns something to you. You made a method call, and the method returns information (or better yet, the method returns some food).

The thing returned to you is called the method’s return value, and the type of thing returned to you is called the method’s return type.

A Java example

This code shows a method that returns a value

import static java.lang.System.out;

double getInterest(double rate)

double interest;

interest = balance * (rate / 100.0);

return interest;

NumberFormat currency = NumberFormat.getCurrencyInstance();

out.print(«The account with last name «);

This code calls the method in the code above.

public static void main(String args[])

Random myRandom = new Random();

NumberFormat currency = NumberFormat.getCurrencyInstance();

GoodAccountanAccount;

doubleyearlyInterest;

anAccount = new GoodAccount();

(char) (myRandom.nextInt(26) + ‘A’) +

(char) (myRandom.nextInt(26) + ‘a’) +

(char) (myRandom.nextInt(26) + ‘a’);

interestRate = myRandom.nextInt(5);

yearlyInterest = anAccount.getInterest(interestRate);

System.out.print(«This year’s interest is «);

Here’s a run from the code.

running Java code

How return types and return values work

  • The value of balance is 9508.00 , and the value of rat e is 2.0 . So the value of balance * (rate / 100.0) is 190.16 — one hundred ninety dollars and sixteen cents.
  • The value 190.16 gets assigned to the interest variable, so the statement
  • The return statement sends this value 190.16 back to the code that called the method. At that point in the process, the entire method call in the first set of code — anAccount.getInterest(interestRate) — takes on the value 190.16 .
  • Finally, the value 190.16 gets assigned to the variable yearlyInterest .

java method call

If a method returns anything, a call to the method is an expression with a value. That value can be printed, assigned to a variable, added to something else, or whatever. Anything you can do with any other kind of value, you can do with a method call.

Working with the method header

When you create a method or a method call, you have to be careful to use Java’s types consistently. Make sure that you check for the following:

In the first set of code, the getInterest method’s header starts with the word double . When the method is executed, it should send a double value back to the place that called it.

Again in the first set of code, the last statement in the getInterest method is return interest. The method returns whatever value is stored in the interest variable, and the interest variable has type double . So far, so good.

In the second set of code, the value returned by the call to getInterest is assigned to a variable named yearlyInterest . Sure enough, yearlyInterest is of type double.

That settles it! The use of types in the handling of method getInterest is consistent in both sets of code. I’m thrilled!

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

Источник

Returning Values From Methods (Java)

As my Java adventure continues I look today at returning values from methods. So far the methods I have discussed have completed a task but have not returned any values to the main method.

The previous methods have been defined as:

public static void methodName()

Methods in Java

I’ve put the word void in bold because this is the key to getting methods to return a value. The word void means “empty” and because it has been used Java is not expecting anything to return from the method.

To change the method from a void to a return the word void should be replaced with int, double, or char – readers of my variables post will notice that these are types of variables Java uses.

public static int returnNumber()

Java Return Method

The above example will return the integer 4 to the main method. The below methods so various examples of the returns including how values can be passed into a method and a new value returned (see addNumbers on the below image).

Examples of method returns method returns in action

public class methodReturn   public static void main(String[] args)  System.out.println(returnNumber());  System.out.println(returnLetter());  System.out.println(returnDouble());  System.out.println(addNumbers(3,3));  >  public static int returnNumber()  return(4);  >  public static char returnLetter()  return('g');  >  public static double returnDouble()  return(10.5);  >  public static int addNumbers(int num1, int num2)  int sum = num1 + num2;  return(sum);  > >

When Java hits the return keyword it exits out of the method and returns back to main void.

Whilst discussing Java, today I completed the “DEV276x: Learn to Program in Java” course offered by edX and Microsoft. I enjoyed the course as it had material to read, videos to watch, practical projects and 3 exams (pass mark is 70%).

Источник

Оцените статью