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

JavaProgrammingForBeginners-CourseBook-41-50

The document provides an overview of Java programming concepts, focusing on the for loop structure and the definition and usage of methods. It explains how all components of a for loop are optional, demonstrates method creation and invocation, and emphasizes the importance of method arguments for flexibility and reusability. Additionally, it includes exercises to reinforce understanding of these concepts.

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-41-50

The document provides an overview of Java programming concepts, focusing on the for loop structure and the definition and usage of methods. It explains how all components of a for loop are optional, demonstrates method creation and invocation, and emphasizes the importance of method arguments for flexibility and reusability. Additionally, it includes exercises to reinforce understanding of these concepts.

Uploaded by

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

196

256
324
400

Solution 7

jshell> for (int i=1; i<=19; i += 2) {


...> System.out.printf(i*i).println();
...> }
1
9
25
49
81
121
169
225
289
361

Step 30: Puzzling You With for


In the conceptual form of the for construct:

for (initialization; condition; updation) {


statement;
statement;
//...
statement;
}

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>

. Multiple initializations, Empty Statement


You can have multiple statements in initialization and update separated by , .

jshell> int j
i ==> 11
jshell> for (i=1, j=2; i<=10; i++, j++);
jshell> i
i ==> 11
jshell> j
j ==> 12
jshell>

In the example below, i is incremented and j is decremented.

jshell> for (i=1, j=2; i<=10; i++, j--);


jshell> i
i ==> 11
jshell> j
j ==> -8
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.

It can only be terminated externally with a keyboard interrupt ( CTRL + c ).

jshell> for (;;);

^C
jshell>

. Statement Block in for


As in case of the if conditional statement, we can have statement blocks in for loops as well. As before, we
enclose the statement set between braces (' { ' and ' } '). The statements are executed repeatedly, in the same
order as they appear in the block.

jshell> for (i=1; i<=5; i++) {


...> System.out.println("No 1");
...> System.out.println("No 2");
...> }
No 1
No 2
No 1
No 2
No 1
No 2
No 1
No 2
No 1
No 2

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

a pair of braces { and } enclose method-body


ReturnType is the type of methodName 's return value

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> void sayHelloWorldTwice() {


...> System.out.println("Hello World");
...> System.out.println("Hello World");
...> }
| created method sayHelloWorldTwice()

A little bit of theory:


Above code for the method is called method definition.
void indicates that the method does not return any computed result - We will examine return values from
methods, a little later.
When the code ran, it didn't exactly welcome us twice, did it? All we got was a boring message from JShell ,
mumbling created method sayHelloWorldTwice() .
That's because defining a method does NOT execute its statement body.
Since the statement block is not stand-alone anymore, its functionality needs to be invoked. This is done by writing
a method call.
Let's look at a few examples for method calls.

jshell> sayHelloWorldTwice
| Error:
| cannot find symbol
| symbol: variable sayHelloWorldTwice
| sayHelloWorldTwice
| ^----------------^

jshell> sayHelloWorldTwice()
Hello World
Hello World

All that we had to do was to add parantheses to name of the method.


The trailing ' ; ' can be left out in JShell , and is another example of syntax rules being relaxed.
Method names need to follow the same rules as variable names.
Summary
In this step we:
Got our hands dirty coding our first method
Learned that defining and invoking methods are two different steps
Step 02: Exercise-Set PE-01
Let's now reinforce our basic understanding of methods, by trying out a few exercises.
Exercise Set -5
. Write and execute a method named sayHelloWorldThrice to print Hello World thrice.
. Write and execute a method that prints the following four statements:
I've created my first variable

I've created my first loop

I've created my first method

I'm excited to learn Java

Solutions to PE-01
Solution-1

jshell> void sayHelloWorldThrice() {


...> System.out.println("Hello World");
...> System.out.println("Hello World");
...> System.out.println("Hello World");
...> }
| created method sayHelloWorldThrice()

jshell> sayHelloWorldThrice()
Hello World
Hello World
Hello World

Solution-2

