0% found this document useful (0 votes)
5 views

Java Control Statements, Methods and Classes

The document provides an overview of Java conditional statements, including if, else, else if, and switch statements, along with their syntax and examples. It also covers loops such as while, do/while, for, and for-each loops, explaining their syntax and use cases. Additionally, it discusses arrays, including single and multi-dimensional arrays, and methods in Java, detailing how to create and call them.

Uploaded by

edward kariuki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Control Statements, Methods and Classes

The document provides an overview of Java conditional statements, including if, else, else if, and switch statements, along with their syntax and examples. It also covers loops such as while, do/while, for, and for-each loops, explaining their syntax and use cases. Additionally, it discusses arrays, including single and multi-dimensional arrays, and methods in Java, detailing how to create and call them.

Uploaded by

edward kariuki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Java If ...

Else
java Conditions and If Statements
You already know that Java supports the usual logical conditions from
mathematics:

● Less than: a < b


● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
● Equal to a == b
● Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

● Use if to specify a block of code to be executed, if a specified condition is


true
● Use else to specify a block of code to be executed, if the same condition
is false
● Use else if to specify a new condition to test, if the first condition is
false
● Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax

if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:

Example

if (20 > 18) {


System.out.println("20 is greater than 18");
}

We can also test variables:

Example

int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}

Example explained

In the example above we use two variables, x and y, to test whether x is


greater than y (using the > operator). As x is 20, and y is 18, and we know that
20 is greater than 18, we print to the screen that "x is greater than y".
The else Statement
Use the else statement to specify a block of code to be executed if the
condition is false.

Syntax

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example

int time = 20;


if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen
"Good evening". If the time was less than 18, the program would print "Good
day".
The else if Statement
Use the else if statement to specify a new condition if the first condition is
false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}

Example

int time = 22;


if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first condition is
false. The next condition, in the else if statement, is also false, so we
move on to the else condition since condition1 and condition2 is both false -
and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Java Switch
Java Switch Statements
Instead of writing many if..else statements, you can use the switch
statement.

The switch statement selects one of many code blocks to be executed:

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

● The switch expression is evaluated once.


● The value of the expression is compared with the values of each case.
● If there is a match, the associated block of code is executed.
● The break and default keywords are optional, and will be described
later in this chapter

The example below uses the weekday number to calculate the weekday name:
Example

int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the
rest of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case match:

Example

int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"

Note that if the default statement is used as the last statement in a switch block, it
does not need a break.

Java While Loop

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.
Java While Loop
The while loop loops through a block of code as long as a specified condition is
true:

Syntax

while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:

Example

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

Note: Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.
Syntax

do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example

int i = 0;

do {
System.out.println(i);
i++;
}
while (i < 5);

Do not forget to increase the variable used in the condition, otherwise the loop will
never end!

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example

for (int i = 0; i < 5; i++) {


System.out.println(i);
}

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

Another Example
This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}

For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:

Syntax

for (type variableName : arrayName) {


// code block to be executed
}

The following example outputs all elements in the cars array, using a "for-each"
loop:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (String i : cars) {
System.out.println(i);
}

Note: Don't worry if you don't understand the example above. You will learn more about
Arrays in the Java Arrays chapter.

Java Break and Continue

Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:

Example

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
System.out.println(i);
}

Java Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example

for (int i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
System.out.println(i);
}

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values
to it, you can place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);
// Outputs Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element


To change the value of a specific element, refer to the index number:

Example

cars[0] = "Opel";

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo

Array Length
To find out how many elements an array has, use the length property:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars.length);
// Outputs 4

Loop Through an Array


You can loop through the array elements with the for loop, and use the length
property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Java Multi-Dimensional Arrays

Multidimensional Arrays
A multidimensional array is an array of arrays.

Multidimensional arrays are useful when you want to store data as a tabular
form, like a table with rows and columns.

To create a two-dimensional array, add each array within its own set of curly
braces:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

Access Elements
To access the elements of the myNumbers array, specify two indexes: one for
the array, and one for the element inside that array. This example accesses the
third element (2) in the second array (1) of myNumbers:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

System.out.println(myNumbers[1][2]); // Outputs 7
Remember that: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Change Element Values


You can also change the value of an element:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };


myNumbers[1][2] = 9;

System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7

Loop Through a Multi-Dimensional Array


We can also use a for loop inside another for loop to get the elements of a
two-dimensional array (we still have to point to the two indexes):

Example

public class Main {


public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);

}
}
}
}

Java Methods
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as
functions.

Why use methods? To reuse code: define the code once, and use it many
times.

Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as System.out.println(), but you can also create your own methods to
perform certain actions:

