public void showEvenNumberCount()
{
int count;
count = 0;
for (int i=1; i<=10; i++)
{
if (i %2 == 0)
{
count++;
}
}
System.out.println("even number count from 1 to 10 is: " + count);
}
public void showEvenNumberCount() {
int count;
count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
count++;
}
}
System.out.println("even number count from 1 to 10 is: " + count);
}
public class Foo {
/* -------------------------------------
Instance methods */
public void showEvenNumberCount() {
int count;
count = 0;
for (int i = 1; i <= 10; i++) {
if (isEven()) {
count++;
}
}
System.out.println("even number count from 1 to 10 is: " + count);
}
public boolean isEven(int n) {
return n % 2 == 0;
}
/* -------------------------------------
main */
public static void main(String[] args) {
Foo foo;
foo = new Foo();
foo.showEvenNumberCount();
}
}
When a conditional statement has only one block statement it may optionally be streamlined by removing the block symbols (this is not required, but is optional per your preference). Advantage is does simplify things further.
Note that the if block in our previous example only has one statement
count++
. Thus, we optionally may remove the {} block brackets. Similarly, the for loop also has only one statement (the if statement). So again we may optionally may remove it's {} block brackets. This is optional and per your preference.
public void showEvenNumberCount() {
int count;
count = 0;
for (int i = 1; i <= 10; i++)
if (isEven())
count++;
System.out.println("even number count from 1 to 10 is: " + count);
}