JavaProgrammingForBeginners-CourseBook-51-60
JavaProgrammingForBeginners-CourseBook-51-60
jshell> printMultiplicationTable()
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
jshell>
Summary
In this step, we:
Revisited the PMT-Challenge solution we had earlier
Enclosed its logic within a method definition, printMultiplicationTable()
Haven't fully explored its power yet!
Step 08: Methods With Arguments, And Overloading
The real power of a definition such as printMultiplicationTable() is when we arm it with arguments. Not verbal
arguments, but "value" ones. That's right!
We will modify printMultiplicationTable() to have it accept a parameter, which would make it more flexible.
void printMultiplicationTable(int number) {
for (int i=1; i<=10; i++) {
System.out.printf("%d * %d = %d", number, i, number*i).println();
}
}
We can now print the multiplication table of any number, by calling the method
printMultiplicationTable(number) .
jshell> printMultiplicationTable(6)
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60
jshell>
Nothing new to explain here. We have only combined stuff you have been learning so far, most recently adding the
flavor of methods to the existing code.
Soak in the power, simplicity and elegance of this program, folks!
Overloaded Methods
It turns out we can call both versions of the method, printMultiplicationTable() and
printMultiplicationTable(5) :
jshell> printMultiplicationTable()
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
jshell>
and
jshell> printMultiplicationTable(5)
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
jshell>
You can have multiple methods with same name but different number of parameters. This is called method
overloading.
Summary
In this step, we:
Enhanced the logic of printMultiplicationTable() by passing arguments
Added flexibility to the PMT-Challenge solution
Were introduced to the concept of method overloading
Step 09: Methods With Multiple Arguments
It is possible, and pretty useful, to define methods that accept more than one argument.
We have already seen how to call two in-built Java methods, Math.max and Math.min , which accept 2 arguments
each.
Time now to enrich our understanding, by writing one such method ourselves as well.
A method void sum(int, int) that computes the sum of two integers, and prints their output.
A method void sum(int, int, int) that computes the sum of three integers, and prints their output.
There are overloaded methods. They have same name sum and have different number of arguments.
Summary
In this step, we:
Used our understanding of method overloading to define our own methods
Step 10: Returning From A Method
A method can also be coded to return the result of its computation. Such a result is called a return value.
A lot of built-in Java methods have return values, the most notable we have seen being Math.min() and
Math.max() .
Summary
In this step, we:
Understood the need for a return mechanism with methods
Explored the syntax for a return statement
Wrote our own method sumOfTwoNumbers() with a return value, and saw how it became more flexible
Step 11: Exercise-Set PE-04 (With Solutions)
Let's now try a few exercises on methods that return values.
Exercises
. Write a method that returns the sum of three integers.
. Write a method that takes as input two integers representing two angles of a triangle, and computes the third
angle. Hint: The sum of the three angles of a triangle is 180 degrees.
Solution-01
Solution-02
india , usa and netherlands are all different objects of type Country .
We actually left the contents of the class Country bare.
A class does often include both data (member variables) and method definitions. More on this at a relevant time.
Let's consider another example:
Summary
In this step, we:
Saw how class creation actually creates a new type
Understood how to create instances of classes - objects
Step 03: Adding A Method To A class
A method defined within a class , denotes an action than can be performed on objects of that class .
Let's define a method inside Planet - to revolve() !
jshell> class Planet {
...> void revolve() {
...> System.out.println("Revolve");
...> }
...> }
replaced class Planet
update replaced variable planet, reset to null
update replaced variable earth, reset to null
update replaced variable venus, reset to null
jshell> Planet.revolve();
| Error:
| non-static method revolve() cannot be referenced from a static context
| Planet.revolve();
|^-----------------^
jshell> earth.revolve();
Revolve
jshell> venus.revolve();
Revolve
jshell>
Our attempt to perform revolve() did not work with the syntax Planet.revolve() as it is not a static method
(more on that in a later section).
Invoking revolve() through syntax such as earth.revolve() succeeds, because earth is an object of type
Planet .
Summary
In this step, we:
Learned how to add a method definition to an existing class
Discovered how to invoke it, on objects of the class
Step 04: Writing and Running Java Code in separate Source Files
So far, we have enjoyed creating classes and defining methods within them, all with our friendly neighborhood
JShell .
JShell kind of spoiled us kids, by relaxing some Java syntax rules, invoking the compiler on our behalf, and also
running the code like room service.
The time has come for us frog princes to outgrow the proverbial well. Yes, you're right! Time to start writing code in
a proper code editor, and smell the greener grass on that side.
Let's start with creating a new source code file - 'Planet.java'. Choose any folder on your hard-disk and create the
file shown below:
Planet.java
class Planet {
void revolve() {
System.out.println("Revolve");
}
}
You can get the code that we wrote earlier in JShell for Planet by running the command /list Planet , and
copying the code.
You can use any text editor of your choice, for now.
The source file name must match the class name it contains. Here, we must name the file Planet.java .
The next course of action would be to compile this code (Stage 2). For that, exit out of JShell , and run back to
your system terminal or command prompt. Now, see what plays out!
jshell> /exit
| Goodbye
You can compile java code using javac Planet.java . You can see that a new file is created Planet.class . This
contains your bytecode .
command-prompt> javac Planet.java
command-prompt> ls
Planet.class Planet.java_
command-prompt> ls
Planet.class Planet.java
command-prompt> java Planet
Error: Main method not found inside class Planet, please define the main method as
public static void main(String[] args)
or a JavaFX application class must extend javax.application.Application
command-prompt>
The code may have compiled without any errors, but what's the use if we cannot run the program to see what stuff
it's got!
The main() method is essential to run code defined within any class .
The definition of main() needs to have this exact synatx:
public static void main(String[] args) { /* <Some Code Goes In Here> */ }
A few details:
void is its return type
`public and static``` are reserved Java keywords. More on these later sections.
Let's add one such definition within the Planet code. Open up your text editor and add the main method as
shown below.
Planet.java
class Planet {
void revolve() {
System.out.println("Revolve");
}
public static void main(String[] args) {
}
}
class Planet {
void revolve() {
System.out.println("Revolve");
}
public static void main(String[] args) {
Planet earth = new Planet();
earth.revolve();
}
}
Console Commands