So you want to learn how to program Java? Well let's jump right in to this crash course.
First a few things to know. This is a crash course designed to get the basics of Java into your head. This will not be a comprehensive review of everything there is to know about Java. Also, we'll be dealing a lot with reading and deconstructing code, so make sure you have Eclipse (eclipse neon) installed along with the latest version of the JDK (8u121).
You can create a new projecy by opening eclipse and going to File -> New -> Java Project. This is where all of your source files (.java files that contain the source code) will reside. Name it CrashCourse
and click Finish. Now open up the CrashCourse
folder and right click on the src
folder which was automatically created. Create a New -> Package. The naming convention of Java packages is typically a reverse domain name followed by the projects name, so in my case it's com.gabrielsimmer.crashcourse
. You do not need to own the domain in the first hand (but it helps) and the package name is used when importing your package into other projects (we may touch on this). So moving right along.
Right click on your newly created package inside the src
folder (you may need to expand the folder with the small caret beside the folder), and create a New -> Class. This is going to be the main code file, so let's name it Main
(eclipse will automatically add the .java extension). You'll also want to make sure that public static void main(String[] args)
is checked under the Which methods would you like to create section
- this method is the method Java looks for when running your program so it knows what to actually execute. You do not require this for all of your files, just the main file you want to run.
You should end up with a file like this:
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Let's break it down a bit. package com.gabrielsimmer.crashcourse
is simple telling Java what package this file is a part of. public class Main {}
is declaring a new Class, which is the same as our file name - typically names don't matter (you could have called this file YourNameHere.java
and it would have been fine) however it's always a good idea to keep your code readable for future you or other people.
public static void main(String[] args) {}
is the function (a function is a group of operations that executes and usually returns a specific value based on the collection of operations) that Java looks for when executing your code. Anything in there is run.
Java's syntax is that of a fairly standard programming language. {}
encloses code inside functions so Java knows what is and isn't inside that function. ()
encloses what are called arguments
, which are values that can be passed to the inside function. We'll cover these in a little bit. //
is a comment, which the Java interpreter ignores completely but allows you to leave little notes to other programmers. /* */
also works, and allows you to do multi-line comments for larger notations.
If you run your program right now, you will get no output in the bottom console. Let's change that and add a simple built-in Java function that will print something out.
Inside the main()
function's braces, add the following (you can remove the comment):
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
System.out.println()
is a function that Java provides to print something to the console. System
is the package that you are referencing. out
is the class name that contains several functions related to "outputting" info. We just want to "print a line", so we use println()
, which is short hand for "print line". print()
also has the same result howevever it does not automatically insert a new line for you.
You may notice the little ;
at the end of the statement. This is an indicator the the Java interpreter that this is the end of the line. If it's not included your code will throw up an error. The error messages are usually pretty good at telling you where you've gone wrong, and eclipse will underline the offending line automatically.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert ";" to complete BlockStatements
at com.gabrielsimmer.crashcourse.Main.main(Main.java:6)
When you run the above code, you'll see in the Console "Hello World". Congrats! You've run your first Java program (and hopefully written it too, although I won't be mad if you copy-pasted).
Alright I know, I dislike math as well. But it's important in programming so let's get it out of the way. Let's take our file and add some math to it.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
System.out.println(3 + 4);
}
}
When we run the above code, we see the output is "7". Math is, at least for writing Java, pretty straightforward. +
and -
are for addition and subtraction, *
is for multiplication and /
is for division. Some of the more complex things, like sqaure roots and pi, are taken care of by the Math
Java package, which I won't cover here in depth however in eclipse if you simply type in Math.
it will offer a list of autocompletes.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(16)); // 4
}
}
But let's say we wanted to perform many operations at once on a number, and maybe do it multiple times. We could rewrite the operations each time, or we could write a function.
Variables help keep your code clean and can hold many different types of values depending on what you need. They are, in simple terms, what x is in math. An unknown until we give it a value. There are several types in Java, such as String
and int
. There will be a link at the end of this section to a breakdown of the types of variables. We will just cover String
and int
for now, as they are the most important ones.
So let's say we had a prefix for error messages, like ERROR:
. But we don't neccesarily want to type that out for each error message. so we store it in a variable. We create it using String errorprefix = "ERROR: "
. Notice a few things. One, we define what kind of variable this is with String
. This tell Java to expect a string of characters. Also notice how my variable's name is all lower case - Java is case sensitive, meaning that errorprefix
is not the same as Errorprefix
or ERRORPREFIX
. The =
sign is used for assigning values, not comparing, which we will get to. Lastly, notice how I included a space at the end of the string; since we'll be appending it to another message, we'll want that space to make sure we can read the message - Java does not automatically insert spaces.
So let's run this code.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
String errorprefix = "ERROR: ";
System.out.println(errorprefix + " This is an error.");
}
}
Woah woah, slow down. Where did that +
between the variable and the message come from?
Well +
is used for more than just adding numbers. It is also used for appending together strings, as we have done here. So the end result from this code is:
ERROR: This is an error.
Integers (int
) is pretty much the same, except it only deals with whole numbers. There is an upper limit to how much data this type can hold, however it is a silly large number and you're unlikely to hit it in this course. We define an intefer in the same way we do strings. int integer = 12;
assigns the value of 12 to integer
, so when we run the following we get 12
.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
int integer = 12;
System.out.println(integer);
}
}
Some important notes about variable names. Most importantly, they can not be names that Java already uses. So String static = "System"
will not work and will throw up an error. Variable names also can't start with a number, and it should not contain any special characters. It is also good to get into the habit of writing clear names for your variable names that are short, concsise, but also descriptive and we know what we're getting when we use it.
Comparing two values is essential for programming. It is not usual that we want to check if two things are the same. To accomplish this, we have if
, which check if something is true
or false
.
For example. if (12 == 12)
evaluates as true
, and the if statement will continue through it's code. However if (12 == 1)
evaluates as false
and the if statement will not run. Let's put this to practice.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
int integer = 12;
if (integer == 12){
System.out.println(integer);
}
if (integer == 13){
System.out.println("Why is this 13?");
}
}
}
So our final result in our console is 12
. The if (integer == 13){}
does not run because integer
is not 13. If integer
was neither 12 nor 13 neither print statement would be run.
What if we wanted to check if it WAS NOT 13? Well, we have a special way of doing that - !=
. This stands for "NOT EQUAL", and is basically the opposite of ==
. So if (integer != 13)
would be true if integer is, indeed, not 13.
We can also use things like >
, <
, <=
and >=
, which respectively mean "greater than", "less than", "less than OR equal to" and "greater than OR equal to".
What should we do if the if
statement is false? What should we do? Well, we can use the nifty else
statement. else
runs if the if
statement was not able to run.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
int integer = 12;
if (integer != 13){
System.out.println(integer);
} else {
System.out.println("It is 13!");
}
}
}
What we're doing here is checking if integer
is 13. If it IS NOT, that we just print out the number, If, however, it is, it runs through else
, so we get It is 13!
.
How about we don't want the number to be 14 either? Well we can add another if to the same block with ||
. ||
means OR, so in english our current statement is "if our variable is not 13, run this", and it becomes "if our variable is not 13 OR if it's not 14, run this". In theory you can have an unlimited number of ORs. Only one of the statements has to return true for the if block to run.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
int integer = 12;
if (integer != 13 || integer != 14){
System.out.println(integer);
} else {
System.out.println("It is 13!");
}
}
}
What about AND? We use &&
for that, which modifies it from "if our variable is not 13 AND if it's not 14, run this". So both statements have to evaluate as true before it can continue.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
int integer = 12;
if (integer != 13 && integer != 14){
System.out.println(integer);
} else {
System.out.println("It is 13!");
}
}
}
These two code examples do essentailly the same thing, however it is important to know how if{ } else { }
code blocks work, as they come up a lot. It is what we refer to as "logic".
Functions are the fun part of Java, and are basically a set of functions you want to call many times but don't want to have to rewrite, like calculating the volume of many objects or printing important messages to the console.
We used functions earlier - System.out.println()
is a function, and so is Math.sqrt()
. They are extremely useful.
Let's write our own that will calculate the volume of an object (length times width times height) named volume
. I personally tend to name functions with lowercase for the first word and then uppercase each proceeding word for better readability (so I could name it volumeCalculator
). We need to declare that this is a public
function, which means any file can call the function - this isn't important for this excersize, but when you get into using multiple files for larger projects it becomes important. Don't forget to add static
to your function, as this is a static function. We also want to tell Java we're returning an int
. This becomes public static int volume()
. We also want to accept some arguments so we know what numbers to multiple. We declare these like so public int volume(int length, int width, int height)
. Basically, we declared three int
variables, which are currently empty.
Then we fill in the rest of the function.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
// Empty for now
}
public static int volume(int length, int width, int height) {
int volume;
volume = length * width* height;
return volume;
}
}
On it's own, this code does basically nothing because we haven't called it. We call it using volume(number, number, number)
. Obviously, number
should be replaced with int
s.
Main.java
package com.gabrielsimmer.crashcourse;
public class Main {
public static void main(String[] args) {
int vol = volume(12, 12, 12);
System.out.println(vol); // 1728
}
public int volume(int length, int width, int height) {
int volume;
volume = length * width* height;
return volume;
}
}
Function go a lot more in depth, and help make sure you DRY - don't repeat yourself, which ends up making your code much messier.
Hopefully this crash course explains the basics of Java. If you have any questions, feel free to leave a comment below this gist or contact @gmem_.