Example

Create a method inside Main:

public class Main {


static void myMethod() {
// code to be executed
}
}

Example Explained
● myMethod() is the name of the method
● static means that the method belongs to the Main class and not an
object of the Main class. You will learn more about objects and how to
access methods through objects later in this tutorial.
● void means that this method does not have a return value. You will learn
more about return values later in this chapter

Call a Method
To call a method in Java, write the method's name followed by two parentheses
() and a semicolon;

In the following example, myMethod() is used to print a text (the action), when
it is called:

Example

Inside main, call the myMethod() method:

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "I just got executed!"

A method can also be called multiple times:

Example

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

// I just got executed!


// I just got executed!
// I just got executed!

In the next chapter, Method Parameters, you will learn how to pass data (parameters)
into a method.

Java Method Parameters

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.

Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

Example

public class Main {


static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters
You can have as many parameters as you like:

Example

public class Main {


static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}

public static void main(String[] args) {


myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}

// Liam is 5
// Jenny is 8

// Anja is 31
Note that when you are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be
passed in the same order.

Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use the
return keyword inside the method:

Example

public class Main {


static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

Example

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to read
and maintain):

Example

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


int z = myMethod(5, 3);
System.out.println(z);
}
}
// Outputs 8 (5 + 3)

A Method with If...Else


It is common to use if...else statements inside methods:

Example

public class Main {

// Create a checkAge() method with an integer variable called age


static void checkAge(int age) {

// If age is less than 18, print "access denied"


if (age < 18) {
System.out.println("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access


granted"
} else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(20); // Call the checkAge method and pass along an age
of 20
}
}

// Outputs "Access granted - You are old enough!"

Java Method Overloading

Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:

Example

int myMethod(int x)
float myMethod(float x)

double myMethod(double x, double y)

Consider the following example, which has two methods that add numbers of
different type:

Example
static int plusMethodInt(int x, int y) {
return x + y;
}

static double plusMethodDouble(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);

Instead of defining two methods that should do the same thing, it is better to
overload one.

In the example below, we overload the plusMethod method to work for both
int and double:

Example

static int plusMethod(int x, int y) {


return x + y;
}

static double plusMethod(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);

}
Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.

Java Scope

Java Scope
In Java, variables are only accessible inside the region they are created. This is
called scope.

Method Scope
Variables declared directly inside a method are available anywhere in the
method following the line of code in which they were declared:

Example

