Prerequisites

Introduction

Hey there and welcome to this course on Java, a powerful and super-popular programming language!

Before we get cracking, let's see if we can display the message "Hello world!".

String greeting = "Hello";
System.out.print(greeting + " world");

//Output Below

Hello world!

Sweet! Together, we just wrote a Java program that displays a nice greeting in the console. Let's explore what we actually did there!

Variables

We created a variable that we called greeting and gave it the word "Hello" as a value.

Variables are containers that help us remember information, like a friend's birthday, for later.

String birthday = "1970/1/1";
System.out.print(birthday);

//Output Below

1970/1/1

Great! Through the variable's name, we can use the information that it contains.

Source code

Java programs are written in source code that contains detailed instructions for the computer to follow.

Let's see if we can display another message with this piece of source code.

String love = "I love.. ";
String thing = "carpets";
System.out.print(love + thing);

//Output Below

I love.. carpets

With System.out.print(), we can display almost anything in the console; we just need to put it inside the parentheses.

Pssst: know-it-alls like me call print() a method.

Strings and numbers

Variables can remember words, which we call strings, but also numbers.

String myString = "4";
int myNumber = 4;

Sweet! Now myString contains the string "4" and myNumber the number 4.

We create string variables with the word String and put their values in quotation marks. Numbers use different words and no quotation marks.

Types of numbers

Numbers come in various types: while integers are whole numbers, doubles are numbers with a decimal place.

int myInteger = 4;
double myDouble = 4.0;

Great! We create integer variables with the intkeyword and use double to create variables for doubles, which are numbers with a decimal place.

The type of number we need to use depends on the information we want to store.

Arithmetic

It might not be everybody's thing but we can also do some arithmetic with Java.

int term1 = 18;
int term2 = 3;
int result = term1 + term2;
System.out.print(result);

//Output Below

21

Nice! We can do basic arithmetic operations with the +, -, *, and / signs.

Psst: the print() method works with numbers just like it does with strings.

Types

If we don't have a value for a variable in the very beginning, we can create it without assigning anything to it. We do, however, have to set its type.

String myString;
int myInteger;
double myDouble;

Spot on! myDouble is now declared and set to hold double-type values.

Psst: have you noticed how every line we wrote so far ended with a semicolon? That's how we mark the end of a statement.

Development tools

This is a great time to get Eclipse or NetBeans. These are development tools for your computer that allow you to write and run Java programs.

Done? Open the tool and create a Java project. If the project doesn't come with a class, create a class (File, New, Class). If possible, create a main method with it.

public class SpaceAdventure {
 public static void main 
 (String[] args) {
  // Write your code here!
 }
}

Hopefully, your project looks somewhat like this. By clicking the play/run button in the tool, you can assemble and run your Java program.

Psst: after //, we can put comments to help us take notes and understand what the code does.

Space adventure #1

At the end of every chapter, we'll go on an adventure with "Colonel Samantha" and create code snippets around her travels.

Create a Java project with a default class. Create variables that store "Colonel" and "Samantha", combine them with a space in between and display the combination.

public class SpaceAdventure {
 public static void main 
 (String[] args) {
  String s1 = "Colonel";
  String s2 = "Samantha";
  String captain = s1 + " " + s2;
  System.out.print(captain);
 }
}

Together with "Sam", we'll explore the Java universe. Let's go to infinity and beyond!

Main?

In brief, a Java program starts with a main() method. Soon, we'll take a close look at main(); for now, it suffices to know that this is the place for your code.

public class SpaceAdventure {
 public static void main
 (String[] args) {
  String s1 = "Colonel";
  String s2 = "Samantha";
  String captain = s1 + " " + s2;
  System.out.print(captain);
 }
}

Perfect! While these words and symbols might look strange in the beginning, we'll get the hang of them in no time!

Compendium

Look how far we've come! We've created variables, used different types, combined string values and used print(). Also, we did a bit of arithmetic.

int someNumber = 42;
int anotherNumber = someNumber + 5;
String someString;
String myName = "Johnny";
someString = "Here's " + myName;
System.out.print(someString);

//Output Below

Here's Johnny

I can tell that we're going to be friends.

Declarations

Every variable has to be declared before we can use it, right? A common way to do this is to use a type and a name.

What type might be a good type choice for a variable called myNumber?

int myNumber;

Sweet, we've successfully declared myNumber! Still, if we want to use it, we have to give, or assign, a value to it.

Initializing

We use the = sign to assign values to variables. Whenever a variable gets its initial value, we're said to initialize it.

int mySpeed;
mySpeed = 88; // miles per hour
double myPower = 1.21; // gigawatts

Nice! We can initialize a variable any time after we've declared it but we can also declare and initialize it in a single step.

Type safety

Once we've declared a variable, its type is permanent, it's set in stone.

int targetSpeed = 88;
int currentSpeed = 21;
currentSpeed = 1;

Of course! currentSpeed is an int-type variable. Because of type safety, we can't assign anything to it that isn't an integer value.

The importance of initializing

It's really important that we initialize a variable before we attempt to use it.

int targetSpeed = 88;
int currentSpeed;
System.out.print(targetSpeed);

//Output Below

88

Yass! Because we haven't initialized currentSpeed, we can only use targetSpeed.

Incrementing

Let's look at a few ways of incrementing a number by 1.

int myYear = 1985;
myYear = myYear + 1;
System.out.print(myYear);

Exactly! We just used the + sign to add 1 to myYear. We then reassigned myYear to itself and printed it out.

Shorthand

What if there was a shorter way of incrementing by 1?

int myYear = 1985;
myYear++;
System.out.print(myYear);

//Output Below

1986

Yass! The ++ operator automatically increments the value by 1 and reassigns it back to itself. Easy peasy.

Another shorthand

If you want to add or subtract a value other than 1, there's another shorthand for that.

int myYear = 1985;
myYear -= 30;
System.out.print(myYear);

//Output Below

1955

Nice! We can also use '+=', *=, and /= operators for addition, multiplication, and division assignments.

Null

Even though null stands for no value, it can be assigned to reference types like any other value.

