☕️ Java Guide
This guide contains basic syntax and tips how to write Java code.
Java is an object-oriented programming language which utilizes virtual machines to get it running on all major platforms.
Installation
Never use any of the Oracle Javas, they have awful licensing agreements. I recommend using Adoptium Eclipse Temurin, which is free, regularly updated and runs everywhere. Pick the latest LTS (long-term support) version available when starting.
- JDK is for running and developing Java applications.
- JRE is only for running Java applications in production, but you could use JDK too.
Use your chosen local development Java with SDKMAN. It makes managing your Java versions much easier.
sdk list java
sdk install java 17.0.0-tem
java --version
Use Spring Boot to create standalone applications.
Architecture
You import packages or individual classes from those packages.
// Import ArrayList class inside of the java.util package.
import java.util.ArrayList;
// Import all classes inside of java.security package.
import java.security.*;
Java files end with .java
and contain one public class that has the same name as the file.
// ClassName.java
public class ClassName {
// ...
}
When you run a Java program, you must target a public class that has main
method.
public class MyClass {
public static void main (String[] args) {
System.out.println("Hello World!");
}
}
Code Layout
Prefer indention of 4 spaces. Not tabs.
// good
public String getName() {
return this.name;
}
Control statement keyword is followed by one space.
// bad
if(true) {
//...
}
// good
if (true) {
//...
}
Opening curly brace stays on the starting row. Applies to all keywords and control structures.
// bad
if (name != this.name)
{
//..
}
// good
if (name != this.name) {
//..
}
Opening curly brace is separated by one space. Applies to all keywords and control structures.
// bad
if (name != this.name){
//..
}
// good
if (name != this.name) {
//..
}
Naming
Constants are named all caps.
// bad
static final String fooBar = "111";
// good
static final String FOO_BAR = "111";
Variable modifier order is access-static-final/volatile
.
// bad
public final static String text = "";
// good
public static final String text = "";
Comments
Prefer //
for the most comments.
// single-line comment
Use /* */
for comments that go multiple lines.
/*
* Multi-line comments look like this. They work in C89 as well.
*/
Use /** */
for formal comments.
/**
* JavaDoc comments look like this. Used to describe the Class or various
* attributes of a Class.
*/
Data Types
// Boolean
boolean myBoolean = true;
// Byte is between -128 and 127.
byte myByte = 99;
// Short is between -32,768 and 32,767.
short myShort = 1337;
// Integer is between -2,147,483,648 and 2,147,483,647.
int myInt = 1337;
// Long is between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
long myLong = 1337;
// Float is a single-precision value between -2,147,483,648 and 2,147,483,647.
// If number is not followed by `f`, it is treated as a double.
float myFloat = 133.7f;
// Double is a double-precision value between -2,147,483,648 and 2,147,483,647.
double myDouble = 133.7;
// Char is a single 16-bit Unicode character.
char myChar = 'A';
// String is an sequence of characters.
String myString = "Printing on a new line?";
You can make variables immutable with final
.
final int HOURS_I_WORK_PER_WEEK = 900;
Cast using helper methods. You can convert variables from one data type to other using helper methods.
Integer.parseInt("123");
Integer.toString(123);
Float.parseFloat("12.34");
Float.toString(12.34f);
Double.parseDouble("12.34");
Double.toString(12.34);
You can use explicit casting to convert classes.
MyClass myStuff = (MyClass)unknownClassObject;
Use StringBuilder
when constructing strings inside loops. Improves performance and reduces memory usage.
// bad
a = a + b; // Where a and b are Strings.
// good
StringBuilder myResult = new StringBuilder("result = ");
myResult.append( foo() ).append( bar() ).append( biz() );
Data Structures
Array size must be specified on declaration. Use java.util.ArrayList<E>
if you do not know the array size.
int[] myArray = new int[10];
String[] myOtherArray = new String[1];
// Instant initialization.
int[] myInstantArray = {9000, 1000, 1337};
// myInstantArray[0] == 9000
Allocate size for lists if possible. Improves performance and reduces memory usage.
// bad
List<MyClass> items = new ArrayList<MyClass>();
// good
List<MyClass> items = new ArrayList<MyClass>(10);
Control Structures
If-statement.
int a = 0;
if (a > 0) {
System.out.println("Positive!");
} else if (a < 0) {
System.out.println("Negative!");
} else {
System.out.println("Zero!");
}
// => Zero!
Ternary operation.
int score = 11;
String result = (score > 10) ? "good" : "bad";
System.out.println(result);
// => good
Switch-statement.
int count = 2;
switch (count) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
case 4:
System.out.println("more than two");
break;
default:
System.out.println("no idea");
break;
}
// => two
For-loop.
for (int i = 0; i < 11; i++){
System.out.println(i);
}
// => 0-10
You can interate over each element with :
.
int[] numbers = {1, 2, 3};
for (int number : numbers){
System.out.println(number);
}
// => 1-3
While-loop.
int i = 0;
while (i < 11) {
System.out.println(i);
i++;
}
// => 0-10
Do-while-loop.
int i = 0;
do {
System.out.println(i);
i++;
} while(i < 11);
// => 0-10
Functions
Functions are always associated with a class.
class Person {
protected String name;
public void setName(String name) {
this.name = name;
}
}
Overriding means redefining an existing function.
@Override
public String toString() {
return "Person: " + this.name;
}
Classes
Class usage.
MyClass stuff = new MyClass();
stuff.methodName();
stuff.methodNameToo();
Access modifiers specify who can access an aspect of the class:
- Private: accessible from within the class.
- Protected: accessible from the class and subclasses.
- Public: accessible from anywhere.
- If not access modifiers is specified, accessible from within the package.
Class definition.
class Employee {
String name;
public String title;
protected int age;
private int stress;
// Constructor must have the same name as the class.
public Employee(String name, String title, int age, int stress) {
this.name = name;
this.title = title;
this.age = age;
this.stress = stress;
}
}
Inheritance.
class Boss extends Employee {
public Boss(String name, String title, int age, int stress) {
super(name, title, age, stress);
}
}
Error Handling
Most used error handling is exceptions.
try {
throw new IOException();
} catch (IOException e) {
// Do something to handle the error or pass it on.
e.printStackTrace();
}
Debugging
Simples debugging tools are at System.out
. But you should seriously get an IDE with debugging tools like break points.
System.out.println("Hello World!");
System.out.print("This will not automatically add a line break!\n");