JAVA OUTPUT - JAVA: Learn JAVA Quickly (2017)

JAVA: Learn JAVA Quickly (2017)

CHAPTER 2. JAVA OUTPUT

Class System is used for printing to console some text. Let`s try it on most famous example of your first Java program, Hello World! To do this we need to set up our Java project. First open Eclipse. Creating project in Eclipse is very simple File ->New ->Java Project. Name project as FirstJavaProject and then click Finish.

In our project press right click on src folder and create a new package by New ->Package. Name package as first.pack.

Note: Packages are used for better organization of Java classes. In this case we build our own classes, but there are many build-in classes which need some packages to import (java.io, java.util etc).

All operations in Java are made in classes. To create them, right click on package New ->Class and name it as JavaClass. Check public static void main (String[]args) and click Finish.

Note: public static void main (String[]args) is method which will be explained later. For now, it is enough to know that in main method are called all other methods in your Java application. This and every other code is supposed to be putinside main method.

System.out.println("Hello World!");

Our program should look like this:

Note: There is a one little trick to print this faster. Type syso, hold ctrl and press space. Then press Enter.

Ok, now this need somehow to be started. To do that pressRun ->Run As ->Java Application.

expected: Hello World! will be printed to console

We learned how to print some massages to console. Let`s now use what we already covered and make some mix with primitive types. Create a new class called PrintPrimitiveTypes and add main method.

Add following lines inside main method:

inta = 2;

doubleb = 3.14;

System.out.println("1. Old value of b = " +b);

b = a;

System.out.println("2. New value of b = " +b);

Run application.

expected: 1. Old value of b = 3.14 will be printed to console.

2. New value of b = 2.0

Note: Try it with other operators. For example:

intc = 4;

b = c * 3.14;

System.out.println("3. New value of b = " +b);

As you can see here is used + operator to chain text with integer. Try to make new examples on your own to feel more comfortable with code writing.

CONTROL FLOW STATEMENTS

IF

if(condition)

action

else

another action

Now we will do some simple example of IF usage. Make a new class ControFlow and add following lines:

inta = 10;

if(a< 11) {

System.out.println("A is less than 10");

}

else {

System.out.println("A is not less than 10");

}

expected: A is less than 10 will be printed to console.

Let`s make it a little more difficult. Just like in a real life, you can provide more than one condition for any situation. In this case, it is made by adding else if statement. Add following lines to current classand run it :

intb = 15;

if (b == 13)

System.out.println("b == 13");

elseif ((b<=17) && (b>= 12))

System.out.println("b is less than or equal to 17 and greater than or equal to 12");

else

System.out.println("b is not any from this");

expected: b is less than or equal to 17 and greater than or equal to 12 will be printed to console.

Program first checks if b == 13, it is not, then checks another condition which is true and print it to console. If this condition was also false, then last one sentence will be printed. Try to make another condition on your own to see output. You can see that statement works fine also without curly braces.

Now we got idea how to make a simple program in Java. Let`s solve this problem. Imagine that you had test in your school. You got some score and grade. Try to make program, using if statement, to check which grade you got based on your score.

Note: First you need to declare two variables score and grade, like this:

intgrade;

intscore = 85;

Try it yourself firstly, think about conditions. Here is solution:

if (score>= 95)

grade = 10;

elseif (score>= 85)

grade = 9;

elseif (score>= 75)

grade = 8;

elseif (score>= 65)

grade = 7;

elseif (score>= 55)

grade = 6;

else

grade = 5;

System.out.println("Grade is: " + grade);

expected: Grade is: 9 will be printed to console