String myName = null;
System.out.print(myName);

//Output Below

null

Sweet! Reference types like String can be null whereas primitive types like int and double can't.

Psst: in most cases, we don't want a variable to be null. Still, it's important to know what null means because we'll encounter it from time to time.

Space adventure #2

"Colonel Samantha" needs to keep track of the number of planets she visits. Whoa, there's another one .. quick, let's help her count!

Declare and initialize a variable with 0. Increase it by 1 and add 2 to it. Finally, display the count in a nice sentence in the console.

Nice! That way, "Sam" doesn't have to do all the counting herself.

int planetCount = 0;
planetCount++;
planetCount += 2;
System.out.print("Sam has seen "
 + planetCount + " planets");

//Output Below

Sam has seen 3 planets

Psst: don't forget to put these snippets inside your main() method!

True or false?

There is a primitive type in Java that tells the truth and nothing but the truth. It's called boolean.

boolean truth;
truth = true;

Exactly! A boolean-type value can only be true or false.

Greater or less

Let's use a boolean to find out if 5 is greater than 3!

boolean myBoolean = 5 > 3;
System.out.print(myBoolean);

//Output Below

true

Whenever we compare numbers, the result can only be true or false and stored in a boolean-type variable.

Greater or equal

Is 5 greater than or equal to myNumber?

int myNumber = 6;
boolean myBoolean = 5 >= myNumber;
System.out.print(myBoolean);

//Output Below

false

Swee-heet! Using >=, we can check if a number is greater than or equal to another number. Conversely, we can use <= for less-than-or-equal-to comparisons.

Equality

Let's hear it for equality! Is myNumber equal to 6?

int myNumber = 6;
boolean myBoolean = myNumber == 6;
System.out.print(myBoolean);

//Output Below

true

Boom! Careful, though: while == is used to compare things, = is used to assign values to variables.

Inequality

Okay, this is the last time that I'll bug you: is 5 not equal to 6?

boolean myBoolean = 5 != 6;
System.out.print(myBoolean);

//Output Below

true

See that? '!=' is used to check whether two values are not equal. If that's the case, the result is true; otherwise it's false. This might still feel a bit odd but you'll get the hang of it!

The not operator

Alright, if you're a fan of not jokes and opposite days, the not operator might be for you.

boolean theTruth = true;
boolean whatWayneSaid;
whatWayneSaid = !theTruth;
System.out.print(whatWayneSaid);

//Output Below

false

Party time! By placing a ! sign before theTruth, we're inverting its value to make whatWayneSaid the opposite of theTruth.

And

The logical and takes two boolean-type values and is only true if both of them are true.

boolean b1 = true;
boolean b2 = 3 < 137;
boolean result = b1 && b2;
System.out.print(result);

//Output Below

true

Sweet! The result is true because b1 and b2 are true; if one or both of them would have been false, the result would have been false as well.

Or

The logical or is kind of similar but not as stringent. It returns true as soon as one out of two boolean-type values is true.

boolean b1 = false;
boolean b2 = true;
boolean result = b1 || b2;
System.out.print(result);

//Output Below

true

Yup! The result is true as long as one of the booleans is true.

Space adventure #3

"Colonel Samantha" wants her spaceship to jump to hyperspeed, which is exciting but resource-intensive.

Create a boolean that's true if a tank variable is at least 10 and a boolean that's false if a water variable drops below 50. Finally, create a boolean that's only true if both values are true.

int tank = 10;
int water = 74;
boolean b1 = tank >= 10;
boolean b2 = water > 50;
boolean ok = b1 && b2;

See you on the other side, "Sam"!

Compendium

A boolean-type variable can only be true or false. Whenever we compare values, we get a boolean that we can store in a variable of that type.

boolean b1;
b1 = 5 < 137;
boolean b2 = 8 > 137;
boolean result = b1 && b2;
System.out.print(result);

//Output Below

false

Booleans are an essential component of Java, and indeed, programming in general.

What if?

What if we want to execute a code snippet only if a specific condition is met?

int myNumber = 6;
boolean myBoolean = myNumber == 6;
if (myBoolean) {
 System.out.print("Yes!");
}

//Output Below

Yes!

Sweet! We can use an if statement in combination with a boolean, which executes the code in the braces only if the boolean is true.

What else?

What if we want to execute a different code snippet in case the condition isn't met?

boolean myBoolean = 5 > 6;
if (myBoolean) {
 System.out.print("Big");
} else {
 System.out.print("Bang");
}

//Output Below

Bang

Bazinga! We can add an else clause to the code. Because myBoolean is false, the else block is executed instead of the if block.

No boolean needed

We can put the condition within an if clause without having to create a variable. Let's try to trigger print()!

double pi = 3.14159;
if (pi != 3.0) {
 System.out.print("Triggered!");
} 

//Output Below

Triggered!

Good stuff! Often times, it's easier to read if statements that compare within the clause.

Else if

So-called else if blocks are only executed if the preceding if clause is false and its own condition is true.

What condition might need to be true for the else if block to execute?

int x = 5;
if (x == 6) {
 System.out.print("x is 6");
} else if (x == 5) {
 System.out.print("x is 5");
} else {
 System.out.print("Not 5, not 6");
}

//Output Below

x is 5

See that? We can add as many else if clauses as we want, but we can't have multiple else clauses.

Nesting

Here's an if clause within an if clause. Once again, let's try to trigger print()!

int x = -3;
if (x < 5) {
 if (x > -5) {
  System.out.print("Triggered!");
 }
}

//Output Below

Triggered!

Great job! At times, these nested if statements are very useful; especially, if we add an else clause to the nested if clause.

String comparisons

Strings aren't quite as easy to compare as primitive types because they're objects.

That's why we need to use a string's equals() method to check if it's equal to another string.

String a = "Orange";
String b = "Apple";
boolean myBoolean = a.equals(b);
System.out.print(myBoolean);

//Output Below

false

See that? We'll get back to objects and Strings a little later; in the meantime, let's not use == to compare strings!

String comparisons II

Let's see another example.