jshell> void sayFourThings() {


...> System.out.println("I've created my first variable");
...> System.out.println("I've created my first loop");
...> System.out.println("I've created my first method");
...> System.out.println("I'm excited to learn Java");
...> }
| created method sayFourThings()

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

Step 03: Editing A Method Definition ( Jshell Tips)


Snippet-01: Editing sayHelloWorldTwice()

jshell> void sayHelloWorldTwice() {


...> System.out.println("Hello World");
...> System.out.println("Hello World");
...> }
| created method sayHelloWorldTwice()

The /methods command lists out the methods defined in the current session.
jshell> /methods
| void sayHelloWorldTwice()
jshell>

The /list command lists the code of the specified method.

jshell> /list sayHelloWorldTwice


59 : void sayHelloWorldTwice() {
System.out.println("HELLO WORLD");
System.out.println("HELLO WORLD");
}
jshell>

The /edit command allows you to modify the method definition, in a separate editor window.

jshell> /edit sayHelloWorldTwice


| modified method sayHelloWorldTwice
jshell> sayHelloWorldTwice()
HELLO WORLD
HELLO WORLD
jshell>

The /save method takes a file name as a parameter. When run, it saves the session method definitions to a file.

jshell> /save backup.txt


jshell> /exit
| Goodbye

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:

ReturnType methodName(ArgType argName) {

method-body

The only addition to the concept of a method, is the phrase


ArgType argName

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 .

jshell> void sayHelloWorld(int numOfTimes) {


...> }
| created method sayHelloWorld(int)

Let's try to call the method.


jshell> sayHelloWorld()
| Error:
| method sayHelloWorld in class cannot be applied to given types;
| required : int
| found : no arguments
| reason : actual and formal argument lists differ in length
| sayHelloWorld(
|^-----------------^
jshell> sayHelloWorld(1)
jshell>

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.

void sayHelloWorld(int numOfTimes) {


System.out.println(numOfTimes);
}

System.out.println(numOfTimes) prints the value of argument passed.


A method can be invoked many times within a program, and each time different values could be passed to it. The
following example will illustrate this fact.

jshell> sayHelloWorld(1)
1
jshell> sayHelloWorld(2)
2
jshell> sayHelloWorld(4)
4
jshell> /edit sayHelloWorld
| modified method sayHelloWorld(int)
jshell>

Snippet-03: More complex method


Code inside a method can be any valid Java code! For instance, you could write code for iteration, such as a for
loop.
Let's look at an example:

void sayHelloWorld(int numOfTimes) {


for (int i=1; i<=numOfTimes; i++) {
System.out.println(numOfTimes);
}
}

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>

Snippet-4 : Saying "Hello World", Again and again...


We wanted to print "Hello World" multiple times. Let's update the method:
void sayHelloWorld(int numOfTimes) {
for (int i=1; i<=numOfTimes; i++) {
System.out.println("Hello World");
}
}

Isn't this cool?


jshell> sayHelloWorld(1)
Hello World
jshell> sayHelloWorld(2)
Hello World
Hello World
jshell> sayHelloWorld(4)
Hello World
Hello World
Hello World
Hello World
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

jshell> void printSquaresOfNumbers(int n) {


...> for(int i=0; i< n; i++) {
...> System.out.println(i*i);
...> }
...> }
| created method printSquaresOfNumbers(int)
jshell>

Step 07: PMT-Challenge Revisited (And Some Puzzles)


A method, in its own right, provides an elegant way to name and reuse a code block. In addition, its behavior can be
controlled with parameters.
Can we top-up the existing solution to the PMT-Challenge, with even more elegance? You're right, we're talking
about:
. Writing a method to print the multiplication table for 5.
. Using this method to print the multiplication table for any number.
Want to take a look? Dive right in.
Here's what we did earlier:

jshell> for (int i=1; i<=10; i++) {


...> System.out.printf("%d * %d = %d", 5, i, 5*i).println();
...> }
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

Let's wrap this in a method:

void printMultiplicationTable() {
for (int i=1; i<=10; i++) {
System.out.printf("%d * %d = %d", 5, i, 5*i).println();
}
}

You might also like