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

JavaProgrammingForBeginners-CourseBook-51-60

The document explains the process of creating and using methods in Java, including method overloading and returning values. It illustrates how to define methods that accept arguments and how to create classes and objects, as well as the importance of the Java compiler and JVM for code execution. Additionally, it covers writing Java code in separate source files and the necessity of a main method for running Java applications.

Uploaded by

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

JavaProgrammingForBeginners-CourseBook-51-60

The document explains the process of creating and using methods in Java, including method overloading and returning values. It illustrates how to define methods that accept arguments and how to create classes and objects, as well as the importance of the Java compiler and JVM for code execution. Additionally, it covers writing Java code in separate source files and the necessity of a main method for running Java applications.

Uploaded by

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

You can call it to print 5 table.

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.

jshell> void sum(int firstNum, int secondNum) {


...> int sum = firstNum + secondNum;
...> System.out.println(sum);
...> }
| created method sum(int, int)
jshell> sum(5, 10)
15
jshell>

A method void sum(int, int, int) that computes the sum of three integers, and prints their output.

jshell> void sum(int firstNum, int secondNum, int thirdNum) {


...> int sum = firstNum + secondNum + thirdNum;
...> System.out.println(sum);
...> }
| created method sum(int,int,int)
jshell> sum(5, 10, 15)
30

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() .

jshell> Math.max(15, 25)


$1 ==> 25
jshell> $1
$1 ==> 25

Math.max() does return a value, which is stored in the JShell variable $1 .


A return mechanism is quite important, as it provides you the flexibility of:
Sharing computed results with other code and methods
Improving the breaking down of a problem, into sub-problems
The next example explains how you can collect a method's return value.
jshell> int max = Math.max(15, 25)
max ==> 25
jshell> max
max ==> 25
jshell>

We are storing the return value in a variable int max .


We could define our own method that returns a value, in a similar manner. In the method sumOfTwoNumbers above,
instead of displaying sum at once, we could return it to the calling-code.

jshell> int sumOfTwoNumbers(int firstNum, int secondNum) {


...> int sum = firstNum + secondNum;
...> return sum;
...> }
| created method sumOfTwoNumbers(int,int)
jshell> sumOfTwoNumbers(1, 10)
$2 => 11

The statement return sum; is called a return statement.


When the code sum = sumOfTwoNumbers(1, 10) is run, sum collects the result returned by sumOfTwoNumbers() .
You could now print sum on the console, store it in another variable, or even invoke a different method by passing it
as an argument!
jshell> sum = sumOfTwoNumbers(1, 10)
sum => 11_
jshell> sum = sumOfTwoNumbers(15, 15)
sum => 30
jshell>

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

jshell> int sumOfThreeNumbers(int firstNum, int secondNum, int thirdNum) {


...> int sum = firstNum + secondNum + thirdNum;
...> return sum;
...> }
| created method sumOfThreeNumbers(int,int, int)
jshell>

Solution-02

jshell> int getThirdAngle(int firstAngle, int secondAngle) {


...> int sumOfTwo = firstAngle + secondAngle;
...> return 180 - sum;
...> }
| created method getThirdAngle(int,int)
jshell>

Step 12: Java Methods, A Review