String a = "Orange";
String b = "Orange";
boolean myBoolean = a.equals(b);
System.out.print(myBoolean);

//Output Below

true

Exactly! Even for cases where one letter is in lowercase, the equals() method would returned false because the words aren't identical. 

Null

So, string-type variables can either have a value or be null. What if we want to make sure that such a variable isn't null before we use it?

String a = null;
String b = "Apple";
if (a == null) {
 System.out.print("Stay back!");
} else {
 System.out.print(a.equals(b));
}

//Output Below

Stay back!

Woop woop! This is a safety measure to prevent the program from crashing if a is null. Safety first!

Logical operators

Let's use the logical and to trigger print()!

int x = -3;
if (x < 5 && x > -5) {
 System.out.print("Triggered!");
}

//Output Below

Triggered!

Awesome! Using the logical and, we've simplified the nested if example.

Space adventure #4

"Colonel Samantha" is traveling a lot of planets these days. In fact, she's about halfway through achieving her goal of 400 planets.

Create planetCount and goal variables. Check if she has reached her goal: if so, compliment her; otherwise, tell her how many planets she's got left.

You're closing in, "Sam"!

int goal = 400;
int planetCount = 201;
if (planetCount >= goal) {
 System.out.print("Did it!");
} else {
 int left = goal - planetCount;
 System.out.print(left + " to go!");
}

//Output Below

199 to go!

Compendium

The concept of if, else and else if is very simple. We only need a boolean-type value and the if statement works like a charm.

int myVolume = 11;
String output;
if (myVolume < 11) {
 output = "Is it on?";
} else if (myVolume == 11) {
 output = "These go to 11.";
} else {
 output = "No way!";
}
System.out.print(output);

//Output Below

These go to 11.

Sometimes you need that extra push, you know.

Hello, array!

An array is a container for a fixed number of values of a single type.

Let's create an array that we'll use to hold a bunch of names!

String[] names;

Perfect! We declare arrays just like regular variables except. The only difference is that we put brackets after the type.

Initializing

So, we have an array. However, before we can use it, we need to initialize it with the new keyword.

Let's initialize names and make it suitable for up to ten values, or elements!

String[] names;
names = new String[10];

Sweet! We can initialize an array with the new keyword, followed by the array's type and its capacity in brackets.

A shortcut

That said, there's a shortcut to declare, initialize and add values to arrays in a single step.

String[] names = { "See", "how", "short", "this", "is" };
String output;
output = Arrays.toString(names);
System.out.print(output);

//Output Below

[See, how, short, this, is]

See that? If we know which elements an array is supposed to hold, we can simply assign them in braces and skip the new keyword.

Psst: Arrays.toString() is a utility method that converts an array into a single String-type value.

Length

Also, we can use the length property to determine the size of an array.

String[] names = { "Jack", "John",
 "Kate", "Rose" };
System.out.print(names.length);

//Output Below

4

Sweet! Living is easy with arrays.

Accessing

Thanks to indices, accessing elements in an array is pretty straight-forward.

String[] names = { "Jack", "John",
 "Kate", "Rose" };
String name = names[0];
System.out.print(name);

//Output Below

Jack

That's it! We can access an element by putting its position, or index, in brackets after the array's name.

Psst: arrays are zero-based, which means the first element has an index of 0, the second an index of 1 and so on.

Empty?

An array is empty when it's initialized but doesn't contain any elements.

int[] innocents = {};
boolean empty;
empty = innocents.length == 0;
if (empty) {
 System.out.print("No innocents");
}

//Output Below

No innocents

Sweet! I guess everyone has some skeletons in their closet.

Replacing

Oh noes, it seems like We made a mistake when We initialized numbers. Let's replace the element that's out of place.

int[] numbers = { 1, 2, 3, 1, 5 };
numbers[3] = 4;
String output;
output = Arrays.toString(numbers);
System.out.print(output);

//Output Below

[1, 2, 3, 4, 5]

Good stuff! As long as we remember that arrays are zero-based, replacing an element is easy.

Space adventure #5

It looks like "Sam" has traveled every single planet in her home solar system. Now what?

Create an array for the five solar systems in her galaxy and a systemCount variable that tracks the systems she visits. Select the system at the (zero-based) position of systemCount and display it.

Full speed ahead to the "Wa" system!

int systemCount = 1;
String[] systems = { "Pagh", "Wa",
 "Cha", "Wej" };
systemCount++;
String s = systems[systemCount - 1];
String output = "Sam -> " + s;
System.out.print(output);

//Output Below

Sam -> Wa

Compendium

Again, an array is a container that holds a fixed number of values of a single type.

int[] numbers;
numbers = { 0, 8, 15, 16, 23, 42 };
numbers[0] = 4;
System.out.print(numbers[5]);

//Output Below

42

Now that we know about arrays, we should never get lost with multiple values again.

Combining strings

We've already combined a couple of strings in the earlier lessons. Do you remember?

String pt1 = "When Harry ";
String pt2 = "met Sally";
String result = pt1 + pt2;
System.out.print(result);

//Output Below

When Harry met Sally

Nice! We use the + sign to combine multiple strings.

Counting

Sometimes it's useful to know the length of a string.

String myString = "AA+";
int length = myString.length();
String output = "That's " + length;
System.out.print(output);

//Output Below

That's 3

Woop woop! A string's length() method returns the number of characters in it.

Psst: an array's length property is, well, a property and not a method.

Empty?

At other times, it's nice to know if a String-type variable is empty.

String myString = "";
if (myString.isEmpty()) {
 System.out.print("It's empty!");
}

//Output Below

It's empty!

Sweet! isEmpty() returns true if the the string is, well, empty.

Psst: another way to check if a string is empty is by using the length() method on the string to check if it equals 0.

String creation

So far, we've created strings by initializing them with a value in quotation marks. There's another way, though, and it uses the new keyword.

String a = "";
String b = new String();
System.out.print(a.equals(b));

//Output Below

true

See that? a and b both hold an empty string. String() is called a constructor, a concept about which we'll talk some more when we dive into objects.

Characters and strings

