1 / 26

Methods in Java

Methods in Java. Program Modules in Java. Java programs are written by combining new methods and classes with predefined methods in the Java Application Programming Interface ( Java API or Java class library ) and in various other class libraries

nola-dennis
Download Presentation

Methods in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Methods in Java

  2. Program Modules in Java • Java programs arewrittenby combining new methods and classes with predefined methodsin the Java Application Programming Interface (Java APIor Java class library) and in various other class libraries • Related classes are grouped into packages so that they can be imported into programs and reused

  3. Predefined Classesof the Java API • methods for performing common mathematical calculations • string manipulations • character manipulations • input/output operations • database operations • networking operations • file processing • error checking • andmore. http://docs.oracle.com/javase/7/docs/api/

  4. staticMethods • Sometimes a method performs a task that does not depend on an object. • Such a method applies to the class in which it’s declared as a whole and is known as a static method or a class method. • To declare a method as static, place the keyword static before the return type in the method’s declaration. • For any class imported into program, call the class’s static methods by specifying the name of the class followed by a dot (.) and the method name ClassName.methodName(arguments)

  5. Math Class Methods as a staticmethod

  6. Math Class Methods as a StaticMethod • Class Math provides a collection of methods that enable you to perform common mathematical calculations. • all Math class methods are static • Each is called by preceding its name with the class name Math and the dot (.) separator • Class Math is part of thejava.langpackage, • it is implicitly imported by the compiler • it’s not necessary to import class Math to use its methods. System.out.println(Math.sqrt(900.0));

  7. static Variables • There are variables for which each object of a class does not need its own separate copy • Suchvariables are declared static • Theyare calledas class variables. • When objects of a class containing static variables are created, all the objects of that class share one copy of those variables. • Together a class’s static variables and instance variables are known as its fields.

  8. A Kind of Variable in Java: Class Variables (Static Fields) A class variableis any field declared with the static modifier; Tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. The keyword final could be added to indicate that the valueof theclassvariablewill never change.

  9. Other Kind of Variable in Java Instance Variables (Non-Static Fields) • Objectsstore their individual states in "non-static fields" • Fieldsdeclared without the static keyword. • Non-static fields are also known as instance variables • Their values are unique to each instance of a class (to each object)

  10. Another Kind of Variable in JavaLocal Variables • A method will often store its temporary state in local variables. • The syntax for declaring a local variable is similar to declaring a field . int count = 0; • There is no special keyword designating a variable as local • determination comes from the locationwhich is between the opening and closing braces of a method. • Local variables are only visible to the methods in which they are declared • they are not accessible from the rest of the class.

  11. Another Kind of Variable in Java : Parameters public static void main(String[] args) The args variable is the parameterto the method. The important thing to remember is that parameters are always classified as "variables" not "fields” This applies to other parameter such as constructors and exception handlers.

  12. Example public class Bicycle { …….. private static intnumberOfBicycles= 0; ………… publicstaticintgetNumberOfBicycles() { returnnumberOfBicycles; } …………. }

  13. ReferringClass Variables Class variables are referenced by the class name itself Bicycle.numberOfBicycles This makes it clear that they are class variables. It is also possibletorefer static fields with an object reference myBike.numberOfBicycles but this is discouraged because it does not make it clear that they are class variables.

  14. StaticMethods • A common use for static methods is to access static fields. • Not all combinations of instance and class variables and methods are allowed: Instance methods can access instance variables and instance methods directly. Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly • they must use an object reference • class methods cannot use the this keyword as there is no instance for this to refer to.

  15. Constants The static modifier, in combination with the final modifier is used to define constants. The final modifier indicates that the value of this field cannot change. static final double PI = 3.141592653589793; Constants defined in this way cannot be reassigned, and it is a compile-time error if theprogram tries to do so.

  16. Why is method main declared static?

  17. Declaring Methods with Multiple Parameters

  18. // MaximumFinder.java // method is declaredwithmaximum with three double parameters.   import java.util.Scanner;public class MaximumFinder   {// obtain three floating-point values and locate the maximum valuepublic static void main(String[] args)      {// create Scanner for input from command window     Scanner input = new Scanner(System.in);  // prompt for and input three floating-point valuesSystem.out.print( "Enter three floating-point values ");    double number1 = input.nextDouble(); // read first doubledouble number2 = input.nextDouble(); // read second double double number3 = input.nextDouble(); // read third double // determine the maximum valuedouble result = maximum(number1, number2, number3);System.out.println("Maximum is: " + result);    // display maximum value    }// returns the maximum of its three double parameters      

  19. public static double maximum(double x, double y, double z)        {                                                                  double maximumValue = x;// determine whether y is greater than maximumValue      if (y > maximumValue)                                       maximumValue = y;                                             // determine whether z is greater than maximumValue         if (z > maximumValue)                                       maximumValue = z;                                         return maximumValue;                                              }        } // end class Enter three floating-point values 9.35 2.115.91Maximum is: 9.35

  20. Keywords public and static • Method maximum’s declaration begins with keyword publicto indicate that the method is “available to the public” • it can be called from methods of other classes. • The keyword static enables the main method to call maximum without qualifying the method name with the class name MaximumFinder • static methods in the same class can call each other directly. • Any other class that uses maximum must fully qualify the method name with the class name.

  21. Method maximum • The maximum method requires three double parameters (x, y and z) to accomplish its task • When maximum is called the parameters x, y and z are initialized with copies of the values of arguments number1, number2 and number3, respectively. • each argument must be consistent with the type of the corresponding parameter • There must be one argument in the method call for each parameter in the method declaration • When program control returns to the point in the program where maximum was called, maximum’s parameters x, y and z no longer exist in memory

  22. Important Methods can return at most one value, but the returned value could be a reference to an object that contains many values. Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.

  23. Implementing Method maximum by Reusing Method Math.max • The entire body of our maximum method could also be implemented with two calls to Math.max, as follows: return Math.max(x, Math.max(y, z)); • The first call to Math.max specifies arguments x and Math.max(y, z). • Before any method can be called, its arguments must be evaluated to determine their values. • If an argument is a method call, the method call must be performed to determine its return value. • Then the result is passed as the second argument to the other call to Math.max, which returns the larger of its two arguments.

  24. Assembling Strings with String Concatenation • Java allows you to assemble String objects into larger strings by using operators + or +=. • This is known as string concatenation. • When both operands of operator + are String objects, operator + creates a new String object in which the characters of the right operand are placed at the end of those in the left operand • the expression "hello " + "there" creates the String "hello there« • the expression "Maximum is: " + result uses operator + with operands of types String and double.

  25. Assembling Strings with String Concatenation • Every primitive value and object in Java can be represented as aString. • When one of the + operator’s operands is a String, the other is converted to a String, then the two are concatenated. System.out.println("Maximum is: " + result); • The double value is converted to its String representation and placed at the end of the String • If there are any trailing zeros in a double value, these will be discarded when the number is converted to a String for example 9.3500 would be represented as 9.35.

More Related