An Introduction to Java
By: Ariel Jakubowski
Tags: Java, Java Programming, Guides And Tutorials, Programming, Coding

Java is one of the most popular programming languages in the world. Java is a general programming language that is often used to create object oriented code. It is designed to make the implementation of code simple for developers and it has few dependencies for implementation.

The Basics

Semicolons are written at the end of each statement, which is a line of code that performs an action. The semicolon marks the end of a command and if a semicolon is not included at the end of a statement, the code will not run properly.

Code will often be written inside of curly braces {}. Curly braces are used to denote the scope of a function, class, or another block of code. A semicolon is not necessary after code that is written inside curly braces.

One important thing to know is how to print a piece of information out to the system. To do this, the following format is used.

System.out.println( what you want to print );

Comments

Single line comments begin with //.

Multiline comments are enveloped within /* and */. This syntax can also be used to put a comment within a line of code.

// This is a comment.

/* This is also a comment. */

Variables and Data Types

When declaring a variable in Java, special keywords are used to specify the type of variable. Some, but not all, of these special keywords represent primitive data types. These are the simplest types of data and they have no built in behavior. These data types are as follows.

int: Int is a shortening of integer. It is used to represent whole numbers. These whole numbers can be either positive or negative. It also can be used to represent zero. It is important to note that not all whole numbers can be used with int. Only whole numbers between -2,147,483,648 and 2,147,483,647 can be used.

long: Long works in a similar way to int. It is also used to represent whole numbers which can be either positive or negative. It also can be used to represent zero. Long differs from int because it can store large numbers that are outside the range offered by int.

double: Double is also used with numbers, although it allows for much greater range than int. It is used with numbers that have decimals and can also be used for numbers outside of the -2,147,483,648 and 2,147,483,647 range of int. The largest value that can be used with double is positive or negative 1.7976931348623157 E+308. The smallest value is 4.9 E-324.

boolean: A boolean can be either true or false.

char: Char is short for character. A character can be a letter, a space, or a punctuation mark. Only one character is written in a char, so ‘a’ is a char but ‘be’ is not. The value for a char variable must be written between single quotation marks. It is important to note that in Java, a char must be written in single quotes or else the code will not run properly.

void: Void represents a lack of information. It is used when something does not have a value and when a method is not expected to return any value.

String: Unlike other data types, a string is not a primitive, it is an object. Objects are more complex and they do have built in behavior. When declaring variables, the string keyword is capitalized, as opposed to the primitive keywords, which are not.

A string is plain text. It holds a sequence of characters. When the value of a string is assigned, it is written between double quotation marks.

Variables are declared and defined using the following format. Variables can be reassigned using the same format.

Keyword variableName = variableValue; int num1 = 4;

double num2 = 2.5;

String color = “yellow”;

Operators

Java calculates basic addition, subtraction, multiplication, and division. It also calculates the remainder of an expression, using the modulus operator. Java follows the normal order of operations. To determine if two things are equal, == is used and to determine if two things are not equal, != is used. Java can also determine if something is greater than something else (>), greater than or equal to something else (>=), less than something else (<), or less than or equal to something else (<=).

In other programming languages, these equality operators can be used to determine if data types that are not numbers are equivalent. This is not the case in Java. Instead, the .equals() operator is used.

String s1 = “A string”;

String s2 = “Another string”;

String s3 = “A string”; s1.equals(s2);

//false s1.equals(s3);

//true

Conditional logic

There are many times when a program needs to make a decision. Conditional logic is used to accomplish this. When a program uses conditional logic, it first checks if a condition is true. If the condition is true, the program executes a particular block of code. To do this, an if statement is used. If statements are formatted as follows.

if (condition to be checked) {

//Code to be executed

}

For example, if we want to know if we should eat, we could use an if statement to help us.

if (mood == “hungry”) {

System.out.println(“I’m going to eat.”);

}

The condition in the if statement above says that if I am hungry, I will eat. We can expand this decision making process by adding an else statement. An else statement accompanies an if statement and it tells the program what to do if the condition that we are testing for is not true.

if (mood == “hungry”) {

System.out.println(“I’m going to eat.”);

}else{

System.out.println(“I’m not going to eat.”)

}

The if/else statement above says that if my mood is hungry then I will eat and if I am not hungry, I will not eat. Else statements are often used to create a default case so that if none of the conditions that the program checks are true then the program will default to a particular block of code.

The if/else statement can further be expanded on by adding other conditions to test for. Instead of simply making a program to tell me if I should eat or not, we can make a program to tell me what to do no matter how I am feeling. The code below checks for my mood and recommends something to do depending on how I am feeling. If the program detects that I am hungry, it tells me to eat, if it detects that I am tired, it tells me to take a nap, if it detects that I am thirsty, it tells me to drink water. If the way I’m feeling does not match any of the options that are built into the program, it tells me to pet my dog.

if (mood == “hungry”) {

System.out.println(“Eat something.”);

}else if (mood == “tired”) {

System.out.println(“Take a nap.”);

}else if (mood == “thirsty”) {

System.out.println(“Drink water.”);

}else{

System.out.println(“Pet your dog!”);

}

The statement above can also be created using a switch statement. A switch statement works in a similar way, checking to see if a test criteria matches any of the test cases that are built into the program. If the switch statement finds a match, it executes the code accordingly. If it does not find a match, it executes default code.

switch (mood) {

case “hungry”:

System.out.println(“Eat something.”);

break;

case “tired”:

System.out.println(“Take a nap.”);

break;

case “thirsty”:

System.out.println(“Drink water.”);

break;

default:

System.out.println(“Pet your dog.”);

}

Arrays