A string is an ordered collection of characters. If we need a variable to hold a single character and nothing more, we can make use of the char type.

char myChar = 'a';
String myString = "a";

Sweet! We write char-type values in between single quotation marks so they're not considered as strings.

Combining types

Also, we can combine strings and characters into a single String-type value.

char myChar = 'a';
String myString = "a";
myString += myChar;
System.out.print(myString);

//Output Below

aa

Easy-peasy! Just like we combine strings with the + and += operators, we can add char-type values in the same way.

Psst: we can neither add a string to a character nor can we combine two characters in a single char-type variable.

Another way

That said, there's a method that offers a very similar functionality.

String a = "Java is ";
String b = a.concat("rad!");
System.out.print(b);

//Output Below

Java is rad!

Great! It's up to us if we use concat() or the + and += operators to combine strings.

Joining

Joining elements of a char-type array into a single-word string is also pretty straight-forward.

char[] myChars = { 'B', 'o', 'b' };
String myString = new String(myChars);
System.out.print(myString);

//Output Below

Bob

Sweet! We can pass the character array to the constructor of the String class.

Prefixes

We can pull off some great tricks with strings. For example, we can check if a string starts with a specific String-type value.

String idol = "Mrs. Hopper";
if (idol.startsWith("Mrs.")) {
 String output = "Hello ma'am!";
 System.out.print(output);
} else if (idol.startsWith("Mr.")) {
 String output = "Hello sir!";
 System.out.print(output);
}

//Output Below

Hello ma'am!

Wahey! startsWith() returns true or false, based on whether or not the specified String-type value is a so-called prefix of the string.

Psst: Grace Hopper developed the first compiler for a computer programming language.

Suffixes

We can also find out if a string ends with a specific value or, in other words, has a specific suffix.

String idol = "Maria Sklodowska";
if (idol.endsWith("a")) {
 String output = "Hello ma'am!";
 System.out.print(output);
} else {
 String output = "Hello sir!";
 System.out.print(output);
}

//Output Below

Hello ma'am!

Great! Unsurprisingly, endsWith() returns true or false, based on whether or not the specified String-type value is a suffix of the string.

Psst: Maria Sklodowska, who is better known as Marie Curie, won two Nobel Prizes for her pioneering work on radioactivity.

Space adventure #6

"Sam" is still exploring the "Wa" system. Word is that there are some very inhospitable planets in the system that have a common prefix: "Qab".

Create a planets array with a bunch of planet names. Pick a planet from the array to go to but make sure that it's hospitable before "Sam" goes there.

String[] planets = { "Qab-Boreth",
 "H'atoria", "Khitomer", "Morska",
 "Qab-Organia", "Praxis" };
String p = planets[5" class="number];
if (p.startsWith("Qab")) {
 System.out.print("Sam -> " + p);
} else {
 System.out.print("Inhospitable");
}

//Output Below

Inhospitable

Let's pick a different planet, "Sam"!

Compendium

A string is an ordered collection of characters. Because strings are objects, they have methods that can pull off very useful tricks.

String o = "Java";
o += " and me ";
o = o.concat("got friends");
if (!o.isEmpty()
 && o.startsWith("Java")) {
 int count = o.length();
 System.out.print(o);
}

//Output Below

Java and me got friends

Strings are easy and fun to use, right?

Declaring

Often times we don't really know how many items an array will have down the line. If that's the case, it might be a good idea to use an object called ArrayList.

ArrayList names;

In essence, ArrayLists are variable-length arrays for objects.

Initializing

Like strings, ArrayLists are objects, which means that we need to use their constructor to initialize them.

ArrayList names;
names = new ArrayList();

Sweet! As always, we need to initialize an ArrayList before we can play with it.

Type safety

Often times it's a good idea to restrict an ArrayList to take nothing but values of a single type.

ArrayList<String> names;
names = new ArrayList<>();

Great! Now we have a type-safe ArrayList, which means that every element has to be a String-type value.

Psst: we can but don't have to repeat the type restriction when we call the constructor.

Adding

Let's add some values to the ArrayList!

ArrayList<String> names;
names = new ArrayList<>();
names.add("Jack");
names.add("John");
String s = String.join(",", names);
System.out.print(s);

//Output Below

Jack,John

See that? With add(), we can add as many values at the end of an ArrayList as we want.

Psst: String.join() is another utility method that joins an ArrayList's values into a single string, separating them with another String-type value.

Getting

Retrieving, or getting, an element of an ArrayList is very straight-forward. Why? Because there's a method that does just that.

ArrayList<String> names;
names = new ArrayList<>();
names.add("Jack");
names.add("Kate");
String name = names.get(0);
System.out.print(name);

//Output Below

Jack

Nice! Just like arrays, ArrayLists are zero-based: the first element has an index of 0, the second has an index of 1 and so on.

Setting

Oh noes, it seems like We made a typo when We added "John" to names. Let's do ourselves a favor and replace the element.

ArrayList<String> names;
names = new ArrayList<>();
names.add("Jack");
names.add("Jhn");
names.add("Kate");
names.add("Rose");
names.set(1, "John");

String s = String.join(",", names);
System.out.print(s);

//Output Below

Jack,John,Kate,Rose

Good stuff! As long as we remember that ArrayLists are zero-based, replacing (or setting) values with set() is easy.

Removing

Whoops! This time, We added "John" twice. Let's remove one of the duplicates.

ArrayList<String> names;
names = new ArrayList<>();
names.add("Jack");
names.add("John");
names.add("Kate");
names.add("John");
names.add("Rose");
names.remove(3);

String s = String.join(",", names);
System.out.print(s);

//Output Below

Jack,John,Kate,Rose

Perfect! Unsurprisingly, remove(), well, removes an element at the specified index.

Empty?

ArrayLists have methods that determine their size and tell us if they're empty. Does that sound familiar?

ArrayList<String> innocents;
innocents = new ArrayList<>();

boolean e1 = innocents.isEmpty();
boolean e2 = innocents.size() == 0;

if (e1 && e2) {
 System.out.print("No innocents");
}

//Output Below

No innocents

