Your first program
Java
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to Java");
System.out.println(2 + 3);
System.out.print("No new line ");
System.out.println("after print");
}
}Line by line
public class Main: all Java code lives inside a class. The file must be named after its public class, so this code goes in Main.java.
public static void main(String[] args): the main method, where the program starts.
public: it can be called from outside the class (the JVM needs to call it),static: it belongs to the class itself, so no object has to be created first,void: it returns nothing,String[] args: command-line arguments, as an array of strings.
System.out.println(...) prints a value and then a new line. System.out.print(...) prints without the new line.
Braces { } mark the start and end of the class and of the method; semicolons end statements.
Case matters
Java is case-sensitive: system.out.println and Main versus main are different. Conventions:
| Kind of name | Convention | Example |
|---|---|---|
| classes | PascalCase | Main, BankAccount |
| methods and variables | camelCase | main, accountBalance |
| constants | UPPER_CASE | MAX_SIZE |
Comments
Java
// single-line comment
/* multi-line
comment */
/** Javadoc comment, used to generate documentation */Joining text
+ joins strings, and converts numbers to text when one side is a string:
Java
public class Main {
public static void main(String[] args) {
int apples = 3;
System.out.println("I have " + apples + " apples");
System.out.println("Sum: " + 2 + 3); // "Sum: 23"!
System.out.println("Sum: " + (2 + 3)); // "Sum: 5"
}
}The second line surprises people: Java works left to right, so "Sum: " + 2 becomes text first, then 3 is joined on.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.