Let`s now see one simple example of code:

if (i< 10)

a = i * 100;

else

a = i * 10;

Now look at this code:

a = i<10 ?i * 100 : i * 10;

This is same thing made intwo different ways. Like if/else statement this line of code tells to compile to check if i < 10, if it is true a = i * 100. If it is false, then multiply i with 10 (i * 10).

Ifis ,with for loop, most common used statement so it would be good to have as much as it possible practice.

SWITCH

switch(a) {

case '1': action

break;

case '2': action

break;

case '3': action

break;

default:

action

}

By looking at example above, try to write a program that will print season of year based on condition. Here is a solution:

intseason = 2;

switch (season) {

case 1: System.out.println("Spring");

break;

case 2: System.out.println("Summer");

break;

case 3: System.out.println("Autumn");

break;

case 4: System.out.println("Winter");

break;

default: System.out.println("Unknown season");

break;

}

expected: Summer will be printed to console

Note: There are three types of print statements:

System.out.print("Massage");

System.out.println("Massage");//add a new line

String str = "World";

System.out.printf ("Hello %s", str);//placeholder for a String (%s), also can be for char, int, boolean, float

FOR

for (initialization; condition; increment/decrement) {

body

}

Now we will do some basic iteration from 1 to 10 with for loop. Here is a code:

for(inti = 1;i<= 10;i++) {

System.out.print(i + " ");//try println to see difference

}

expected: 1 2 3 4 5 6 7 8 9 10will be printed to console

Ok, but what if we want to iterate in reverse way. In first example is used incrementation, so in second we need decrementation. Think what else need to be changed, is condition still i <= 10 ? Here is solution of problem:

for(inti = 10;i>= 1;i--) {

System.out.print(i + " ");

}

expected: 10 9 8 7 6 5 4 3 2 1will be printed to console

FOR EACH

For each loops are used to iterate through arrays, what will be covered later. This is simpler type of loop because arrays have already fixed length and there is no need for that condition (i <= 10). Here is some basic example:

double[] array = {1.6, 2.8, 4.54};

for (doublear : array){

System.out.print(ar + " ");

}

expected: 1.6 2.8 4.54 will be printed to console

Nested loops

We will now make things a little more complicated by using nested loops. Nested loops are loops inside another loops. It can be confusing for someone who is beginner, but when you start to understand concept of them you will realize how powerful they could be. Let`s start with this one example:

for(inti = 0; i< 10; i++){

if (i==7){

break;

}

if (i == 2)

continue;

System.out.print(i + " ");

}

expected: 0 1 3 4 5 6 will be printed to console

Difference between break and continue is clear to resolve from this example.

break – when loop reaches to 7 it stops and prints everything until that condition.

continue – when condition is met it stops and start another iteration.

Next peace of code will make this more advanced. Look at this:

intsumEven=0;

intsumOdd=0;

intcounterEven=1;

intcounterOdd=1;

for(inti = 1;i<= 100;i++){

if(i % 2 == 0){

if(counterEven == 3){

sumEven+=i;

counterEven = 1;

}elsecounterEven++;

}else{

If(counterOdd == 5){

sumOdd+=i;

counterOdd = 1;

}elsecounterOdd++;

}

}

System.out.println("Sum of even numbers is: " + sumEven + " , sum of odd numbers is: " + sumOdd);

expected: Sum of even numbers is: 816, sum of odd numbers is: 540 will be printed to console

Program will loop through first 100 numbers, check which one is even or odd and based on that condition will sum them.

WHILE

while (condition) {

body

}

while loop is looping until condition is false. Let`s see this on example:

intn = 15;

inti = 5;

while (i<n){

System.out.print(i + " ");

i++;

}

expected: 5 6 7 8 9 10 11 12 13 14 will be printed to console

So, it starts with 5 (inti = 5;) and goes through while loops every time until condition i < n (intn = 15;) is false. i++ means that every iteration through loop adds 1 to value of I (6, 7, 8..14).

DO WHILE

do{

body

}while(condition);

Note: Difference between those two is that do while loop will execute minimum one time. To figure this out follow this code:

inty = 0;

do {

System.out.print(y++);

} while (y< 10);

expected: 0123456789 will be printed to console

It literally says do something, in this case print value of y incremented every other time, and then check condition. Iterate through loop until condition is false (until 9).