Tuesday, September 1, 2015

Java methods

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
}
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.
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);

Java Method example program


class Methods { 
// Constructor method
Methods() { 
System.out.println("Constructor method is called when an object of it's class is created");
} 
// Main method where program execution begins
public static void main(String[] args) { 
staticMethod(); 
Methods object = new Methods(); 
object.nonStaticMethod(); 
}  
// Static method  
static void staticMethod() { 
System.out.println("Static method can be called without creating object"); 
}  
// Non static method  
void nonStaticMethod() { 
System.out.println("Non static method must be called by creating an object"); 
} 
}

Output of program:



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

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


class StringMethods { 
public static void main(String args[]) { 
int n; 
String s = "Java programming", t = "", u = "";   
System.out.println(s);   
// Find length of string   
n = s.length(); 
System.out.println("Number of characters = " + n);   
// Replace characters in string   
t = s.replace("Java", "C++"); 
System.out.println(s); 
System.out.println(t);   
// Concatenating string with another string   
u = s.concat(" is fun"); 
System.out.println(s); 
System.out.println(u); 
} 
}
Output of program:

0 Comments:

Post a Comment