# Introduction to Java

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Source: Wikipedia

### Code structure in Java

A source-code file (with the .java extension) holds class. The class contains the methods and the methods contain the statements.

// This is the source file
public class spaceship {
//this is a class
void fly() {
//this is a method
statement1;
statement2;
}
}


### Anatomy of a class

Inside the class there must be a specially written method named main() that makes the program running:

public class HelloWorld {
public static void main (String[] args) {
System.out.println("Hello, World!");
}
}


Now save the file as HelloWorld.java and to compile and run in the terminal:

javac HelloWorld.java && java HelloWorld

Things you can do inside the main method (or inside any method):

Statements: declarations, assignments, method calls, etc.

int x = 3;
String name = “Dirk”;
x = x * 17;
System.out.print("x is " + x);
double d = Math.random();
// this is a comment


Loops: for and while

while (x > 12) {
x = x -1;
}
for (int x = 0; x < 10; x = x + 1) {
System.out.print("x is now " + x);
}


Conditions: if/else tests

if (x == 10) {
System.out.print("x must be 10");
} else {
System.out.print("x isn't 10");
}
if ((x < 3) & (name.equals("Dirk"))) {
System.out.println("Gently");
}
System.out.print("this line runs no matter what");


Note:
Each statement must end in a semicolon. x = x + 1;
A single-line comment begins with two forward slashes. // this line is a comment
Most white space doesn’t matter. x = 3 ;
Variables are declared with a name and a type int weight; //type: int, name: weight
Classes and methods must be defined within a pair of curly braces.