In this section, we introduced you to the concept of methods in Java.
We understood that methods are routines that perform a unit of computation. They group a set of statements
together into a block, and need to be run by being invoked, through a method call.
We can define methods that accept no arguments, a single argument and multiple arguments.
A method can also be defined to return results of its computation, and this makes it your program more flexible.
Understanding the Java Platform
JShell is amazing to start with the basics of Java programming. It abstracts all complexities behind writing,
compiling and running Java code.
What's happening behind the screens? Let's find out.
Step 01: The Java Platform - An Introduction
A computer only understands binary code, which are sequences of 0 ʼs and 1 ʼs (called bits). All instructions to a
computer should be converted to 0 ʼs and 1 ʼs before execution.
When we wrote our code in JShell, how was it converted to binary code?
We write our programs in a high-level language, such as Java, as it is easier to learn, remember and maintain.
Who converts it to binary code?
Typically, Compiler is a program which understands the syntax of your programming language and converts it into
binary code.
Java designers wanted it to be Platform independent. Compile the code once and run it anywhere.
However, different Operating Systems have different instruction sets - different binary code.
Java provides an interesting solution:
All Java compilers translate source code to an intermediate representation ( bytecode ).
To run Java programs (bytecode), you need a JVM (Java Virtual Machine).
JVM understands bytecode and runs it.
There are different JVM's for different operating systems. Windows JVM converts bytecode into Windows
executable instructions. Linux JVM converts bytecode into Linux executable instructions.
The Java compiler translates Java source code to bytecode, which is stored as a .class file on the computer.
Summary
In this step, we:
Understood the role of the Java compiler in translating source code
Realized the need for an Intermediate Representation (IR) such as bytecode
Understood how the (Compiler + JVM + OS) combination ensure source code portability
Step 02: Creating a Java class
First, let's understand the concept of a class .
Let's consider an example:
A Country is a concept. India, USA and Netherlands are examples or instances of Country.
Similarly, a class is a template. Objects are instances of a class .
We will discuss more about class and object in the section on Object Oriented Programming.
The syntax to create a class, and its objects, is very simple.

jshell> class Country {


...> }
created class Country

Let's create an instance of the class:


jshell> Country india = new Country();
india ==> Country@6e06451e

The syntax is simple - ClassName objectName = new ClassName() .


india is an object of type Country , and is stored in memory at a location indicated by 6e06451e .

Let's create a few more instances of the class:


jshell> Country usa = new Country();
usa ==> Country@6e1567f1
jshell> Country netherlands = new Country();
netherlands ==> Country@5f134e67
jshell>

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:

jshell> class Planet {


...>}
created class Planet
jshell> Planet planet = new Planet();
planet ==> Planet@56ef9176
jshell> Planet earth = new Planet();
earth ==> Planet@1ed4004b
jshell> Planet planet = new Planet();
venus ==> Planet@25bbe1b6

We can also create a class for a different concept, like a Planet .


Planet is now a different template. planet , earth and venus are instances of Planet class.

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

Syntax of revolve() is similar to other methods we've created before.


The class template got updated as a result of adding new method. Earlier instances planet , earth and
venus got reset to null as they are based on the old template

Let's re-instantiate a few objects.


jshell> Planet earth = new Planet();
earth ==> Planet@192b07fd
jshell> Planet planet = new Planet();
venus ==> Planet@64bfbc86
jshell>

How do we call the revolve method?

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

cd to the folder where you have created the file Planet.java


in28minutes$> cd in28Minutes/git/JavaForBeginners/
command-prompt> ls
Planet.java

Check Java version.


command-prompt> java -version
java version "x.0.1"
Java(TM) SE Runtime Environment (build x.0.1+11)
Java HotSpot(TM) 64-bit Server VM (build x.0.1+11, mixed mode)

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_

You can run the class using command java Planet .


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>
Why is there an error? Let's discuss that in the next step.
Summary
In this step, we:
Ventured out of JShell into unexplored territory, to write source code
Learned how to invoke the compiler to compile source files, from the terminal
Step 05: Introducing main() , And Running Bytecode
In the previous step, we compiled Planet.java. In this step, let's run the bytecode generated, which lies inside
Planet.class.
Snippet-01: Running Planet
Console Commands

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

main is its name

args is its formal argument. Here, it's an array of String .

`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) {

}
}

Let's run it now:


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

Why is there no change in result?


After changing your Java source file, you need to compile the code again to create a new class file.
command-prompt> javac Planet.java
command-prompt> ls
Planet.class Planet.java_

Let's try it again.


command-prompt> java Planet
command-prompt>

We got a blank stare from the terminal. Why?


What did we write in the main method? Nothing.
public static void main(String[] args) {

Let's fix it. We need to edit Planet.java once again!


Planet.java

class Planet {
void revolve() {
System.out.println("Revolve");
}
public static void main(String[] args) {
Planet earth = new Planet();
earth.revolve();
}
}

Console Commands

command-prompt> javac Planet.java


command-prompt> ls
Planet.class Planet.java
command-prompt> java Planet
Revolve
command-prompt>

Bingo! We finally got what we wanted to see!


Summary
In this step, we:

You might also like