Great! As with arrays, there are two ways to check if an ArrayList is empty.

Shape-shifting

Okay, here's the last trick of ArrayLists that we're going to explore for now: converting or, how some would say, shape-shifting.

ArrayList<String> names1;
names1 = new ArrayList<>();
names1.add("Jack");
names1.add("John");
names1.add("Kate");
 names1.add("Rose");
String[] names2 = names1.toArray() ;

String s = Arrays.toString(names2);
System.out.print(s);

//Output Below

[Jack,John,Kate,Rose]

Nice! We can use toArray() to convert an ArrayList into a regular array.

Psst: again, Arrays.toString() converts an array into a printable string.

Space adventure #7

There are a bunch of items that "Sam" needs before she can leave the "Wa" system. She got a pass but still needs a replacement control stick and fuel.

Create a list with the mentioned elements, tick off those that "Sam" already took care of by removing them and display the remaining elements.

Sweet! Only two items left to take care of!

ArrayList<String> items;
items = new ArrayList<>();
items.add("pass");
items.add("control stick");
items.add("fuel");
items.remove(0); // Got a pass!" class="comment

String s = String.join(", ", items);
System.out.print(s);

//Output Below

control stick, fuel

Declaring

HashMaps are collections of key-value pairs. In a way, they're like dictionaries: every key points to a value.

HashMap<String, String> map;

See that? We've created a HashMap that requires String-type keys and values.

Psst: HashMaps can be set to take whatever object we want, but we can't make it accept a primitive type.

Initializing

So, we've declared a HashMap and defined that it should take string as keys and values. Now what?

HashMap<String, String> map;
map = new HashMap<>();

That's right! We need to initialize the HashMap with a very ArrayList-like syntax.

Type inference

When we initialize a HashMap, we can but don't have to repeat the type of its key-value pairs.

HashMap<Integer, String> map; 
map = new HashMap<>();

<> is called the diamond. Using it, we don't have to re-specify our HashMap's types upon initialization. That's called type inference.

Psst: we're using Integer, an object that contains an int-type value, because HashMaps only take objects.

Adding

Let's add some key-value pairs to the HashMap!

HashMap<Integer, String> map;
map = new HashMap<>();
map.put(23, "Michael");

Nice! put() requires a key and a value, which get added to the HashMap.

Counting

Let's count the key-value pairs in the HashMap, shall we?

HashMap<String, String> team;
team = new HashMap<>();
team.put("Ron", "News");
team.put("Brick", "Weather");
System.out.print(team.size());

//Output Below

2

Good stuff! size() is a simple method that returns the number of key-value pairs in a HashMap.

Accessing

Accessing values of a HashMap is pretty straight-forward.

HashMap<Integer, String> map;
map = new HashMap<>();
map.put(23, "Michael");
map.put(91, "Dennis");

String value = map.get(23);
System.out.print(value);

//Output Below

Michael

Nice job! If the key is valid, get() returns the value for a given key.

Empty?

Of course a HashMap can also tell us whether it's empty or not.

HashMap<Integer, String> map;
map = new HashMap<>();
boolean empty = map.isEmpty();
if (empty) {
 String s = "HashMap is empty!";
 System.out.print(s);
}

//Output Below

HashMap is empty!

Sweet! isEmpty() returns a boolean that's true if the HashMap is empty and false if it's not.

Removing

Sometimes we want to get rid of values. Let's try to remove something!

HashMap<Integer, String> map;
map = new HashMap<>();
map.put(23, "Michael");
map.put(91, "Dennis");

map.remove(23);
System.out.print(map);

//Output Below

{91=Dennis}

Yass! In order to get rid of values with remove(), we need to have a key that we can pass to the method.

Updating

Replacing or updating a value is just as easy as adding something.

HashMap<Integer, String> map;
map = new HashMap<>();
map.put(23, "Scottie");
map.put(91, "Dennis");

map.put(23, "Scottie");
System.out.print(map);

//Output Below

{23=Scottie, 91=Dennis}

In fact, it's the same thing.

Space adventure #7

"Sam" has a hard time remembering her crew members by their full names. She can always recall their nicknames, though.

Create a HashMap that uses nicknames as keys to the real names of the crew members. Then pick a name and display it.

"Sam" will not be embarrassed again.

HashMap<String, String> members;
members = new HashMap<>();
members.put("Jack", "Jonathan");
members.put("Cam", "Cameron");
members.put("Hank", "Henry");
members.put("Chuck", "Charles");
String member = members.get("Cam");
System.out.print(member);

//Output Below

Cameron

Staying in the loop

Loops are magical things: they allow us to execute blocks of code for as often as we want.

One of them, the while loop, repeats while a boolean-type condition is true.

int counter = 1;
while (counter < 4) {
 counter++;
}
System.out.print(counter);

//Output Below

4

Boom! The code just runs and runs while the counter variable is less than 4. In this case, it runs 3 cycles, adding up to 4.

Psst: we've got to be sure that the condition becomes false at some point; otherwise it'd keep running and running. Or crash.

Do while

The do while loop works in the same way, except that the code block gets executed at least one time before the condition is checked.

int counter = 5;
do {
 counter++;
} while (counter < 5);
System.out.print(counter);

//Output Below

6

Nice job! We only check the condition of counter being less than 5 at the end, so we're able to increment the number at least once.

Psst: a while loop would see the condition at the beginning and not execute the code. At times, this little difference can be really useful.

Until when?

Let's take a closer look at the previous example. Let's make the output be 7.

int counter = 5;
do {
 counter++;
} while (counter < 7);
System.out.print(counter);

//Output Below

7

You're fantastic! This case allows the do while loop to increment counter twice in total before satisfying the condition.

Looping upwards

The for loop starts with the for keyword followed by parentheses. In it, we define a start value, a run condition and a way to get from the start value to a value that doesn't meet the run condition.

for (int i = 1; i <= 4; i++) {
 System.out.print(i);
}

//Output Below

1234

Yass! The control variable i changes its value every time the loop is executed: from 1 to 2 to 3 and so on, until the run condition becomes false.

Looping downwards

