Java methods tutorial: Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will learn about Java methods. Methods are known as functions in C and C++ programming languages. A method has a name and return type. Main method is a must in a Java program as execution begins from it.
Syntax of methods
"Access specifier" "Keyword(s)" "return type" methodName(List of arguments) {
// Body of method
}
// Body of method
}
Access specifier can be public or private which decides whether other classes can call a method.
Kewords are used for some special methods such as static or synchronized.
Return type indicate return value which method returns.
Method name is a valid Java identifier name.
Kewords are used for some special methods such as static or synchronized.
Return type indicate return value which method returns.
Method name is a valid Java identifier name.
Access specifier, Keyword and arguments are optional.
Examples of methods declaration:
public static void main(String[] args);
void myMethod();
private int maximum();
public synchronized int search(java.lang.Object);
public static void main(String[] args);
void myMethod();
private int maximum();
public synchronized int search(java.lang.Object);
Java Method example program
Output of program:
Download Methods program class file.
Java methods list
Java has a built in library of many useful classes and there are thousands of methods which can be used in your programs. Just call a method and get your work done :) . You can find list of methods in a class by typing following command on command prompt:
javap package.classname
For example
javap java.lang.String // list all methods and constants of String class.
javap java.math.BigInteger // list constants and methods of BigInteger class in java.math package
javap java.lang.String // list all methods and constants of String class.
javap java.math.BigInteger // list constants and methods of BigInteger class in java.math package
Java String methods
String class contains methods which are useful for performing operations on String(s). Below program illustrate how to use inbuilt methods of String class.
Java string class program
Output of program:
No comments:
Post a Comment