JavaProgrammingForBeginners-CourseBook-41-50
JavaProgrammingForBeginners-CourseBook-41-50
256
324
400
Solution 7
It may surprise you that each one of initialization, condition, updation and statements block is optional. They can all
be left out individually, in combination, or all altogether!! Let's examine a few interesting cases in code.
. Empty initialization, Empty Statement
Increments the control variable in quick succession until the condition evaluates to false.
jshell> int i = 1
i ==> 1
jshell> for (; i<=10; i++);
jshell> i
i ==> 11
jshell>
jshell> int j
i ==> 11
jshell> for (i=1, j=2; i<=10; i++, j++);
jshell> i
i ==> 11
jshell> j
j ==> 12
jshell>
. Infinite Loop
An infinite loop is one where the condition is left empty. An empty condition always evaluates to true . Since a
for loop only terminates when the condition becomes false , such a loop this never terminates.
^C
jshell>
Summary
In this step, we saw that all components of a for loop are optional:
initialization
condition
updation
statement block
Step 31: A Review Of Basic Concepts
Before we go further, let's quickly get a Big Picture of what we are doing here!
A computer is a machine that does a job for you and me. It is can be used to run tasks that we find complicated,
time-consuming, or even boring! For instance, a laptop can play music from a CD, videos from the web, or fire a
print job.
We have mobile phones around us, which are mini versions of computers. Then there are others, ranging from
blood-sugar monitors to weather-forecast systems. Computers surround us, wherever we go!
Any computer is made up of two basic layers:
The hardware: Consists of all the electronic and mechanical parts of the computer, including the electronic
circuits.
The software: Describes the instructions fed into the computer, which are stored and run on its hardware.
If the human body were a computer,
Its hardware would consist of the various organs (such as limbs, blood and heart)
Its software would be the signals from the nervous system, which drive these organs.
Computer programming involves writing software instructions to run tasks on a computer. The user who gives
these instructions is called the programmer. Often, computer programming involves solving challenging, and very
interesting problems.
In the previous steps, we introduced you to the basic Java language concepts and constructs.
We solved a programming challenge, the PMT-Challenge using basic Java constructs.
We used JShell REPL to learn the following concepts, Step by-step:
Expressions, Operators and Statements
Variables and Formatted Output
Conditionals and Loops
At each step, we applied fresh knowledge to enhance our solution to the PMT-Challenge
Hope you liked the journey thus far. Next sections delve deeper into Java features, using the same Step by-step
approach. We will catch up again soon, hopefully!
Understanding Methods
Feeling good about where you are right now? You just created an elegant, yet powerful solution to the PMT-
Challenge, using:
Operators, variables and expressions
Built-in formatted output
Conditionals for control-flow, and
Iteration through loops
And guess what we ended up with? A good-looking display of a Multiplication Table! There's a good chance people
in your circles want to see it, use it and maybe share it among their friends.
However, some might be unhappy that it works only for 5 , and not for 8 and 7 . Maybe it would, but then they
would need to type in those lines of code again. This might disappoint them, and your new found popularity would
slide downhill.
Surely a more elegant solution exists, a pattern waiting to unravel itself.
Exist it does, and the mechanism to use it lies with Java methods. A method is a feature that allows you to group
together a set of statements, and give it a name. This name represents the functionality of that set, which can be
re-used when necessary.
A method is essentially a routine that performs a certain task, and can do it any number of times it is asked to. It
may also return a result for the task it performs. The syntax for a method definition is along these lines:
ReturnType methodName () {
method-body
}
Where
methodName is the name of the routine
method-body is the set of statements
Summary
In this step, we:
Examined the need for labeling code, and its reuse
Learned that a Java method fits the bill
Saw how a method definition looks like, conceptually
Step 01 : Defining A Simple Method
We will start off, by writing a simple method that prints " Hello World " twice on your screen.
jshell> sayHelloWorldTwice
| Error:
| cannot find symbol
| symbol: variable sayHelloWorldTwice
| sayHelloWorldTwice
| ^----------------^
jshell> sayHelloWorldTwice()
Hello World
Hello World
Solutions to PE-01
Solution-1
jshell> sayHelloWorldThrice()
Hello World
Hello World
Hello World
Solution-2
jshell> sayFourThings()
I've created my first variable
I've created my first loop
I've created my first method
I'm excited to learn Java
The /methods command lists out the methods defined in the current session.
jshell> /methods
| void sayHelloWorldTwice()
jshell>
The /edit command allows you to modify the method definition, in a separate editor window.
The /save method takes a file name as a parameter. When run, it saves the session method definitions to a file.
in28minutes$>
Summary
In this step, we explored a few JShell tips that make life easier for you while defining methods
Step 04: Methods with Arguments
We wrote the method sayHelloWorldTwice to say Hello World twice. In the programming exercise, we wanted to
print Hello World thrice and we wrote a new method sayHelloWorldThrice .
Imagine you're in the Java classroom, where your teacher wants to test your Java skills by saying: "I want you to
print Hello World an arbitrary number of times".
Now, that probably would test your patience as well!
How to write a method to print Hello World an arbitrary number of times?
The thing to note is the word "arbitrary", which means the method body should have no clue! This number has to
come from outside the method, which can only happen with a method call.
External input to a method is given as a method argument, or parameter.
To support arguments during a call, the concept of a method needs to be tweaked to:
method-body
within the parentheses. argName represents the argument, and ArgType is its type. The next example should clear
the air for you.
Snippet-01: Method with an argument: Definition
Let's look at a method definition using an argument numOfTimes .
Method call must include the same number and types of arguments, that it is defined to have. sayHelloWorld() is
an error because sayHelloWorld is defined to accept one parameter. sayHelloWorld(1) works.
However, the method does not do anything. Isn't it sad?
Snippet-02 : Passing and accessing a parameter
The next example will show you how method body code can access arguments passed during a call. Not only that,
the argument values can be used during computations.
jshell> sayHelloWorld(1)
1
jshell> sayHelloWorld(2)
2
jshell> sayHelloWorld(4)
4
jshell> /edit sayHelloWorld
| modified method sayHelloWorld(int)
jshell>
In the above example, we printed numOfTimes a total of numOfTimes for each method call.
We print 2 two times and 4 four times.
jshell> sayHelloWorld(2)
2
2
jshell> sayHelloWorld(4)
4
4
4
4
jshell>
You can now proudly demonstrate this code to your Java instructor. Your program can print "Hello World" an
arbitrary number of times!
What started off giving you a headache, will probably keep you in her good books, for the rest of your course!
Armed with this confidence booster, let's now see how Java treats mistakes you may make. .
Snippet-5 : Parameter type mismatch
Java is a strongly typed language, with strict rules laid out for type compatibility. We saw that with variables, and
how they play out with expressions and assignments. The same type compatibility rules are enforced by the
compiler, when it needs to match the arguments from method calls with method definition.
jshell> sayHelloWorld("value")
| Error:
| incompatible types: java.lang.String cannot be converted to int
| sayHelloWorld("value")
| ^-----^
jshell> sayHelloWorld(4.5)
| Error:
| incompatible types: possibly lossy conversion from double to int
| sayHelloWorld(4.5)
| ^-^
jshell>
Summary
In this step, we:
Understood why Java supports method arguments, and how we may use them
Observed how method arguments lead to convenience and reuse
Decided to abide by type compatibility for actual arguments
Step 05: Exercise Set PE-02 (With Solutions)
Exercises
. Write a method printNumbers(int n) that prints all successive integers from 1 to n .
. Write a method printSquaresOfNumbers(int n) that prints the squares of all successive integers from 1 to
n.
Solution-01
jshell> void printNumbers(int n) {
...> for(int i=0; i< n; i++) {
...> System.out.println(i);
...> }
...> }
| created method printNumbers(int)
jshell>
Solution 2
void printMultiplicationTable() {
for (int i=1; i<=10; i++) {
System.out.printf("%d * %d = %d", 5, i, 5*i).println();
}
}