Last time, we've increased the control variable i after each run. This time, let's decrease it by 1 when we loop through this loop!

for (int i = 5; i > 0; i--) {
 System.out.print(i);
}

//Output Below

54321

Nice! Remember, besides i--', we can also use  i -= 1 or the full version of i = i - 1' to decrease i.

Growing strings

Here's a for loop with a string that grows every time the loop, well, loops.

int sum = 0;
String log = "0";
for (int i = 1; i < 3; i++) {
 sum += i;
 log += "+" + i;
}
System.out.print(log + "=" + sum);

//Output Below

0+1+2=3

The control variable i gets added to sum every time the for loop is executed; the growing-string log keeps record.

Fibonacci numbers

Have you ever heard of the Fibonacci numbers? That's a sequence of numbers where every number is the sum of the previous two numbers.

int a = 1;
int b = 1;
System.out.print(a + "-" + b);
for (int i = 1; i < 5; i++) {
 int c = a + b;
 a = b;
 b = c;
 System.out.print("-" + c);
}

//Output Below

1-1-2-3-5-8

Sweet! With for loops, it's easy to create all sorts of sequences like the Fibonacci numbers.

Iterating over arrays

We can also use an enhanced for loop to go through, or iterate over, the elements of an array.

String[] friends = { "Harry",
 "Ron", "Hermione" };
for (String f : friends) {
 System.out.print(f + "; ");
}

//Output Below

Harry; Ron; Hermione; 

Great! For every iteration, f points to a different element of friends.

Psst: this concept is also known as the foreach loop.

Iterating over HashMaps

Since HashMaps are quite different from arrays, we can't iterate over them in the same way. Let's try go through the keys of a HashMap!

HashMap<String, String> people;
people = new HashMap<>();
people.put("Harry", "Seeker");
people.put("Ginny", "Chaser");

for (String k : people.keySet()) {
 String s = k + ": ";
 s += people.get(k) + "; ";
 System.out.print(s);
}

//Output Below

Ginny: Chaser; Harry: Seeker;

If you need the values without any keys, you can also use 'people.values()'.

Nested loops

We can also put loops inside other loops, creating a so-called nested loop.

for (int x = 1; x < 5; x++) {
 System.out.print(x + ": ");
 int y = x;
 while (y <= 4) {
  System.out.print(y);
  y++;
 }
 System.out.print("; ");
}

//Output Below

1: 1234; 2: 234; 3: 34; 4: 4;

Sweet! The for loop simply runs from 1 to 4. The while loop, however, restarts in every iteration of the for loop, running four times from x to 4.

Psst: don't worry you can't wrap your head around nested loops yet. You'll get the hang of it!

Space adventure #9

"Sam" is ready to explore the "Cha" system. This time, however, she is going to take a structured approach.

Create a HashMap for the planets in the system and their relative distance from the system's sun. Then go through the HashMap and select the planet that's closest to the sun.

Alright, let's go to "Risa"!

HashMap<String, Integer> planets;
planets = new HashMap<>();
planets.put("Andoria", 9415);
planets.put("Risa", 5284);
planets.put("Vulcan", 6820);

String minDestination = "";
int minDistance = 0;
for (String k : planets.keySet()) {
 if (minDistance == 0 ||
  planets.get(k) < minDistance) {
   minDestination = k;
   minDistance = planets.get(k);
  }
}
System.out.print(minDestination);

//Output Below

Risa

Printing

A method is a named block of code that serves a specific purpose. In order to call a method, we use its name followed by parentheses.

String quote = "None shall pass!";
System.out.print(quote);

System.out.print(), which we've used quite a lot, is a great example of a method.

Creating methods

There are many built-in methods in Java but we can also create methods ourselves.

// Outside of main():
void sayHi() {
 String name = "Elliot Alderson";
 System.out.print("Hi " + name);
}
// Within main():
sayHi();

//Output Below

Hi Elliot Alderson

A method's declaration needs a return type (or void if it doesn't return anything), a name and parentheses. The code block in the braces is executed when we call the method.

Psst: we need to put these methods outside of main() but call them from main().

Why methods?

If we want to use a block of code more often, it's a good idea to put it in a method. Once it's written, we can reuse it whenever we want.

We also need to make sure we call the method correctly. How would you call the triple() method?

// Outside of main():
void triple(int number) {
 System.out.print(number * 3);
}

// Within main():
triple(8);

//Output Below

24

Variables found in the parentheses of a method are called parameters. When calling a method, we need to use parameters of the right type.

More parameters

Check this out: we can use more than just a single parameter.

void sayHi(String p1, String p2) {
 String s = "Hi " + p1
  + "! Hi " + p2 + "!";
 System.out.print(s);
}

sayHi("Ben", "Luke");

//Output Below

Hi Ben! Hi Luke!

If we use multiple parameters, we simply separate them with commas.

Returning results

Sometimes it makes sense to return the result of a method.

int triple(int number) {
 int result = number * 3;
 return result;
}

int myNumber = triple(13);
System.out.print(myNumber);

//Output Below

39

Great job! Whenever we want to return something, for example a result of a calculation, we need to use the return value's type instead of void.

Arrays

We can also pass an array to a method.

void sayHi(String[] people) {
 String output = "";
 for (String p : people) {
  output += "Hi " + p + "! ";
 }
 System.out.print(output);
}

String[] myFriends = { "Ben",
 "Luke" };
sayHi(myFriends);

//Output Below

Hi Ben! Hi Luke! 

Sweet! Using arrays as parameters is quite easy!

...

Sometimes, however, we don't know exactly how many values, or arguments, we need to pass to a method.

Let's figure out how to make our method handle a variable number of arguments.

int totalize(int... numbers) {
 int result = 0;
 for (int n : numbers) {
  result += n;
 }
 return result;
}

int s = totalize(5) + totalize(4, 5, 15);
System.out.print(s);

//Output Below

29

Yass! We just used a method with two different sets of arguments. ... allows us to pass a variable number of arguments.

Psst: these arguments are treated as elements of an array.

Inception

We can also call a method within a method within a method. Some would say that's Inception.

