What are methods?

Intermediate Java

Jim White

Java Developer

What you'll learn

  • Methods as reusable blocks of code
    • Custom methods
    • Parameters
  • Control flow
    • if-else statements
    • switch statements
    • Loops
      • for loops
      • while loops
  • Workflow

Icon with a light bulb and a cog wheel

Intermediate Java

What is a method?

  • Block of code performing a specific task
  • Allows reusing of code

Coffee machine with three cups of coffee

Intermediate Java

Methods we've already seen

  • Built-in types have their own methods

For example, String:

  • .length()
  • .toLowerCase() , ...
  • and more methods to come!
Intermediate Java

.contains()

  • Check if String contains a specific substring
  • Returns true or false
"Java".contains("av"); // Returns true
Intermediate Java

.charAt()

  • Returns character at specified place
"Java".charAt(1); // Returns 'a'

Remember, Java starts counting at 0!

Intermediate Java

.substring()

  • Returns part of String, starting at start and stopping before end:

String.substring(start, end)

"Java".substring(1,3); // Return "av"
Intermediate Java

.equals()

  • Compares values of Strings
  • Returns true if values are the same
String word = "Java";
word.equals("Java"); // Returns true

Reminder: == can give unexpected results with Strings

Intermediate Java

Summary

word = "Java";

// .contains()
"Java".contains("v"); // Returns true
word.contains("w"); // Returns false

// .charAt()
"Java".charAt(0); // Returns 'J'
word.charAt(1); // Returns 'a'

// .substring()
"Java".substring(1,3); // Returns "av"
word.substring(0,1); // Returns "J"

// .equals()
"Java".equals(word); // Returns true

// The following may 
// or may not return true
boolean output = "Java" == word; 
Intermediate Java

Let's practice!

Intermediate Java

Preparing Video For Download...