Methods in Java

From Knowledge Kitchen
Jump to navigation Jump to search


Methods are the fancy object-oriented term for functions.

Simple methods example

The following program illustrates the concept of the method "call stack". See the flow diagram below for a pictorial explanation.

Code

 package edu.nyu.cs.fb1258;
 
 public class SimpleMethodExample {
 
 	static int x = 0; //global variable
 	
 	public static void doSomething3() {
 		System.out.println("Running  doSomething3");		
 		x++;
 		System.out.println("x is " + x);
 		System.out.println("Exiting  doSomething3");
 	}
 	
 	public static void doSomething2() {
 		System.out.println("Running  doSomething2");		
 		x++;
 		System.out.println("x is " + x);
 		doSomething3();
 		System.out.println("Exiting  doSomething2");
 	}
 	
 	public static void doSomething1() {
 		System.out.println("Running  doSomething1");
 		int x = 10; //create a local variable of  the same name
 		x++; //changing this value does not  affect the global x value
 		System.out.println("x is " + x);
 		doSomething2();
 		System.out.println("Exiting  doSomething1");
 	}
 	
 	public static void main(String[] args) {
 		System.out.println("Running main...");
 		System.out.println("x is " + x);
 		doSomething1(); //method call
 		System.out.println("Exiting main");
 	}
 
 }

Flow diagram

Programming method call stack.png


Methods with parameters

Exhibition of creating methods with parameters. Calling the method with arguments populates the parameters.

 package edu.nyu.cs.fb1258;
 
 public class MethodsWithParameters {
 	
 	public static void doSomething2(String foo,  int bar) {
 		System.out.println("This is a method  with two parameters with values " + foo  + " and " + bar);	
 	}
 
 	public static void doSomething2(String foo) {
 		System.out.println("This is a method  with one parameter with value " + foo); 	
 	}
 	
 	public static void doSomething1() {
 		System.out.println("This is a method  with no parameters");	
 	}
 	
 	public static void main(String[] args) {
 		
 		doSomething1(); //method call with no  arguments
 		doSomething2("hello"); //method call  with 1 argument
 		doSomething2("hello", 15); //method call  with 2 arguments of different types
 
 	}
 
 }


Overloaded methods example

 package edu.nyu.cs.fb1258;
 
 import java.util.Random;
 
 public class OverloadedMethodsExample {
 
 	public String openTextFile() {
 		return "foo bar";
 	}
 	
 	public static int luckyNumber() {
 		return 10;
 	}
 	
 	public static int luckyNumber(long mySeed) {
 		Random foo = new Random();
 		foo.setSeed(mySeed);
 		return foo.nextInt();
 	}
 
 	public static void main(String[] args) {
 		long seed = 666;
 		int x = luckyNumber(seed);
 		System.out.println(x);
 	}
 
 }


String parsing example

This example shows how to count the occurrences of arbitrary words within a text. Notice how the while loop has been set up with a boolean condition that only iterates as long as the selected word has been found in the text. Also note the use of a return value in the method.

package edu.nyu.cs.fb1258.string_examples;

/**
 * Counts occurrences of a String within another String
 * @author Foo Barstein
 * @version 2
 *
 */
public class OccurrenceCounter {
	
	/**
	 * Determines how many times a particular needle occurs within a given haystack.
	 * @param needle a String to search for
	 * @param haystack a String within which to search for the needle
	 * @return the number of occurrences of the needle within the haystack
	 */
	public static int numberOfOccurrences(String  needle, String haystack) {
		// start out having found no occurrences of the needle within the haystack
		int occurrences = 0;
		
		//start searching for the need starting from the character at position 0 in the haystack
		int position = haystack.indexOf(needle,  0);  // indexOf() returns -1 if the needle is not found within the haystack
		
		//keep looking for another occurrence as long as we have found one previously
		while (position >= 0) {
			occurrences++; // if indexOf() did not return -1, we have a new occurrence

			// output where we found it
			System.out.println("Found the word  at position " + position);
			
			// find the next occurrence of the needle by searching again within the haystack starting from one character later in the String from where we previously found it
			position = haystack.indexOf(needle, position + 1);
		}
		
		// return the counter of occurrences
		return occurrences;
	}
	
	public static void main(String[] args) {
	    //corporate jargon text generated by bullshitipsum.com
		String myText = "Synergies platforms  visualize e-business cross-media platforms  addelivery communities synergies, e-commerce  infrastructures, tagclouds. Turn-key web- readiness folksonomies enable out-of-the-box  efficient relationships, ubiquitous,  bandwidth e-commerce A-list. Redefine  mindshare dynamic beta-test embrace,  platforms embedded value models reinvent  synergize. Architect leverage redefine  aggregate engage social e-commerce  relationships semantic, grow integrated  reinvent semantic citizen-media--productize  content efficient. Vortals productize,  reintermediate, blogospheres A-list e- enable; niches, rss-capable aggregate  virtual Cluetrain models efficient  envisioneer niches. Strategic utilize niches  action-items matrix, 24/7 transition deliver  global interfaces Cluetrain whiteboard  sticky! Cultivate authentic, A-list  integrate brand cultivate niches, Cluetrain  engineer e-business technologies, engineer  podcasting communities systems, syndicate  markets innovative schemas user-contributed,  enhance. Whiteboard embrace dynamic,  ubiquitous enhance solutions mesh  blogospheres, widgets. Initiatives  folksonomies engage robust portals, A-list  strategic extensible platforms action-items  web-readiness leading-edge; eyeballs  convergence synergies e-business tag  initiatives web services?";

		// determine number of occurrences of the word "platform" within this text
		String myWord = "platform";
		int number =  numberOfOccurrences(myWord, myText);

		// output the number of occurrences
		System.out.println("The word " + myWord + " is used " + number + " times.");
	}

}

Using text files as input

 /**
  * Program shows how to use a text file as input.
  * @author Foo Barstein
  * @version 1.0
  */
 
 package edu.nyu.cs.fb1258;
 
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;
 
 public class OpenFileFromWithinEclipse {
 
 	public static void main(String[] args) throws FileNotFoundException {
 		//create a scanner with the file as input
 		 Scanner in = new Scanner(new File("src/data.txt"));
 		 //check to see if there's a line available in the file
 		 while(in.hasNextLine()){
 			 //get the next line
 			 String line = in.nextLine();
 			 //print it out
 			 System.out.println(line);
 		 }
 	} //main
 } //class