// Outside of main():
int addFive(int number) {
 return number + 5;
}
void process(int[] myNumbers) {
 for (int n : numbers) {
  n = addFive(n);
  System.out.print(n + " ");
 }
}

// Within main():
int[] myNumbers = { 3, -4, 0 };
process(myNumbers);

//Output Below

8 1 5

Great! n and myNumbers don't even exist outside of the braces of the for loop and the process() method. That's called a scope.

Pass by value

Here's an important thing to notice: methods don't change the variables that they receive as arguments.

void addFive(int number) {
 number += 5;
 System.out.print(number);
}

int myNumber = 21;
addFive(myNumber);
System.out.print(" " + myNumber);

//Output Below

26 21

When we pass myNumber to addFive(), number takes on the value of myNumber. However, number only exists within addFive() and doesn't change the value of myNumber.

Space adventure #10

Now that "Sam" knows the distance to the planets in the "Cha" system, she wants to know the time it takes the spaceship to get there.

Create a method that takes the distance to a planet and the speed of travel to calculate and return the time it takes to travel the distance.

If those are minutes, "Sam" will get to "Risa" in no time.

static double calculateETA
(int distance, double speed) {
 return distance / speed;
}

double time = calculateETA(5284, 19.0);
System.out.print("ETA: " + time);

//Output Below

"ETA: 275.20833333333337"

Are you confused about the static keyword? No worries, we'll talk about it very soon!

Objects

It's time to talk about objects.

Java objects are similar to real-world things: they have properties and behavior. Take our dog friend "Baxter":

Dog myDog = new Dog();
myDog.name = "Baxter";
myDog.bark();

//Output Below

Woof!

Great! We can access these things through the myDog object, in which variables like name model properties and methods like bark() account for behavior.

Woof?

So-called classes are kind of like blueprints. In them, we define properties and behavior that objects of the same type have in common.

class Dog {
 String name;
 void bark() {
  System.out.print("Woof!");
 }
}

Great! We can introduce a class with the class keyword and a name that starts with an uppercase letter.

Constructors

Constructors are special methods that share their name with their class and get called whenever we create an instance of a class.

class Dog {
 String name;
 void bark() {
  System.out.print("Woof!");
 }

 Dog() {
  bark();
 }
}

Dog myDog = new Dog();
myDog.name = "Baxter";

//Output Below

Woof!

Good stuff! When we use new Dog(), we call the constructor of the Dog class and, therefore, trigger bark().

Psst: myDog is an instance and, as such, represents a specific object: the one-and-only "Baxter".

Parameters

A constructor can also take parameters, which makes it a great place to set initial values.

class Dog {
 String name;
 void bark() {
  System.out.print("Woof!");
 }

 Dog(String name) {
  this.name = name;
  bark();
 }
}

Dog myDog = new Dog("Baxter");

//Output Below

Woof!

Good stuff! The this keyword stands for the instance of the class and helps us distinguish between the name parameter and the name variable.

Inheriting

Dogs share some of their properties and behavior with other animals.

class Animal {
 int age = 0;
 void eat() {
  System.out.print("Munch!");
 }
}

class Dog extends Animal {
 String name;
 void bark() {
  System.out.print("Woof!");
 }

 Dog(String name) {
  super();
  this.name = name;
  bark();
 }
}

Yup! Dog is a subclass of Animal. A subclass inherits everything from its superclass. In the subclass constructor, we need to call the superclass constructor using super().

Inherited variables

A subclass can use the variables it inherits from its superclass.

class Animal {
 int age = 0;
 void eat() {
  System.out.print("Munch!");
 }
}

class Dog extends Animal {
 String name;
 void bark() {
  System.out.print("Woof!");
 }

 Dog(String name, int age) {
  super();
  this.name = name;
  this.age = age;
  bark();
 }
}

Great! We can access and use inherited variables just like class variables.

Psst: we don't have to use this if the properties and the parameters have different names.

Inherited methods

Of course the same is true for methods.

class Animal {
 int age = 0;
 void eat() {
  System.out.print("Munch!");
 }
}

class Dog extends Animal { ... }

Dog myDog = new Dog("Baxter", 5);
myDog.eat();

//Output Below

Munch!

A subclass has access to the variables and methods that it inherits from its superclass.

Overriding

Sometimes it's necessary or at least useful for a subclass to adapt an inherited method to its needs.

class Animal {
 void eat() {
  System.out.print("Munch!");
 }
}

class Dog extends Animal {
 void eat() {
  System.out.print("Eat a doggie snack");
 }
}

Dog myDog = new Dog();
myDog.eat();

//Output Below

Eat a doggie snack

Overriding an inherited method is easy: we just rewrite it the way we want it to be.

Accessing methods

When we override a method, the original method becomes hidden. Still, there's a way to access it.

class Animal {
 void eat() {
  System.out.print("Munch!");
 }
}

class Dog extends Animal {
 void eat() {
  super.eat();
  System.out.print("Chomp!");
 }
}

Dog myDog = new Dog();
myDog.eat();

//Output Below

Munch!Chomp!

Nice! Calling the original method is useful when there's some generic behavior in it that we'd like to have in the subclass as well.

Space adventure #11

"Sam" couldn't go anywhere without "NX-01", her spaceship. Even though it's a unique model, its features are similar to those of other spaceships.

Create a class for spaceships like "NX-01" with a constructor that sets the type, fuel and water variables. Then create an instance for "NX-01".

class Spaceship {
 String type;
 int fuel = 100;
 int water = 10;
 Spaceship(String type) {
  this.type = type;
 }
}

Spaceship nx01;
nx01 = new Spaceship("NX-01");

Isn't she a beauty?

Compendium

A class bundles variables and methods to represent an object.

class Spaceship {
 int fuel = 1000
 int mileage = 0;
 void move(int lightyears) {
  fuel -= 2 * lightyears;
  mileage += lightyears;
  System.out.print("Swoosh!");
 }
}

Spaceship myShip = new Spaceship();
myShip.move(5);

Classes are great things: they're another powerful concept that we can use to make the code we write more reusable and understandable.

