owned this note
owned this note
Published
Linked with GitHub
# Start point with Java
:::info
This is a part of preparation for Paper 2 in IB Computer Science diploma. The lessons are
1) [Start point with Java](/S3oXtcWLQduOy_R5_03Z2g)
2) [The concept of Object in OOP](/6FsqJbw3SKq5m1NKk56U3Q)
3) [The POJO (Plain Old Java Object) and their common methods](/zJgmWQUbSLqf3JIiVehBNA)
4) [Relationship between objects and UML diagrams](/5rUt1ACuTQGF7nuLhvx7TA)
:::
Java is a High level programming language. By high level we refer high level of abstraction. In this case the abstraction is that doesn't care about the machin is made to.
It's a compiled then run programming language.
It compiles into a "bitcode" program that is going to be run by a Virtual Machine (Java Virtual Machine, to be specific)
:::info
**Virtual machine:**
Is software that emulates a type of machine. That machine that it's emulated can also have their own OS (or maybe not). Examples of Virtual Machines are JVM but also old consoles emulators.
Also these VM can be accessed sometimes online. _example of when I used VM for the TSB_
:::
The purpose of the JVM
The Java Virtual Machine is a software that interpret the bytecode compiled from a java IDE. This software is different for different OS and devices. But the idea is the same program would run exactly the same in both OS using this layer of the VM

_Quick paint and mouse used here. Still better than some AIs_
Their motto is "compile once run everywhere"
## Characteristics of Java
One of the main characteristics of Java is that is a highly typed programming language (unlike python or javascript)
This means that every time that we declare a variable we need to define also its type.
When we declare a variable the word that it's just before it is the type.
```java
String name = "M";
int height = 145;
boolean empty = true;
Student jcr = null;
```
Also statements ends with a semicolon (";")
## The Main class, the strart point
The entry point of any java app is the Public static void Main function (method). Whatever is inside of it will be executed.
So the most basic program in java would be this one:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
:::danger
:warning: For now you don't need to understand everything that is about the public static void Main, but in the end you would need to understand it.
:::
So a simple program would be like this:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
int x = 5;
int y = 6;
x = x +y ;
System.out.println(x);
}
}
```
### Comments
In java comments are written with //. If you want to do several lines comment you can do `/*` and finish with `*/`
### Output
We're not going to deal with all the details but for outputing we're going to use the console with `System.out.println(stringToBeOutput);`
### Workflow (if/else and derivates)
In Java the structure of an if is similar to pseudocode and C++. You put the condition in parethesis and what happens is between curly braces.
```java
if (condition) {
//this happens only if the condition
}
//this happens all the time
```
We also have if/else and also if/ else if
```java
if (condition1) {
//this happens only if the condition1 applies
}
else if (condition 2) {
//this happens if conditon 1 is not met but condition 2 is met
}
else{
//if both conditons 1 and 2 are not met this happens
}
```
### Iteration
#### While loop
While loop is while is similar to all the whiles in other programming languages and pseudocode. Evaluates a certain condition and while this condition is met it repeats the block of code inside of it.
```java
while (condition) {
//this is repeated while the condition is met (can be forever)
}
```
Exercise:
With this information _use a while loop_ to add all numbers from 1 to 100 and output it:
:::spoiler
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
int a=1;
int sum=0;
while(a<100) {
sum=sum+a;
a=a+1;
}
System.out.println(sum);
}
}
```
Credit: C.R.
The result should be 5050
:::
#### For loop
In Java the for loop has 3 statements inside
The first statement is the iteration variable declaration (usually int i = 0). This is a local variable whose scope is going to be just the for loop.
The second statement is the staying condition. It's a condition that needs to be met in order to continue in the loop. (usually i < than certain threshold but varies)
The third statement is the step. This is executed at the end of each iteration (each loop) and usually is dedicated to modify the iteration variable. The most common is add one to the variable or substract
```java
for( int x = 0; x < 100; x++) {
//statements that are going to be repeated
}
```
:::success
x++ is the same as writing x +=1 and it's the same as writing x = x +1
:::
Exercise:
With this information _use a for loop_ to add all numbers from 1 to 100 and output it:
solution in the spoiler:
:::spoiler
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++){
sum += i;
}
System.out.println(sum);
}
}
```
Credit P.H.F.
The result should be (still) 5050
:::
### Exercises
#### Exercise 1
Reverse count
I want a program whose output is a reverse count from 20 to 0. After that it's going to say "LIFT OFF!"
Solutions in the spoiler:
:::spoiler
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
for (int i = 20; i >= 0; i--) {
System.out.println(i);
}
System.out.println("LIFT OFF!");
}
}
```
Credit D.Z.
:::
#### Exercise 2
I want a program that outputs all odd numbers that are multiples of 7 from 0 to 200.
:::info
**Modulus operator**
Here you can use the modulus operator to specify if a number has a certain remainder. To do that you use %. For example if we write
```java
int x = 5;
int y = 2;
System.out.println(5%2); //1
```
:::
Solution in the spoiler
:::spoiler
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 200; i++){
if(i%2 == 1 && i%7 == 0){
System.out.println(i);
}
}
}
}
```
:::
#### Exercise 3
Output the 20 first Fibonacci numbers.
The first one is 1, the second is 1, then rest are the sum of the 2 previous.
:::success
HL you can use an iterative way or you may try to use a recursive function to do it.
:::
Solution in the spoiler
:::spoiler
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Fibonacci numbers");
int n = 0;
int secondLastFibonacci = 1;
int lastFibonacci = 1;
System.out.println(secondLastFibonacci);
n++;
System.out.println(lastFibonacci);
n++;
int newFibonacci = secondLastFibonacci + lastFibonacci;
while (n < 20) {
newFibonacci = secondLastFibonacci + lastFibonacci;
n++;
System.out.println(newFibonacci + " is the fibonacci number number "+ n);
secondLastFibonacci = lastFibonacci;
lastFibonacci = newFibonacci;
}
}
}
```
:::
#### Exercise 4
(a bit complex)
Print all numbers from 0 to 1000 whose figures add 12.
:::info
**Hint** Use modulus 10 for separate figures.
:::
Solution in the spoiler
:::spoiler
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
for(int i= 1 ; i <= 1000; i++){
if(i%10 + (i/10)%10 + (i/100)%10 + (i/1000)%10 == 12){
System.out.println(i);
}
}
}
}
```
Credit P.H.F.
:::
### Arrays
:::info
**Reference**
https://www.w3schools.com/java/java_arrays.asp
:::
We need to state the type of the variable.
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2,2, 3, 4,4,5,5,5,5, 7, 8,9,10, 12};
//Mean (average)
int sum = 0;
for (int x = 0; x < numbers.length; x++){
sum = sum + numbers[x];
}
System.out.println("The mean is: "+ (sum/numbers.length));
//Median (previously the array has to be sorted)
if (numbers.length %2 == 1) {
System.out.println("The median is "+ numbers[numbers.length/2] );
}
else{
int median =(numbers[numbers.length/2] + numbers[numbers.length/2-1] )/2;
System.out.println("The median is " + median);
}
}
}
```
## Resources
https://onecompiler.com/java/
https://www.w3schools.com/java/default.asp
## Next step
Once you have grasped the concepts of java we can jump to [The concept of Object in OOP](/6FsqJbw3SKq5m1NKk56U3Q)