Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


Code indentation

Note that the commands in the block following the if statement (i.e. the lines after the curly brace, { ) are not written at the same level as the if statement itself. They should be indented slightly to the right. Indentation happens when you press the tab key, which is located to the left of q key. When the block ends with the closing curly brace, indentation ends as well. The closing curly brace } should be on the same level as the original if statement.

The use of indentation is crucial for the readability of program code. During this course and generally everywhere, you are expected to indent the code properly. IntelliJ helps with the correct indentation. You can easily indent your program by pressing control, alt, and l simultaneously. It’s also possible to select a whole section of code, and press tab to indent this whole section

Exercise code-layout-1 : A positive number

Create a program that asks the user for a number and tells if the number is positive (i.e. greater than zero).

Type a number: ~~5~~

The number is positive.
Type a number: ~~-2~~

The number is not positive.

Are you certain that your code is indented correctly?

Reread the section on code indentation. Observe what happens when you press shift, alt and f simultaneously! The same automatic indentation functionality can also be used using the menu bar by selecting Source and then Format.

Exercise code-layout-2 : Age of majority

Create a program that asks for the user’s age and tells whether the user has reached the age of majority (i.e. 18 years old or older).

How old are you? ~~12~~ 

You have not reached the age of majority yet!
How old are you? ~~32~~ 

You have reached the age of majority!

Exercise code-layout-3 : Even or odd?

Create a program that asks the user for a number and tells whether the number is even or odd.

Type a number: ~~2~~

Number 2 is even.
Type a number: ~~7~~

Number 7 is odd.