Arrays can hold multiple pieces of information. It may be helpful to think of an array as a list. In Java, an array can only hold values of one data type. This means that in Java, an array will consist entirely of values that are ints or entirely of values that are booleans, but it will not contain values of both data types. Arrays can also contain values of any other primitive data type and they can contain Strings and objects.

Each element in an array has an index, which represents where in the array this element occurs. Array indexes start at 0.

Arrays are created in Java using the following format.

datatype arrayName = {element1, element2, element3}; String[] words = {“This”, “is”, “an”, “array”};

int numbers = {1, 2, 3, 4};

Array Methods

When working with arrays in Java, there is an Arrays package with methods that will be very helpful to have available. This package can be imported into our file by putting the following code at the top of the file.

import java.util.Arrays;

Doing this will provide many methods that will be useful in working with arrays. For example, if we want to print out one of the arrays from the example code above, we will not see {“This”, “is”, “an”, “array”} or {1, 2, 3, 4}. We will instead see the memory address of the array. This will be no help in understanding or working with an array. Array methods from this package will need to be used within our code.

One of these useful methods is Arrays.toString(). When an array is passed into this method, the contents of that array are printed out.

Elements in an array can be accessed using their index. For example, let’s use the words array from above.

Words[0];

// “This”

This method can be used to alter specific elements in an array. The third element in the array can be reassigned using the following.

words[2] = “very”;

//words = {“This”, “is”, “very”, “array”}

To determine how many elements are in an array, add “.length” to the end of an array’s name. An important thing to note about the length of an array is that once an array is created, its length can not be changed. Elements of the array can be altered, but they can not be added or removed.

Words.length

//4

ArrayLists

Java also features ArrayLists, which are similar to arrays, but more dynamic. Like arrays, ArrayLists store elements that are of the same data type and they allow elements to be accessed by index. However, unlike arrays, ArrayLists allow elements to be added and removed.

As with arrays, there is an ArrayLists package that when imported, provides methods that will be very helpful to have available when working with ArrayLists. These methods can be imported by adding the following code to the top of the file.

import java.util.ArrayList;

ArrayLists are created in Java using the following format.

ArrayList <datatype> ArrayListName = {element1, element2, element3}; ArrayList<Integer> numbers = new ArrayList<Integer>();

Unlike when working with arrays, instead of using the primitive data type keywords, when working with ArrayLists, a generic is used. Generics are used in Java to define objects and classes as parameters of ArrayLists. String remains String but int becomes Integer, double becomes Double, and char becomes Char.

To add an element to an ArrayList, the following format is used.

ArrayListName.add(elementToBeAdded);

Especially when working with something that can always be changing in size, it is important to be able to keep track of how many elements you are working with. The following code can be used to determine how many elements are in an ArrayList.

ArrayList.size()

ArrayList Methods

When accessing elements in arrays, index notation is used. This does not work with ArrayLists. Instead, there is a method, get, which is used to access an index. As with normal arrays, the indices for ArrayLists start at 0. The format for using this method is as follows.

ArrayListName.get(index);

A similar method, set, can be used to change the elements in an ArrayList.

ArrayListName.set(index, newValue);

When removing an element from an ArrayList, the index or value of the element to be removed can be used along with the following format.

ArrayListName.remove(index);

ArrayListName.remove(value);

To determine the index of a specific element, the following code can be used.

ArrayListName.indexOf(value);

Loops

Loops allow the same block of code to be repeated when a condition is met. In Java, there are three main types of loops, for loops, while loops, and for-each loops.

While loops are written as follows. They execute a block of code while a specified condition is true and stop running that code when the condition is false.

while (condition) {

//Code to be executed

}

When working with loops, it is common and extremely helpful to use an iterator. An iterator is a variable that is incremented each time a loop is executed and is often used in the conditional logic that tells a loop to stop executing.

A for loop is another type of loop. For loops have incrementing built into them. A for loop is written in the following format.

for (int i = 0; i < 10; i++) {

//Code to be executed

}

There are three parts of the code that is in the parentheses. The first part initializes an iterator, the second part defines the condition that will allow the loop to run, and the third part determines how the iterator will be incremented.

The example above initializes an iterator, called i, with an initial value of 0, tells the code to stop looping when i reaches a value of 10, and increments i by 1 each time a loop executes.

A type of array that is helpful when working with arrays and ArrayLists is the for-each loop. A for-each loop cycles through an array or ArrayList and performs some action on every single element. For-each loops are written using the following formula.

for (datatype element : list) {

//Code to be executed

}

For example, if we had a list of dogs and wanted to print out each one, this is how we would do so.

for (String dog : dogs) {

System.out.println(dog);

}

Working with Strings

Concatenation

Concatenation of strings means joining multiple strings together.

The + operator is one possible and popular method used to achieve concatenation.

String color = “blue”;

String favColor = “My favorite color is “ + color + “.”;

//My favorite color is blue.

There are many functions built into Java that can be used to easily manipulate strings. Below is a basic guide to some of the most popular string functions. For examples, we will work with the following strings.

String hi = “Hello ”;

String world = “World”;

length: The length method returns the number of characters in a string.

hi.length()

//6

concat: This method concatenates strings.

hi = hi.concat(“everyone”);

//”Hello everyone”

hi = hi.concat(world);

//”Hello World”

charAt: This method returns the character at a specified index of a string. As with arrays, the index starts at 0.

hi.charAt(1);

//”e”

substring: This method allows a part of a string to be extracted from a larger string.

string.substring(starting character, ending character); hi.substring(1,4);

//”ello”

toUpperCase: This method capitalizes each character in a string.

toLowerCase: This method converts each character in a string to lowercase.

Conclusion

I hope this guide has been helpful in learning the basics of programming in Java. To learn about object oriented programming in Java, check out this blog post.