public class Main {


public static void main(String[] args) {

// Code here CANNOT use x

int x = 100;

// Code here can use x


System.out.println(x);
}

Block Scope
A block of code refers to all of the code between curly braces {}.

Variables declared inside blocks of code are only accessible by the code between
the curly braces, which follows the line in which the variable was declared:

Example

public class Main {


public static void main(String[] args) {

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x


System.out.println(x);

} // The block ends here

// Code here CANNOT use x

A block of code may exist on its own or it can belong to an if, while or for statement.
In the case of for statements, variables declared in the statement itself are also
available inside the block's scope.
java Recursion

Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:

Example

Use recursion to add all of the numbers up to 10.

public class Main {


public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}

Example Explained
When the sum() function is called, it adds parameter k to the sum of all
numbers smaller than k and returns the result. When k becomes 0, the function
just returns 0. When running, the program follows these steps:

10 + sum(9)

10 + ( 9 + sum(8) )

10 + ( 9 + ( 8 + sum(7) ) )

...

10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)

10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and
returns the result.
Java Classes
Java OOP

Java - What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.

Object-oriented programming has several advantages over procedural


programming:

● OOP is faster and easier to execute


● OOP provides a clear structure for the programs
● OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
● OOP makes it possible to create full reusable applications with less code
and shorter development time

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
Java - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.Look at the following illustration to see the difference between
class and objects:

Another example

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and
methods from the class.
Java Classes and Objects
Java Classes/Objects
Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car has
attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

Main.java

Create a class named "Main" with a variable x:

public class Main {

int x = 5;

Remember from the Java Syntax chapter that a class should always start with an
uppercase first letter, and that the name of the java file should match the class name.
Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object
name, and use the keyword new:

Example

Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Multiple Objects
You can create multiple objects of one class:

Example

Create two objects of Main:


public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

Using Multiple Classes


You can also create an object of a class and access it in another class. This is
often used for better organization of classes (one class has all the attributes and
methods, while the other class holds the main() method (code to be
executed)).

Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:

● Main.java
● Second.java

Main.java

public class Main {

int x = 5;

}
Second.java

class Second {

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

When both files have been compiled:

C:\Users\Your Name>javac Main.java

C:\Users\Your Name>javac Second.java

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

5
Java Class Attributes

Java Class Attributes


In the previous chapter, we used the term "variable" for x in the example (as
shown below). It is actually an attribute of the class. Or you could say that class
attributes are variables within a class:

Example

Create a class called "Main" with two attributes: x and y:

public class Main {

int x = 5;

int y = 3;

Another term for class attributes is fields.

Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):

The following example will create an object of the Main class, with the name
myObj. We use the x attribute on the object to print its value:

Example

Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Modify Attributes
You can also modify attribute values:

Example

Set the value of x to 40:

public class Main {

int x;
public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

Or override existing values:

Example

Change the value of x to 25:

public class Main {

int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // x is now 25

System.out.println(myObj.x);

If you don't want the ability to override existing values, declare the attribute as
final:

Example

public class Main {


final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error: cannot assign a value to a


final variable

System.out.println(myObj.x);

The final keyword is useful when you want a variable to always store the same value,
like PI (3.14159...).

The final keyword is called a "modifier". You will learn more about these in the Java
Modifiers Chapter.

Multiple Objects
If you create multiple objects of one class, you can change the attribute values
in one object, without affecting the attribute values in the other:

Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

myObj2.x = 25;

System.out.println(myObj1.x); // Outputs 5

System.out.println(myObj2.x); // Outputs 25

Multiple Attributes
You can specify as many attributes as you want:

Example

public class Main {

String fname = "John";

String lname = "Doe";

int age = 24;


public static void main(String[] args) {

Main myObj = new Main();

System.out.println("Name: " + myObj.fname + " " + myObj.lname);

System.out.println("Age: " + myObj.age);

Java Class Methods


Java Class Methods
You learned from the Java Methods chapter that methods are declared within a
class, and that they are used to perform certain actions:

Example

Create a method named myMethod() in Main:

public class Main {

static void myMethod() {

System.out.println("Hello World!");

}
myMethod() prints a text (the action), when it is called. To call a method, write
the method's name followed by two parentheses () and a semicolon;

Example

Inside main, call myMethod():

public class Main {

static void myMethod() {

System.out.println("Hello World!");

public static void main(String[] args) {

myMethod();

// Outputs "Hello World!"

Static vs. Public


You will often see Java programs that have either static or public attributes
and methods.

In the example above, we created a static method, which means that it can
be accessed without creating an object of the class, unlike public, which can
only be accessed by objects:

Example
An example to demonstrate the differences between static and public methods:

public class Main {

// Static method

static void myStaticMethod() {

System.out.println("Static methods can be called without creating


objects");

// Public method

public void myPublicMethod() {

System.out.println("Public methods must be called by creating


objects");

// Main method

public static void main(String[] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main

myObj.myPublicMethod(); // Call the public method on the object

}
Note: You will learn more about these keywords (called modifiers) in the Java Modifiers
chapter.

Access Methods With an Object

Example

Create a Car object named myCar. Call the fullThrottle() and speed() methods
on the myCar object, and run the program:

// Create a Main class

public class Main {

// Create a fullThrottle() method

public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

// Create a speed() method and add a parameter

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);

}
// Inside main, call the methods on the myCar object

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

// The car is going as fast as it can!

// Max speed is: 200

Example explained
1) We created a custom Main class with the class keyword.

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some
text, when they are called.

4) The speed() method accepts an int parameter called maxSpeed - we will


use this in 8).

5) In order to use the Main class and its methods, we need to create an object
of the Main Class.

6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar.

8) Then, we call the fullThrottle() and speed() methods on the myCar


object, and run the program using the name of the object (myCar), followed by
a dot (.), followed by the name of the method (fullThrottle(); and
speed(200);). Notice that we add an int parameter of 200 inside the speed()
method.

Remember that..

The dot (.) is used to access the object's attributes and methods.

To call a method in Java, write the method name followed by a set of parentheses (),
followed by a semicolon (;).

A class must have a matching filename (Main and Main.java).

Using Multiple Classes


Like we specified in the Classes chapter, it is a good practice to create an object
of a class and access it in another class.

Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:

● Main.java
● Second.java

Main.java

public class Main {

public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

public void speed(int maxSpeed) {


System.out.println("Max speed is: " + maxSpeed);

Second.java

class Second {

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

When both files have been compiled:

C:\Users\Your Name>javac Main.java

C:\Users\Your Name>javac Second.java

Run the Second.java file:

C:\Users\Your Name>java Second


And the output will be:

The car is going as fast as it can!

Max speed is: 200

Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:

Note that the constructor name must match the class name, and it cannot have
a return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.

You might also like