Hello there! This article is created to help you dive in Java, the programming language that changed the world. This guide assumes you’ve already got some experience with programming, however I’ll try to explain step by step the first moves towards mastering (a bit) of Java. Taking in consideration English is not my mother tongue, I hope the language barrier will not be a problem.
Why does Java matter?
Perhaps you’ve already heard of Java. No doubt, it’s considered the most widely spread programming language nowadays. It’s the language that controls printers, faxes, TVs and even your phone! Java does that because of its cross-platform ability. ‘How’, you may ask? That’s done through Java’s Virtual Machines which translate the code you type into byte code, which the device understands. So, if you write an application in Java, you can be sure that all *NIX, Macintosh and Windows systems will understand it. What’s great about Java is that you’ll understand it too! It’s simple and easy to use.
Just for the fact, Java’s created in 1995 by Sun Microsystems (who were bought by Oracle in 2010). Make sure not to confuse Java with JavaScript - JavaScript is used by your browser to show messages, validation forms, etc.
Hint: type javascript:alert("Hello world!")
in your browser’s URL bar to see JavaScript in action.
Before beginning
After all the useless blabbering, let’s get our programming environment set up.
First of all you’ll need the Java Development Kit, or JDK. You can get it at the official Java website (here). Download it and install it in destionation of your personal choice. Of course, the most up-to-date version is suggested.
In this article I’ll be helping you to learn the fundamentals of Java’s Standart Edition (SE), but if you’re interested, you can read about Java ME (Micro Edition, used for mobile phones and other gadgets) in the Web.
You could use either one of those “professional” IDEs or type your code in a normal text editor. I personally write Java in Notepad++, but perhaps you’d like something more professional. If so, I could only guide you to use either Eclipse or NetBeans IDE. Google them if you wish!
A plus of those IDEs is that they’ll help you compile and run your code easier. If you decide to use a casual text editor, that’s what you’ll have to do in order to get your program running:
[list=1]
[] Save your code with the extension .java (keep reading for important information about programs' names in Java);
[] Open the Shell / Terminal / Command Prompt;
[] Go to the directory where you’ve saved your file;
[] Type javac nameOfFile.java
[*] Once the shell is finished compiling and if no errors were found, it’ll let you know by creating a new line. Now you can start your program using java nameOfFile
[/list]
First Java program
So let’s just begin with Java. Here’s a sample program to let you know what we’re talking about.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Java is special because everything in it is an object. That means that the code in Java is assigned into classes, and each of them has its own variables and methods (a function within a class).
As you can see, no libraries/header files are declared. Java needs no such for basic operations such as printing on screen, calculations, etc. However, we’ll later introduce more advanced libaries. Also parenthesis wrap the contents of a class/method, just as in most other programming languages, and every command ends with a semicolon ( ; ).
class HelloWorld {
This is the part where you “declare” your program. “class HelloWorld” is practically the same as “public class HelloWorld”. If you’re not too lazy, you could use the second one to start getting used to Object Orientated Programming. This class should have exactly the same name as your file’s name, otherwise an error will be produced during compilation and your program won’t run.
public static void main(String[] args) {
This is the main method of your class. It indicates your program where the instructions start at and what to read. Unfortunately you’ll have to remember that whole line (don’t worry though, after you read it a couple of times it’ll just stick in your mind). However, here’s a short explanation about the words used:
[list]
[] public - this means that your method is accessible from other classes of your program. The opposite to public is private - so if you changed that here, your program wouldn’t work as the method wouldn’t be accessible as you start your program.
[] static - static’s got no opposite. It basically tells the compiler “hey, the method/variable here is static, it’ll be the same for every instance of this object”.
[] void - one of the method types, indicating what kind of value it’ll return after it’s been executed. void means that it basically returns nothing.
[] main(String[] args) - the name of the method itself, along with the parameters given to it. As you advance through Java, you’ll learn how to pass arguments to your program through the command shell.
[/list]
System.out.println("Hello world!");
This is the statement all the fuss was about. The main idea behind it is to call the println method of the class System, passing an argument to it (in our case, the line you wish to have printed). If it’s a string or a number, it should be wrapped in quotation marks, or if it is a variable, you should only use the variable’s name. For example, if you had a variable named varName, you’d print it like this:
System.out.println(varName);
… Now a sudden interruption. I didn’t know where to place that, but I thought this’d be the best chapter. You should know that Java is case-sensitive, so you -have- to type “System” - not “system”, neither “sYsTeM” or anything else. The same goes for variables (explained later in this article).
Then the two lines of closing parenthesis follow.
Nota bene! System.out.println();
is a slight variation ofSystem.out.print();
The difference between those is that the latter just prints something on the screen, while the other one prints something on the screen and then moves the cursor onto the next line.
Variable types and assignment operator
It’s easy to work with variables with Java. Here’s a list of variable types:
[list]
[] int - a type to store integers, doubles will be stored after the decimal part is trimmed (for example, 4.75 would be 4 as an int, not 5);
NB! Variations of int are: [list][]byte (stores values from -128 to 127), []short (from -32768 to 32767) and []long (from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 - that’s pretty much, isn’t it?)[/list]
[] double, float - types for fractions. The only difference between those two is that double allows you to store more digits after the decimal point;
[] char - contains a single character. It’s important to note that Java uses Unicode characters instead of ASCII.
[] boolean - contains either true or false. Look back at it again - it isn’t named “bool”, but “boolean”.
[] String - The name speaks of itself; it’s all about keeping a string in the memory. Watch out, capital S!
[/list]
But how do we give each of those types some value? First of all, to declare a variable of some type, you have to type the type (funny English), followed by the name of the variable, which is to your choice, and then use the equals operator (=) and the value you wish the variable to have.
As in other programming/scripting languages, you have to watch out how you enter the value after the equals sign:
[list]
[] If you wish to assign a number (int or float/double) you only type in the number, e.g. 42;
[] If you wish to assign a character, you type the character wrapped in single quotation marks, e.g. ‘a’;
[] If you wish to assign a String, you type in the string wrapped in double quotation marks, e.g. “I love Java”;
[] If you wish to assing a variable the value of another variable, you type in the name of the variable, e.g. var1.
[/list]
For example:
String cows = "I have 5 cows";
So now that we know about types and initialization, let’s test those out:
public static void main(String[] args) {
int myNumber = 5;
double price = 3.99;
char h = 'x';
String robust = "I have ";
System.out.print(robust + myNumber + " bottles of milk, $")
System.out.println(price + "each. " + h);
}
}
The output will then be:
[quote=Output]I have 5 bottles of milk, $3.99 each. x[/quote]
Input
I bet that by now you’re already wondering how to get input with Java. That’s a little bit complicated, but be afraid not!
First of all, in the beginning of your code you’ll have to import a method from a library. I’ll dedicate a moment to talk about importing here.
All the functions you can use are a part of the Java API (Application Programming Interface). It contains about 3000 different functions and all of them are described in the Java API documentation which can be found here (You’ve downloaded JDK 7, right?). Everything in the API is written by volunteer programmers to make your experience easier. All you have to do is to look at the documentation and use whatever you’d like!
Now to importing. To be able to receive any input, we’ll need the following line in the beginning of our code:
import java.util.Scanner;
[list]
[] import - a keyword; needed for every import action in Java;
[] java.util.Scanner - tells the compiler that you’re importing the function Scanner from the class “util” of the Java API.
[/list]
Then, further in your program, you’ll have to create an instance of the class Scanner. Do you remember when I told you everything in Java was an object? Here’s where we should recall of that. Anyway, here’s the next step to getting input from the user, namely declaring a new instance of the class Scanner:
Scanner input = new Scanner(System.in);
You can only change the second word of the line (input), which you’ll later use to (finally) get the input you’ve always been wishing for. That line tells the compiler “What’s up, yo, take the class Scanner and create a new instance of it. Oh, and name it "input” for me, okay?“ - and so the compiler nods in agreement and does what you asked for.
Finally, you’ll have to use a new function to get the information you wanted. But halt! There’s one more thing you need to know. Depending on what kind of information you wish to get, you’ll need a different command to get it. Here’s a code snippet demonstrating the differences:
int number = input.nextInt();
double dec = input.nextDouble();
String sentence = input.next();
char character = input.findWithinHorizon(".", 0).charAt(0);
Alternatively, you could declare the variable without initializing it, and then give it a value.
Make note of the way you get a character from input. It’s a little bit harder because Java’s got no functions to directly grab a character from the input, so you’ll have to play a bit.
Conditions
Every programmer, at some point, falls in desperate need to use conditions. For example, whenever I have nothing better to do, I code a program to guess numbers. Here’s how one looks like in Java:
import java.util.Random;
public class GuessTheNumber {
public static void main(String[] args) {
int random = new Random().nextInt(10)+1;
Scanner keyboard = new Scanner(System.in);
System.out.print("I've just thought of a number between 1 and 10. Guess it: ");
int guess = keyboard.nextInt();
System.out.println("");
if (guess > 10 && guess < 1) System.out.println("You entered a number off limits!");
else if (guess == random) System.out.println("You guessed it!");
else System.out.println("I'm sorry, you guessed wrong!");
}
}```
Take a moment to look through the code. You can see a new package imported, java.util.Random, but I'll let you figure it out yourself. However, here's what's new: if, else if, else.
Here's where programming languages look like human speech the most. By using conditions, you command the computer to compute something (that's why it's called a computer), and, depending on the result, do something. Here's how it works:
doSomething;
}
else if (another condition that evaluates to true, but is different from the first) {
DoSomethingElse;
}
else {
DoAnotherThing;
} ```
Note that only one of those operators could be executed by the program - the one which is true. The ‘else’ statement does not need a condition, it only takes all the cases not fulfilled by the if/else if statements. As to the if/else if statements, it’s necessary to put the condition in a pair of small parenthesis and the code to be carried out in big parenthesis. However, if only one line follows the if/else if/else statement, you could skip the big parenthesis!
You should know that the following variations of the if/else if/else statements are possible:
[list]
[] If, without else if/else;
[] If and else if, without else;
[] If and multiple else if-s (and else);
[] If and else, without else if.[/list]
There is also a shortened version of the if/else, named the condition operator. It goes as follows:
(condition) ? doSomething : doSomethingElse;
Quickly explained, you place a condition between the brackets. If its result is true, the program’ll execute whatever you’ve placed before the colon. Else, if it is false, the program pays all its attention to doSomethingElse.
Let’s take for example 7 > 4. We want to store the bigger of those numbers in an already declared variable named number.
(7 > 4) ? number = 7 : number = 4;
As you can guess, the value of number after the fragment’s execution would be 7.
Condition control
This’ll be a short subchapter on how to control your conditions. The following table offers information about comparisons.
== Equals
!= Different than
Greater than
< Less than
= Greater than or equals
<= Less than or equals
Note that you can not compare strings using ==. You’ll have to use a method of the class String named equals. Here’s how to use it:
string1.equals(string2);
What you do here is access the method of the string1 object named equals and pass string2 as an argument, which returns true if the strings are the same, and false if not. You can use that with both String variables and on-the-go strings.
Loops
Sometimes in programming you need to do the same thing multiple times. Retyping the code is uneffective, and so programming languages’ve come up with loops loops loops.
The for loop
The for loop is used whenever you already know how many times you need to repeat the action. For example, if you need to go through an array (documented later in this article), you’d use the for loop. Here is the syntax:
for (iterator initialization; condition; iterator step) {
DoSomething;
}
Explanations:
[list]
[] iterator initialization - the for loops are powered by a variable called an iterator, which is kind of the command center of the loop. It is also an integer. Here you tell its starting value;
[] condition - every time the loop starts, it checks that condition. If it evaluates to true, the program proceeds to do the code in the brackets. Else, it exits the loop and carries on with your code;
[*] iterator step - after every passage through the loop the program looks at this part and performs an action on the iterator, changing its value, and thus moving the loop forward.[/list]
NB! Make sure to create your loops using logic. A slight mistake in your for loop may cause an infinite loop (that is, the loop being repeated again and again until the end of time, or until you terminate the program). If this is done, your program will be stuck at the loop, thus making it unusable.
Usually, programmers name their iterator i. However, it’s up to you what to call it.
Let’s get back to “Hello world”. Imagine there were a couple of words passing by you, and you wanted to greet them all. You’ll do this most quickly using the for loop:
public class HelloWorlds {
public static void main(String[] args) {
for (int i=0; i<5; i++) {
System.out.println("Hello world!");
}
}
}
This will cause the string “Hello world!” to be printed 5 times on the screen, each time on a new line.
Here’s something new: i++. This is short for i += 1, or for i = i + 1. What it does is complete the loop, then add 1 to the iterator value. A variation is ++i, which first adds 1 to the value of the iterator, then completes the whole code.
The while loop
However, sometimes you don’t know how many times you have to do something. Then you use the while loop. Its syntax is:
while (condition) {
doSomething;
}
Everything I have to say about the while loop is that it does something while the condition evaluates to true. Obviously, the while loop is no rocket science.
The do-while loop
The do while loop is almost the same as the while loop. The only difference is that the while loop checks the condition and then goes through the code, and the do-while loop first runs the code, then looks at the condition. It’s a technique that personally I mostly use in those pesky (but funny) DOS games. Anyway, here’s how a do-while loop looks like:
do {
doSomething;
} while (condition);
Arrays
Imagine that you had to store 10 integer variables, and then use them. You could name them a1, a2, a3… a10, but that’ll take a lot of your precious time, and will also be hard to manage. Here’s where arrays come to your help. Imagine that arrays are train compositions: It’s a single thing containing many “wagons”. Here’s how to declare an array in Java:
arrayType[] arrayName;
arrayName = new arrayType[numberOfPositions];
[list]
[] arrayName - the name of the array;
[] new - a keyword indicating that you’re creating a new object of arrayType;
[] arrayType - the type of the array. An array contains elements of only one type (int, double/float, char), so be careful with that;
[] numberOfPositions - indicate how many vacant positions your array will have. That number is also called an index.[/list]
Then, to write a value into an index of the array, you’d want to use:
arrayName[index] = value;
NB! In every programming/scripting language, the first array index is 0, not 1. Keep that in mind!
NB! Also, in every programming/scripting language the last index is numberOfPositions - 1. That’s because a single spot is used for the null-character, indicating the end of the array.
The same can be used to get the value of an array’s index:
System.out.println(arrayName[index]);
Conclusion
So let’s now combine our knowledges from this article to create an array with the numbers 1 to 10.
public class oneToTen {
public static void main(String[] args) {
int[] numbers;
numbers = new int[10];
for (int i=0; i<10; i++) {
numbers[i] = i;
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.print("Finished counting!");
}
}
After compiling and running the program, the otput of the program will be:
0 1 2 3 4 5 6 7 8 9
Finished counting!
And those were the fundamentals of Java. I hope this article’s been helpful and that now you’re much more confident with Java. Got a question? Message me or search the Internet!
However, this is only the beginning. There’s much more of Java to discover. Feeling gossip on how to create a GUI? Work on more advanced programs? Algorithms? Make Google your best friend or visit the Oracle website! Perhaps this should be your next step.