The Dirtiest Java Fundamentals: Unlock the Power of the Programming Language
If you want to nail the basics of Java — look no further than this article. Here is everything you need to know in order to get started with Java programming!
This was fun to go through and it was made using the Obsidian markdown note taking app / productivity app. The notes are really just for me to refer back to. They are messy but if you use ctrl+f you can probably find what you are looking for.
public class Main {
public void main () {
}
}
This is the most basic structure. Minimum is to have a ‘Main’ Class and within that, the ‘Main’ Method.
Classes
Are named with *P*ascal*N*aming*C*onvention — which is giving **every** first letter a capital.
Methods
Are named with camelNamingConvention — which gives every first letter after the first word a capital.
Main Method should always be static.
Execution
The process of how the code gets executed in the IDE (IntelliJ).
Source code (.java) -> Java Compiler -> Byte Code (.class)
The steps are basically COMPILATION & EXECUTION.
Compilation:
IntelliJ uses the Java Compiler to compile our code into Byte Code. The Java Compiler comes with the Java Development Kit (JDK) that we downloaded already.
Java Byte code is platform independent — meaning we can run it anywhere, MacOS, Windows, Linux — as long as the operating system has a Java Runtime Environment (JRE).
Java Runtime Environment (JRE)
Byte Code (.class) -> Java Virtual Machine (JVM) -> Native Code (Windows, Mac,…)
This has a software component, the Java Virtual Machine (JVM). This translates the byte code into the native code for the operating system so that the system you are running will understand it. Therefore we can write a Java program on a Windows machine and then execute it on Mac, Linux, etc that have this JRE.
-> C# and Python do the same.
Variables
Variables are used to temporarily store data in the computers memory.
int age = 30;
The ‘age’ (name of variable) is known as the identifier — Obviously because this is how we identify our variable.
The ‘=’ is called the assignment operator.
The ‘30’ is the initial value.
This whole first creation is called initialisation. Therefore we are initialising a variable, age.
Types
There are 2 categories of types:
- Primitve — for storing simple values
- Reference — for storing complex objects
Primitive:
byte
short
int -> can use an underscore to seperate digits for easy reading : 123_456_789
long -> can take number greater than 2 billion :
long viewsCount = 3_123_456_789L;
float -> example:
float price = 10.99F;
double
char -> Uses single quotes :
char letter = 'A';
boolean -> example:
boolean isEligible = false;
Reference:
A big difference between primitive and reference types is having to use the ‘new’ keyword. When declaring a REFERENCE we will need to use the ‘new’ keyword to allocate it some memory.
Date now = new Date();
Primitive vs Reference Types:
They are stored in memory differently.
Primitive :
byte x = 1;
byte y = x;
x = 2;
System.out.println(y);
**----------------**
** OUTPUT **
** y = 1 **
**----------------**
Primitive :
Point point1 = new Point(1,2);
Point point2 = point1;
point1.x = 4;
System.out.println(point2);
**-------------------------**
** OUTPUT **
** java.awt.Point[x=4,y=2] **
**-------------------------**
Rather than allocating a new space in memory like with the primitive type, reference types create a space in memory with an address and then another location where the name of the reference type just holds the address of the created space in memory.
As per the example below, we created a ‘new’ Point object in memory with the address = 100. This was originally linked to the identifier (name of variable) ‘point1’. When we look up ‘point1’ in memory, it doesn’t give us ‘Point{x=4, y=2}’ — which we assigned it — rather it gives us ‘100’. This is the address in memory where we stored ‘Point{x=4, y=2}’. Then we created ‘point2’ which linked to ‘point1’ but since it just references the address in memory — it again shows us ‘100’. This means that when we change either ‘point1’ or ‘point2’ — they will always BOTH be affected.
EXAMPLE IN CODE BELOW:
Point point1 = new Point(1,2);
Point point2 = point1;
point1.x = 4;
point2.y = 12;
System.out.println(point2);
System.out.println(point1);
**--------------------------**
** OUTPUT **
** java.awt.Point[x=4,y=12] **
** java.awt.Point[x=4,y=12] **
**--------------------------**
Parameters vs Arguments
Parameters are the holes that we define in our methods.
Arguments are the actual values we pass to these methods.
Arrays
We first need to instantiate an Array and since it is a Reference type we need to use the ‘new’ keyword. This is different to Python as we need to state what type we are going to be putting into our array and how large it must be.
We also have to convert the array to a string before we can print it nicely.
BELOW IS THE OLD SYNTAX
int [] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
String numString = Arrays.toString(numbers);
System.out.println(numString);
**-----------------**
** OUTPUT **
** [1, 2, 0, 0, 0] **
**-----------------**
Now we can see the NEW SYNTAX.
int [] numbers = { 2,3,4,5,6 };
System.out.println(Arrays.toString(numbers));
**-----------------**
** OUTPUT **
** [2, 3, 4, 5, 6] **
**-----------------**
NOTE -> Arrays have a fixed size. Therefore you cannot remove or add items
Constants
In order to create a constant we need to use the keyword ‘final’. Then once initialised, the constant will NOT be able to change later on.
For naming constants we use all capital letters.
final float PI = 3.14F;
Arithmetic Expressions
This is ridiculous — you will understand what is going on when reading the code. But damn this is a lot of extra work.
double result = (double)10/ (double)3;
System.out.println(result);
**-----------------**
** OUTPUT **
** 3.3333333333333 **
**-----------------**
This language is crazy
int x = 1;
int y = x++;
System.out.println(x);
System.out.println(y);
**-----------------**
** OUTPUT **
** 2 **
** 1 **
**-----------------**
BUT change the ‘++’ to a prefix
int x = 1;
int y = x++;
System.out.println(x);
System.out.println(y);
**-----------------**
** OUTPUT **
** 2 **
** 1 **
**-----------------**
Easier:
int x = 1;
x += 2;
x -= 1;
x *= 5;
System.out.println(x);
**-----------------**
** OUTPUT **
** 10 **
**-----------------**
If Statements
In Java we do not need the braces if there is only one statement.
int temp = 9;
if (temp > 30) {
System.out.println("Hot day");
System.out.println("Hot day");
}
else if (temp > 20)
System.out.println("Not Behd");
else {
System.out.println("cold bruv");
}
Simplifying If Statements
3 Ways of simplifications:
1:
int income = 90_000;
boolean hasHighIncome;
if (income > 100_000)
hasHighIncome = true;
else
hasHighIncome = false;
2:
int income = 90_000;
boolean hasHighIncome = false;
if (income > 100_000)
hasHighIncome = true;
3: Can use parentheses or not
Without parentheses
int income = 120_000;
boolean hasHighIncome = income > 100_000;
With parentheses
int income = 120_000;
boolean hasHighIncome = (income > 100_000);
Ternary Operator
Original :
int income = 120_000;
String className = "Economy";
if (income > 100_000)
className = "First";
Using Ternary :
int income = 120_000;
String className = income > 100_000 ? "First" : "Economy";
Switch Statements
Below is the difference between IF STATEMENTS and SWITCH STATEMENTS.
Pretty nifty stuff no lies.
String role = "admin";
switch (role) {
case "admin":
System.out.println("Bang! You are admin");
break; case "moderator":
System.out.println("You're a moderator");
break; default:
System.out.println("You are a guest");
}
if (role== "admin")
System.out.println("Bang! You are admin");
else if (role == "Mod")
System.out.println("You're a moderator");
else
System.out.println("You are a guest");
Loops
For Loops
Most basic implementation
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
While Loops
Basic implementation:
while (!input.equals("quit")) {
System.out.println("Input : ");
input = scanner.next().toLowerCase();
System.out.println(input);
}
Do While
With these loops we will always execute the code at least once — as the code only checks the condition after the code block. These are rarely used though.
do {
System.out.println("Input : ");
input = scanner.next().toLowerCase();
System.out.println(input);
} while (!input.equals("quit"));
For Each
This loop will go through for example a String Array, one item at a time. The initial ‘for loop’ is one way of doing this followed by the ‘for each’ method:
String[] fruits = {"Apple", "Mango", "Orange"};
for (int i = 0; i < fruits.length; i++)
System.out.println(fruits[i]);
for (String fruit : fruits)
System.out.println(fruit);
The limitations of this are that the ‘for each’ loop is forwards only — but we can do this with a ‘for loop’.
Continue & Break Statements
The break statement will completely break out of a loop.
while (!input.equals("quit")) {
System.out.println("Input : ");
input = scanner.next().toLowerCase();
if (input.equals("quit"))
break;
System.out.println(input);
}
The continue statement moves the control to the beginning of the loop
while (!input.equals("quit")) {
System.out.println("Input : ");
input = scanner.next().toLowerCase();
if (input.equals("pass"))
continue;
if (input.equals("quit"))
break;
System.out.println(input);
}
To execute forever, until user does X
We will use the while TRUE technique:
~ If we use this we MUST have a break statement in the loo somewhere
while (true) {
System.out.println("Input : ");
input = scanner.next().toLowerCase();
if (input.equals("pass"))
continue;
if (input.equals("quit"))
break;
System.out.println(input);
}
Methods
public static void main(String[] args) {
greetUser("Liam", "Loughnane");
}
public static void greetUser(String name, String lastName) {
System.out.println("Hello " + name + " " + lastName );
}
Void means it does NOT return anything.
If we want to make it return something then we have to state what type to return.
public static void main(String[] args) {
String myName = greetUser("Liam", "Loughnane");
System.out.println(myName);
}
public static String greetUser(String name, String lastName) {
return "Hello " + name + " " + lastName;
}
Refactoring
This means changing the structure of our code without changing its’ behaviour.
Types of errors
Compile-time errors
These occur when we don’t follow the correct syntax — often referred to as syntax errorsRun-time errors
Usually quite easy to find and fix due to your IDE telling you where they are and what’s up.
What to do when you don’t understand the error?
You’ve probably heard the saying ‘google is your friend’ — well that is definitely true! Search the exact error you get with google and see what comes up. More often than not you will be able to find a link to stackoverflow where someone else has had the same error as you. There, you will definitely be able to find the fix and if not the fix, some clarification that will help you to fix your specific issue.
Deploying Applications
Once you have finished with your Java program and want someone else to be use it — you will need to ‘package’ your code into a jar file. Jar is short for Java Archive which is a package file format that will contain all your code — nicely packaged for distribution.
The catch is that the person you want to use your program, must have a Java Runtime Environment (JRE) installed on their computer.
Process :
File -> Project Structure -> Artifacts -> + -> JAR -> From Modules… -> Select Main class -> OK -> OK
Build -> Build Artifacts -> Build
In Project panel -> out -> artifacts -> … -> right click jar file -> open in -> terminal
Once the terminal window has popped up, you can use the ‘ls’ command to list what is in the directory. You will be able to see your ‘HelloWorld.jar’ file just chilling there. To run the file you must start with the ‘java’ command which will invoke the Java Virtual Machine followed by a switch ‘-jar’ followed by the name of the jar file you are calling.
java -jar HelloWorld.jar
Side Notes
An object is an instance of a class.
With classes we can use the dot notation to see what methods it has — similarly to PythonStrings are Reference Types — don’t need to use the ‘new’ keyword
Any methods that modify a STRING will always return a NEW object rather than modify the old STRING.Public means it can be called from outside of the class
Static means it belongs to a class as opposed to an object
Final thoughts
Took me quite some time to write up all the notes — I know they are messy but they initially were not meant for the public. I thought I would post them just for in case someone else can get some use out of them 🤙🏼