Skip to content

Methods

Kunal Purohit edited this page Jan 3, 2018 · 12 revisions

Overview

New Concepts

public static void main(String[] args)

Let's break down every part of that statement

This statement basically means that you have a method called main that:

  1. is accessible anywhere and by anyone (public)
  2. you can call main without having an object present (static)
  3. has no return value (void)
  4. can contain String based arguments (String[] args)

These are the basic parts of a method.

public vs private

Methods can either be public, private, or in some cases protected. We'll go over protected when we begin talking about classes/objects later on.

  • public - can be accessed directly inside or outside a class
  • private - can only be accessed within the class

NEED TO ADD EXAMPLES

static

Static is an optional keyword that can be applied so that you could use a method without having to declare an object of the class containing the method.

NEED TO ADD EXAMPLES - Like a class that contains a static method to convert temperature from C to F that can be useful without needing to declare the class

void, int, double, String

A method must also have a return type listed. All the methods you've seen so far have been of the type void meaning that they don't return anything. If your method returns something though you must specify the type returned and also use the return keyword at the end of the method.

It should also be noted that a method can only have one return type.

> public class Example {
>    public static int add(int a, int b) {
>       int c = a + b;
>       return c;
>    }
>    
>    public static void main(String[] args) {
>       System.out.println(Example.add(5, 6);
>    }

11

In the example above, we have a method takes two integer numbers and returns their integer sum.

return Statement

Arguments and Parameters

Local vs Global Scope

Activity

Guess the Number Game

Summary

Practice Problems

Clone this wiki locally