MOOC.fi Java Programming I Part 2
Fundamentals of Java
Continuing the journey to master fundamentals of Java in MOOC.fi Java Programming I Part 2!
Recurring problems and patterns to solve them
- print and println is different! careful that print just prints everything in 1 line, even with multiple print statements
Repeating functionality
-
Remember from part 1 that expression is the thing in parentheses in conditional statement?
-
Simple example of while (true) if … break:(breaks out of loop when true expression is false)
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Input a number, 0 to quit");
int command = Integer.valueOf(scanner.nextLine());
if (command == 0) {
break;
}
System.out.println("You input " + command);
}
System.out.println("Done, thank you!");
- Continue makes execution of loop go to beginning of that loop. Below example, prints unfit number, insert positive integers
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insert positive integers");
int number = Integer.valueOf(scanner.nextLine());
if (number <= 0) {
System.out.println("Unfit number! Try again.");
continue;
}
System.out.println("Your input was " + number);
}
-
If we need to use a variable after a loop, it needs to be declared before the loop. (Obviously, but sometimes we miss it and careless mistakes happen)
-
Every if-statement should a single, clear task and not multiple.
More loops
-
Difference between multiple if statements and else if statements: If statements are executed independent of one another; each one will run. Else if statements only execute if the previous ifs fail.
-
Good while loop structure:
Scanner reader = new Scanner(System.in);
// Create variables needed for the loop
while (true) {
// read input
// end the loop -- break
// check for invalid input -- continue
// handle valid input
}
// functionality to execute after the loop ends
Methods and dividing the program into smaller parts (useful to run code simulation for this part)
-
Don’t forget public static double/int nameOfMethod()
-
A method is a named set consisting of statements that can be called from elsewhere in the program code by its name. It can be custom-made or pre-made by respective languages.
-
Methods are written outside of the curly braces of the main, yet inside out the “outermost” curly braces. They can be declared below or above main.
-
Order of code execution: When the encountered statement is a method call, the execution of the program moves inside the method. The statements of the method are executed one at a time from top to bottom. After this, the execution returns to the place where the method call occured, and then proceeds to the next statement in the program.
-
The main program (main) itself is a method. When the program starts, the operating system calls main. The main method is the starting point for the program, since the execution begins from its first line. The execution of a program ends at the end of the main method.
-
Naming method follows camelCase like public static void thisMethodSaysWoof()
-
Parameters are values given to a method that can be used in its execution in parentheses like public static void divisibleByThreeInRange(int beginning, int end)
public class Example {
public static void main(String[] args) {
int number = 1;
System.out.println("The value of the number in the main program: " + number);
incrementByThree(number);
System.out.println("The value of the number in the main program: " + number);
}
public static void incrementByThree(int number) {
System.out.println("The value of the number in the method: " + number);
number = number + 3;
System.out.println("The value of the number in the method: " + number);
}
}
// The value of the number in the main program: 1, The value of the number in the method: 1, The value of the number in the method: 4, The value of the number in the main program: 1
-
The variable living in the main program is different from the variable of the method, even if they have same name. This is because The parameter number is copied for the method’s use, i.e., a new variable called number is created for incrementByThree method, to which the value of the variablenumber in the main program is copied during the method call. The variable number inside the method incrementByThree exists only for the duration of the method’s execution and has no relation to the variable of the same name in the main program.
-
keyword void means method returns nothing while static returns something. If we want the method to return a value, the keyword must be replaced with the type of the return variable like int or double like public static int. For example:
public static int alwaysReturnsTen() {
return 10;
}
-
When execution inside a method reaches the command return, the execution of that method ends and the value is returned to the calling method. The lines of source code below the return command are never executed.
-
But this works since it is possible to reach every statement in it — even though there is source code below the return command.
public static int functioningMethod(int parameter) {
if (parameter > 10) {
return 10;
}
System.out.println("The number received as parameter is ten or less.");
return parameter;
}
- If a method has the form public static void nameOfMethod() it is possible to return from it — in other words, to stop its execution in that place — with the return command that is not followed by a value. For example:
public static void division(int numerator, int denominator) {
if (denominator == 0) {
System.out.println("Can not divide by 0!");
return;
}
System.out.println("" + numerator + " / " + denominator + " = " + (1.0 * numerator / denominator));
}
- Correct way to call method:
public static void main(String[] args) {
double averageResult = average(4,3,2);
System.out.print("The average of the numbers: " + averageResult);
}
public static double average(int number1, int number2, int number3) {
int sum = number1 + number2 + number3;
double avg = sum / 3.0;
return avg;
}
- Wrong way to call method (because variables in method are not visible in main program):
public static void main(String[] args) {
int first = 3;
int second = 8;
int third = 4;
average(first, second, third);
// trying to use a method's internal variable, DOES NOT WORK!
System.out.print("The average of the numbers: " + avg);
}
public static double average(int number1, int number2, int number3) {
int sum = number1 + number2 + number3;
double avg = sum / 3.0;
return avg;
}
- As well as placing the method result into a helper variable, another way that works is to execute the method call directly inside the print statement:
public static void main(String[] args) {
int first = 3;
int second = 8;
int third = 4;
// calling the method inside the print statement, DOES WORK!
System.out.print("The average of the numbers: " + average(first, second, third));
}
- Wrong way where method is used like a variable instead of calling the method:
public static void main(String[] args) {
int first = 3;
int second = 8;
int third = 4;
// trying to use the method name only, DOES NOT WORK!
System.out.print("The average of the numbers: " + average);
}
- The return value does not need to be pre-defined - it can also be calculated.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int number1 = Integer.valueOf(scanner.nextLine());
System.out.print("Enter the second number: ");
int number2 = Integer.valueOf(scanner.nextLine());
System.out.print("The total sum of the numbers is: " + sum(number1, number2));
}
public static int sum(int first, int second) {
// instead of storing method's return value in a vriable
// like int hola = first+ second, return hola;
return first + second;
}
-
Computer looks for the variables (number1.number2) and copies their values as the values of the method sum’s parameters. (i.e. value of variable number1 is copied as value of method paramter first)/ The method then adds the values of the parameters together, after which it returns a value.
-
Call stack contains frames, each of which includes information about a specific method’s internal variables and their values. It works just like a stack in data structure, prioritising methods on top of its stack
-
very useful simulations and exercises