The ugly truth

Alright, let's bring these things together!

In Java, everything we write needs to be in a class.

class SpaceAdventure {
 public static void main 
 (String[] args) {
  String output = "To infinity";
  output += " and beyond!";
  System.out.print(output);
 }
}

//Output Below

To infinity and beyond!

Great! That's why we wrote everything in the class and main() method that we created at the very beginning.

Main

Every Java program needs an entry point, which is what the main() method provides. In order to work, it needs to be in a class and look exactly like this:

class SpaceAdventure {
 public static void main 
 (String[] args) {
  // ...
 }
}

If you've been wondering about what public, static and the args array mean for the past chapters, this chapter is for you.

Another welcome

Whatever we're up to, we need a main() method to pull it off. Take the very beginning:

class MyApp {
 public static void main 
 (String[] args) {
  String greeting = "Hello";
  System.out.print(greeting + " world");
 }
}

//Output Below

Hello world!

None of this would have been possible without main().

Arg(h)s

Before we talk about modifiers, let's have a look at the args array!

In order to work, main() needs to have a string array as a parameter. But why?

class MyApp {
 public static void main 
 (String[] args) {
  System.out.print(args.length);
 }
}

//Output Below

0

As it turns out, we can pass arguments to a program when we launch it, at which point they'll be stored in args. In most cases, however, args will be empty.

Baxter and main

Now that we know about the main() method, let's explore how it connects with classes!

class Playground {
 public static void main 
 (String[] args) {
  Dog myDog = new Dog("Baxter");
  myDog.bark();
 }
}

//Output Below

Woof!
class Dog {
 String name;
 void bark() {
  System.out.print("Woof!");
 }

 Dog(String name) {
  this.name = name;
 }
}

Sweet! We could define both classes in the same .class file but it's a much better idea to add a separateDog.classfile to the project.

Static

Alright let's talk about the static keyword!

Variables and methods that have static in their introduction belong to the class instead of a specific instance.

0class MyApp {
 public static void main 
 (String[] args) {
  int myNumber = triple(2);
  System.out.print(myNumber);
 }
 static int triple(int number) {
  return number * 3;
 }
}

//Output Below

6

Good stuff! Because triple() is a static method, we can use it without creating an instance of MyApp.

Psst: did you notice that we never created an instance of System before we used the print() method? Well, that's because print() is also static.

The alternative

So, what if triple() wasn't a static method?

class MyApp {
 public static void main 
 (String[] args) {
  MyApp a;
  a = new MyApp();
  int myNumber = a.triple(2);
  System.out.print(myNumber);
 }
 int triple(int number) {
  return number * 3;
 }
}

See that? We'd need an instance of the MyApp class in order to use triple(). That'd be very inconvenient as it never uses any variables of the a instance.

Utility methods

In case it makes sense to call a variable or method even if we didn't create an instance of its class, it's smart to make it static.

class MyApp {
 public static void main 
 (String[] args) {
  double mpg = 26.9;
  double kpl = Car.convert(mpg);
  System.out.print(kpl);
 }
}

//Output Below

11.4363657183
class Car {
 // Convert MPG to KM per Liter:
 static double convert(double m) {
  return m * 0.425143707; 
 }
}

That's especially true for utility methods, which don't need instance variables or methods.

Private

Psst: some variables and methods don't want to be disturbed. How about we give them some privacy?

class Playground {
 public static void main 
 (String[] args) {
  Dog myDog = new Dog("Baxter");
  myDog.eat();
 }
}
class Dog {
 private int hunger = 10;
 void eat() {
  if (hunger > 0) {
   hunger--;
  }
 }
}

Perfect! By adding the private keyword to hunger, we're shielding it from being accessed from outside of its scope, the Dog class.

Publicity

In other cases, we might want a variable or method to be accessible from any other class.

class Dog {
 public String name;
 private int hunger = 10;
 void eat() {
  if (hunger > 0) {
   hunger--;
  }
 }
}

Sweet! By adding public before the declaration, any other class in the project can access name.

Psst: public and private are so-called modifiers. If we skip them, variables and methods are package-private, which is somewhere in between.

Space adventure #12

Traveling the "Wej" system, "Sam" has a secret message to transmit to her friend "Jar". Unfortunately, the system's government is very nosy.

Create a class with the secret message and include a method that takes a reader parameter and returns the message for nobody else but "Jar".

class Message {
 private String message;
 public String readMessage
 (String reader) {
  if (reader.equals("Jar")) {
   System.out.print("Access granted");
   return message;
  } else {
   System.out.print("Access denied");
  }
 }
}

That way, nobody except "Jar" can read the message.

Compendium

In Java, everything needs to be in a class and every program needs a class with a main()method.

class MyGame {
 public static void main
 (String[] args) {
  Hero myHero = new Hero("Thrall");
  myHero.levelUp();
 }
}
class Hero {
 public String name;
 private int level;
 public Hero() {
  this.name = name;
  this.level = 1;
 }
 public void levelUp() {
  if (level < 100) {
   level++;
  }
 }
}

Also, we can restrict access to variables and methods with modifiers.

Introduction

Hello there and welcome, we'll be setting up to begin coding in a programming language called Java.Java is a language of choice for developers of all kinds.

We'll talk more about it later so let's get into setting up.

What we'll need

Firstly we'll need to install JDK(Java Development Kit).

Download the development kit for Windows, for Linux.

Once you've installed the JDK download on your computer, set up should be complete.

If you want to develop web applications, you need to use either the NetBeans IDE , Sun Java Studio Creator IDE, or Sun Java Studio Enterprise in addition to the JDK, as these environments provide a web server that's necessary for creating and testing servlets, JavaServer Pages, and database connections.

Luckily the JDK that comes bundled with the NetBeans IDE.

If you downloaded the JDK with the NetBeans IDE, start NetBeans, and begin programming.

Now type your program into the IDE and save as anyName.java. To run this program we need to compile it first, to do that, open the location where your program is in terminal or shell and enter

javac anyName.java

to compile it.


And enter

java anyName.java

to run it